Debian Codegraph @

gcc/d/dmd/location.d

raw
1 /**
2 * Encapsulates file/line/column locations.
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/location.d, _location.d)
8 * Documentation: https://dlang.org/phobos/dmd_location.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/location.d
10 */
11
12 module dmd.location;
13
14 import core.stdc.stdio;
15
16 import dmd.common.outbuffer;
17 import dmd.root.array;
18 import dmd.root.filename;
19 import dmd.root.string: toDString;
20
21 /// How code locations are formatted for diagnostic reporting
22 enum MessageStyle : ubyte
23 {
24 digitalmars, /// filename.d(line): message
25 gnu, /// filename.d:line: message, see https://www.gnu.org/prep/standards/html_node/Errors.html
26 sarif /// JSON SARIF output, see https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html
27 }
28 /**
29 A source code location
30
31 Used for error messages, `__FILE__` and `__LINE__` tokens, `__traits(getLocation, XXX)`,
32 debug info etc.
33 */
34 struct Loc
35 {
36 private uint index = 0; // offset into lineTable[]
37
38 // FIXME: This arbitrary size increase is needed to prevent segfault in
39 // runnable/test42.d on Ubuntu x86 when DMD was built with DMD 2.105 .. 2.110
40 // https://github.com/dlang/dmd/pull/20777#issuecomment-2614128849
41 version (DigitalMars) version (linux) version (X86)
42 private uint dummy;
43
44 static immutable Loc initial; /// use for default initialization of Loc's
45
46 extern (C++) __gshared bool showColumns;
47 extern (C++) __gshared MessageStyle messageStyle;
48
49 nothrow:
50
51 /*******************************
52 * Configure how display is done
53 * Params:
54 * showColumns = when to display columns
55 * messageStyle = digitalmars or gnu style messages
56 */
57 extern (C++) static void set(bool showColumns, MessageStyle messageStyle)
58 {
59 this.showColumns = showColumns;
60 this.messageStyle = messageStyle;
61 }
62
63 /// Returns: a Loc that simply holds a filename, with no line / column info
64 extern (C++) static Loc singleFilename(const char* filename)
65 {
66 Loc result;
67 locFileTable ~= new BaseLoc(filename.toDString, null, locIndex, 0, [0]);
68 result.index = locIndex++;
69 return result;
70 }
71
72 /// utf8 code unit index relative to start of line, starting from 1
73 extern (C++) uint charnum() const @nogc @safe
74 {
75 return SourceLoc(this).column;
76 }
77
78 /// line number, starting from 1
79 extern (C++) uint linnum() const @nogc @trusted
80 {
81 return SourceLoc(this).line;
82 }
83
84 /// Advance this location to the first column of the next line
85 void nextLine()
86 {
87 const i = fileTableIndex(this.index);
88 const j = locFileTable[i].getLineIndex(this.index - locFileTable[i].startIndex);
89 if (j + 1 < locFileTable[i].lines.length)
90 index = locFileTable[i].startIndex + locFileTable[i].lines[j + 1];
91 }
92
93 /***
94 * Returns: filename for this location, null if none
95 */
96 extern (C++) const(char)* filename() const @nogc
97 {
98 if (this.index == 0)
99 return null;
100
101 const i = fileTableIndex(this.index);
102 if (locFileTable[i].substitutions.length > 0)
103 {
104 const si = locFileTable[i].getSubstitutionIndex(this.index - locFileTable[i].startIndex);
105 const fname = locFileTable[i].substitutions[si].filename;
106 if (fname.length > 0)
107 return fname.ptr;
108 }
109
110 return locFileTable[i].filename.ptr;
111 }
112
113 extern (C++) const(char)* toChars(
114 bool showColumns = Loc.showColumns,
115 MessageStyle messageStyle = Loc.messageStyle) const nothrow
116 {
117 return SourceLoc(this).toChars(showColumns, messageStyle);
118 }
119
120 /// Returns: byte offset into source file
121 uint fileOffset() const
122 {
123 const i = fileTableIndex(this.index);
124 return this.index - locFileTable[i].startIndex;
125 }
126
127 /// Returns: this location as a SourceLoc
128 extern (C++) SourceLoc toSourceLoc() const @nogc @safe
129 {
130 return SourceLoc(this);
131 }
132
133 /**
134 * Checks for equivalence by comparing the filename contents (not the pointer) and character location.
135 *
136 * Note:
137 * - Uses case-insensitive comparison on Windows
138 * - Ignores `charnum` if `Columns` is false.
139 */
140 extern (C++) bool equals(Loc loc) const
141 {
142 SourceLoc lhs = SourceLoc(this);
143 SourceLoc rhs = SourceLoc(loc);
144 return (!showColumns || lhs.column == rhs.column) &&
145 lhs.line == rhs.line &&
146 FileName.equals(lhs.filename, rhs.filename);
147 }
148
149 /**
150 * `opEquals()` / `toHash()` for AA key usage
151 *
152 * Compare filename contents (case-sensitively on Windows too), not
153 * the pointer - a static foreach loop repeatedly mixing in a mixin
154 * may lead to multiple equivalent filenames (`foo.d-mixin-<line>`),
155 * e.g., for test/runnable/test18880.d.
156 */
157 extern (D) bool opEquals(ref const(Loc) loc) const @trusted nothrow @nogc
158 {
159 return this.index == loc.index;
160 }
161
162 /// ditto
163 extern (D) size_t toHash() const @trusted nothrow
164 {
165 return hashOf(this.index);
166 }
167
168 /******************
169 * Returns:
170 * true if Loc has been set to other than the default initialization
171 */
172 bool isValid() const pure @safe
173 {
174 return this.index != 0;
175 }
176 }
177
178 /**
179 * Format a source location for error messages
180 *
181 * Params:
182 * buf = buffer to write string into
183 * loc = source location to write
184 * showColumns = include column number in message
185 * messageStyle = select error message format
186 */
187 void writeSourceLoc(ref OutBuffer buf,
188 SourceLoc loc,
189 bool showColumns,
190 MessageStyle messageStyle) nothrow
191 {
192 if (loc.filename.length == 0)
193 return;
194 buf.writestring(loc.filename);
195 if (loc.line == 0)
196 return;
197
198 final switch (messageStyle)
199 {
200 case MessageStyle.digitalmars:
201 buf.writeByte('(');
202 buf.print(loc.line);
203 if (showColumns && loc.column)
204 {
205 buf.writeByte(',');
206 buf.print(loc.column);
207 }
208 buf.writeByte(')');
209 break;
210 case MessageStyle.gnu: // https://www.gnu.org/prep/standards/html_node/Errors.html
211 buf.writeByte(':');
212 buf.print(loc.line);
213 if (showColumns && loc.column)
214 {
215 buf.writeByte(':');
216 buf.print(loc.column);
217 }
218 break;
219 case MessageStyle.sarif: // https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html
220 // No formatting needed here for SARIF
221 break;
222 }
223 }
224
225 /**
226 * Describes a location in the source code as a file + line number + column number
227 *
228 * While `Loc` is a compact opaque location meant to be stored in the AST,
229 * this struct has simple modifiable fields and is used for printing.
230 */
231 struct SourceLoc
232 {
233 const(char)[] filename; /// name of source file
234 uint line; /// line number (starts at 1)
235 uint column; /// column number (starts at 1)
236 uint fileOffset; /// byte index into file
237
238 /// Index `fileOffset` into this to to obtain source code context of this location
239 const(char)[] fileContent;
240
241 // aliases for backwards compatibility
242 alias linnum = line;
243 alias charnum = column;
244
245 this(const(char)[] filename, uint line, uint column, uint fileOffset = 0, const(char)[] fileContent = null) nothrow @nogc pure @safe
246 {
247 this.filename = filename;
248 this.line = line;
249 this.column = column;
250 this.fileOffset = fileOffset;
251 this.fileContent = fileContent;
252 }
253
254 this(Loc loc) nothrow @nogc @trusted
255 {
256 if (loc.index == 0 || locFileTable.length == 0)
257 return;
258
259 const i = fileTableIndex(loc.index);
260 this = locFileTable[i].getSourceLoc(loc.index - locFileTable[i].startIndex);
261 }
262
263 extern (C++) const(char)* toChars(
264 bool showColumns = Loc.showColumns,
265 MessageStyle messageStyle = Loc.messageStyle) const nothrow
266 {
267 OutBuffer buf;
268 writeSourceLoc(buf, this, showColumns, messageStyle);
269 return buf.extractChars();
270 }
271
272 bool opEquals(SourceLoc other) const nothrow
273 {
274 return this.filename == other.filename && this.line == other.line && this.column == other.column;
275 }
276
277 }
278
279 /// Given the `index` of a `Loc`, find the index in `locFileTable` of the corresponding `BaseLoc`
280 private size_t fileTableIndex(uint index) nothrow @nogc
281 {
282 // To speed up linear find, we cache the last hit and compare that first,
283 // since usually we stay in the same file for some time when resolving source locations.
284 // If it's a different file now, either scan forwards / backwards
285 __gshared size_t lastI = 0; // index of last found hit
286
287 size_t i = lastI;
288 if (index >= locFileTable[i].startIndex)
289 {
290 while (i + 1 < locFileTable.length && index >= locFileTable[i+1].startIndex)
291 i++;
292 }
293 else
294 {
295 while (index < locFileTable[i].startIndex)
296 i--;
297 }
298
299 lastI = i;
300 return i;
301 }
302
303 /**
304 * Create a new source location map for a file
305 * Params:
306 * filename = source file name
307 * fileContent = content of source file
308 * Returns: new BaseLoc
309 */
310 BaseLoc* newBaseLoc(const(char)* filename, const(char)[] fileContent) nothrow
311 {
312 locFileTable ~= new BaseLoc(filename.toDString, fileContent, locIndex, 1, [0]);
313 // Careful: the endloc of a FuncDeclaration can
314 // point to 1 past the very last byte in the file, so account for that
315 locIndex += fileContent.length + 1;
316 return locFileTable[$ - 1];
317 }
318
319 /**
320 Mapping from byte offset into source file to line/column numbers
321
322 Consider this 4-line 24 byte source file:
323
324 ---
325 app.d
326 1 struct S
327 2 {
328 3 int y;
329 4 }
330 ---
331
332 Loc(0) is reserved for null locations, so the first `BaseLoc` gets `startIndex = 1`
333 and reserves 25 possible positions. Loc(1) represents the very start of this source
334 file, and every next byte gets the next `Loc`, up to Loc(25) which represents the
335 location right past the very last `}` character (hence it's 1 more than the file
336 size of 24, classic fence post problem!).
337
338 The next source file will get `Loc(26) .. Loc(26 + fileSize + 1)` etc.
339
340 Now say we know that `int y` has a `Loc(20)` and we want to know the line and column number.
341
342 First we find the corresponding `BaseLoc` in `locFileTable`. Since 20 < 26, the first `BaseLoc`
343 contains this location. Since `startIndex = 1`, we subtract that to get a file offset 19.
344
345 To get the line number from the file offset, we binary search into the `lines` array,
346 which contains file offsets where each line starts:
347
348 `locFileTable[0].lines == [0, 9, 11, 22, 24]`
349
350 We see 14 would be inserted right after `11` at `lines[2]`, so it's line 3 (+1 for 1-indexing).
351 Since line 3 starts at file offset 11, and `14 - 11 = 3`, it's column 4 (again, accounting for 1-indexing)
352
353 #line and #file directives are handled with a separate array `substitutions` because they're rare,
354 and we don't want to penalize memory usage in their absence.
355 */
356 struct BaseLoc
357 {
358 @safe nothrow:
359
360 const(char)[] filename; /// Source file name
361 const(char)[] fileContents; /// Source file contents
362 uint startIndex; /// Subtract this from Loc.index to get file offset
363 int startLine = 1; /// Line number at index 0
364 uint[] lines; /// For each line, the file offset at which it starts. At index 0 there's always a 0 entry.
365 BaseLoc[] substitutions; /// Substitutions from #line / #file directives
366
367 /// Register that a new line starts at `offset` bytes from the start of the source file
368 void newLine(uint offset)
369 {
370 lines ~= offset;
371 }
372
373 /// Construct a `Loc` entry for the start of the source file + `offset` bytes
374 Loc getLoc(uint offset) @nogc
375 {
376 Loc result;
377 result.index = startIndex + offset;
378 return result;
379 }
380
381 /**
382 * Register a new file/line mapping from #file and #line directives
383 * Params:
384 * offset = byte offset in the source file at which the substitution starts
385 * filename = new filename from this point on (null = unchanged)
386 * line = line number from this point on
387 */
388 void addSubstitution(uint offset, const(char)* filename, uint line) @system
389 {
390 auto fname = filename.toDString;
391 if (substitutions.length == 0)
392 substitutions ~= BaseLoc(this.filename, null, 0, 0);
393
394 if (fname.length == 0)
395 fname = substitutions[$ - 1].filename;
396 substitutions ~= BaseLoc(fname, null, offset, cast(int) (line - lines.length + startLine - 2));
397 }
398
399 /// Returns: `loc` modified by substitutions from #file / #line directives
400 SourceLoc substitute(SourceLoc loc) @nogc
401 {
402 if (substitutions.length == 0)
403 return loc;
404
405 const i = getSubstitutionIndex(loc.fileOffset);
406 if (substitutions[i].filename.length > 0)
407 loc.filename = substitutions[i].filename;
408 loc.linnum += substitutions[i].startLine;
409 return loc;
410 }
411
412 /// Resolve an offset into this file to a filename + line + column
413 private SourceLoc getSourceLoc(uint offset) @nogc
414 {
415 const i = getLineIndex(offset);
416 const sl = SourceLoc(filename, cast(int) (i + startLine), cast(int) (1 + offset - lines[i]), offset, fileContents);
417 return substitute(sl);
418 }
419
420 private size_t getSubstitutionIndex(uint offset) @nogc
421 {
422 size_t lo = 0;
423 size_t hi = substitutions.length + -1;
424 size_t mid = 0;
425 while (lo <= hi)
426 {
427 mid = lo + (hi - lo) / 2;
428 if (substitutions[mid].startIndex <= offset)
429 {
430 if (mid == substitutions.length - 1 || substitutions[mid + 1].startIndex > offset)
431 return mid;
432
433 lo = mid + 1;
434 }
435 else
436 {
437 hi = mid - 1;
438 }
439 }
440 assert(0);
441 }
442
443 /// Binary search the index in `this.lines` corresponding to `offset`
444 private size_t getLineIndex(uint offset) @nogc
445 {
446 size_t lo = 0;
447 size_t hi = lines.length + -1;
448 size_t mid = 0;
449 while (lo <= hi)
450 {
451 mid = lo + (hi - lo) / 2;
452 if (lines[mid] <= offset)
453 {
454 if (mid == lines.length - 1 || lines[mid + 1] > offset)
455 return mid;
456
457 lo = mid + 1;
458 }
459 else
460 {
461 hi = mid - 1;
462 }
463 }
464 assert(0);
465 }
466 }
467
468 // Whenever a new source file is parsed, start the `Loc` from this index (0 is reserved for Loc.init)
469 private __gshared uint locIndex = 1;
470
471 // Global mapping of Loc indices to source file offset/line/column, see `BaseLoc`
472 private __gshared BaseLoc*[] locFileTable;