Debian Codegraph @

gcc/d/dmd/identifier.d

raw
1 /**
2 * Defines an identifier, which is the name of a `Dsymbol`.
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/identifier.d, _identifier.d)
8 * Documentation: https://dlang.org/phobos/dmd_identifier.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/identifier.d
10 */
11
12 module dmd.identifier;
13
14 import core.stdc.ctype;
15 import core.stdc.stdio;
16 import core.stdc.string;
17 import dmd.id;
18 import dmd.location;
19 import dmd.common.outbuffer;
20 import dmd.rootobject;
21 import dmd.root.string;
22 import dmd.root.stringtable;
23 import dmd.root.utf;
24 import dmd.tokens;
25
26
27 /***********************************************************
28 */
29 extern (C++) final class Identifier : RootObject
30 {
31 private const int value;
32
33 // Indicates if this is an identifier used for an anonymous symbol.
34 private const bool isAnonymous_ = false;
35
36 private const char[] name;
37
38 nothrow:
39
40 /// Construct an identifier from the given name.
41 extern (D) this(const(char)* name)
42 {
43 //printf("Identifier('%s', %d)\n", name, value);
44 this(name.toDString(), TOK.identifier);
45 }
46
47 /**
48 Construct an identifier from the given name.
49
50 Params:
51 name = the identifier name. There must be `'\0'` at `name[length]`.
52 length = the length of `name`, excluding the terminating `'\0'`
53 value = Identifier value (e.g. `Id.unitTest`) or `TOK.identifier`
54 */
55 extern (D) this(const(char)* name, size_t length, int value)
56 in
57 {
58 assert(name[length] == '\0');
59 }
60 do
61 {
62 //printf("Identifier('%s', %d)\n", name, value);
63 this(name[0 .. length], value);
64 }
65
66 /// ditto
67 extern (D) this(const(char)[] name, int value) @safe
68 {
69 //printf("Identifier('%.*s', %d)\n", cast(int)name.length, name.ptr, value);
70 this(name, value, false);
71 }
72
73 extern (D) private this(const(char)[] name, int value, bool isAnonymous) @safe
74 {
75 //printf("Identifier('%.*s', %d, %d)\n", cast(int)name.length, name.ptr, value, isAnonymous);
76 this.name = name;
77 this.value = value;
78 isAnonymous_ = isAnonymous;
79 }
80
81 static Identifier create(const(char)* name)
82 {
83 return new Identifier(name);
84 }
85
86 override const(char)* toChars() const pure
87 {
88 return name.ptr;
89 }
90
91 extern (D) override const(char)[] toString() const pure @safe
92 {
93 return name;
94 }
95
96 int getValue() const pure
97 {
98 return value;
99 }
100
101 bool isAnonymous() const pure @nogc @safe
102 {
103 return isAnonymous_;
104 }
105
106 const(char)* toHChars2() const
107 {
108 const(char)* p = null;
109 if (this == Id.ctor)
110 p = "this";
111 else if (this == Id.dtor || this == Id.__xdtor || this == Id.__fieldDtor ||
112 this == Id.__aggrDtor || this == Id.cppdtor || this == Id.ticppdtor)
113 p = "~this";
114 else if (this == Id.unitTest)
115 p = "unittest";
116 else if (this == Id.dollar)
117 p = "$";
118 else if (this == Id.withSym)
119 p = "with";
120 else if (this == Id.result)
121 p = "result";
122 else if (this == Id.returnLabel)
123 p = "return";
124 else if (this == Id.postblit)
125 p = "this(this)";
126 else
127 {
128 p = toChars();
129 if (*p == '_')
130 {
131 if (strncmp(p, "_staticCtor", 11) == 0)
132 p = "static this";
133 else if (strncmp(p, "_staticDtor", 11) == 0)
134 p = "static ~this";
135 else if (strncmp(p, "__invariant", 11) == 0)
136 p = "invariant";
137 }
138 }
139 return p;
140 }
141
142 override DYNCAST dyncast() const
143 {
144 return DYNCAST.identifier;
145 }
146
147 private extern (D) __gshared StringTable!Identifier stringtable;
148
149 /**
150 * Generates a new identifier.
151 *
152 * Params:
153 * prefix = this will be the prefix of the name of the identifier. For debugging
154 * purpose.
155 */
156 extern(D) static Identifier generateId(const(char)[] prefix)
157 {
158 return generateId(prefix, newSuffix, false);
159 }
160
161 /**
162 * Generates a new anonymous identifier.
163 *
164 * Params:
165 * name = this will be part of the name of the identifier. For debugging
166 * purpose.
167 */
168 extern(D) static Identifier generateAnonymousId(const(char)[] name)
169 {
170 return generateId("__anon" ~ name, newSuffix, true);
171 }
172
173 /**
174 * Generates a new identifier.
175 *
176 * Params:
177 * prefix = this will be the prefix of the name of the identifier. For debugging
178 * purpose.
179 * suffix = this will be the suffix of the name of the identifier. This is
180 * what makes the identifier unique
181 */
182 extern(D) static Identifier generateId(const(char)[] prefix, size_t suffix)
183 {
184 return generateId(prefix, suffix, false);
185 }
186
187 /// ditto
188 static Identifier generateId(const(char)* prefix, size_t length, size_t suffix)
189 {
190 return generateId(prefix[0 .. length], suffix);
191 }
192
193 // Generates a new, unique, suffix for an identifier.
194 extern (D) private static size_t newSuffix()
195 {
196 __gshared size_t i;
197 return ++i;
198 }
199
200 extern(D) private static Identifier generateId(const(char)[] prefix, size_t suffix, bool isAnonymous)
201 {
202 OutBuffer buf;
203 buf.write(prefix);
204 buf.print(suffix);
205 return idPool(buf[], isAnonymous);
206 }
207
208 /***************************************
209 * Generate deterministic named identifier based on a source location,
210 * such that the name is consistent across multiple compilations.
211 * A new unique name is generated. If the prefix+location is already in
212 * the stringtable, an extra suffix is added (starting the count at "_1").
213 *
214 * Params:
215 * prefix = first part of the identifier name.
216 * loc = source location to use in the identifier name.
217 * parent = (optional) extra part to be used in uniqueness check,
218 * if (prefix1, loc1) == (prefix2, loc2), but
219 * parent1 != parent2, no new name will be generated.
220 * Returns:
221 * Identifier (inside Identifier.idPool) with deterministic name based
222 * on the source location.
223 */
224 extern (D) static Identifier generateIdWithLoc(string prefix, Loc loc, string parent = "")
225 {
226 // generate `<prefix>_L<line>_C<col>`
227 auto sl = SourceLoc(loc);
228 OutBuffer idBuf;
229 idBuf.writestring(prefix);
230 idBuf.writestring("_L");
231 idBuf.print(sl.line);
232 idBuf.writestring("_C");
233 idBuf.print(sl.column);
234
235 /**
236 * Make sure the identifiers are unique per filename, i.e., per module/mixin
237 * (`path/to/foo.d` and `path/to/foo.d-mixin-<line>`). See issues
238 * https://issues.dlang.org/show_bug.cgi?id=16995
239 * https://issues.dlang.org/show_bug.cgi?id=18097
240 * https://issues.dlang.org/show_bug.cgi?id=18111
241 * https://issues.dlang.org/show_bug.cgi?id=18880
242 * https://issues.dlang.org/show_bug.cgi?id=18868
243 * https://issues.dlang.org/show_bug.cgi?id=19058
244 *
245 * It is a bit trickier for lambdas/dgliterals: we want them to be unique per
246 * module/mixin + function/template instantiation context. So we use extra parent
247 * argument for that when dealing with lambdas. We could have added it to prefix
248 * directly, but that would unnecessary lengthen symbols names. See issue:
249 * https://issues.dlang.org/show_bug.cgi?id=23722
250 */
251 static struct Key { string locKey; string prefix; string parent; }
252 __gshared uint[Key] counters;
253
254 string locKey = cast(string) (sl.filename ~ idBuf[]);
255 static if (__traits(compiles, counters.update(Key.init, () => 0u, (ref uint a) => 0u)))
256 {
257 // 2.082+
258 counters.update(Key(locKey, prefix, parent),
259 () => 1u, // insertion
260 (ref uint counter) // update
261 {
262 idBuf.writestring("_");
263 idBuf.print(counter);
264 return counter + 1;
265 }
266 );
267 }
268 else
269 {
270 const key = Key(locKey, prefix, parent);
271 if (auto pCounter = key in counters)
272 {
273 idBuf.writestring("_");
274 idBuf.print((*pCounter)++);
275 }
276 else
277 counters[key] = 1;
278 }
279
280 return idPool(idBuf[]);
281 }
282
283 /********************************************
284 * Create an identifier in the string table.
285 */
286 static Identifier idPool(scope const(char)* s, uint len)
287 {
288 return idPool(s[0 .. len]);
289 }
290
291 extern (D) static Identifier idPool(scope const(char)[] s, bool isAnonymous = false)
292 {
293 auto sv = stringtable.update(s);
294 auto id = sv.value;
295 if (!id)
296 {
297 id = new Identifier(sv.toString(), TOK.identifier, isAnonymous);
298 sv.value = id;
299 }
300 return id;
301 }
302
303 /******************************************
304 * Used for inserting keywords into the string table.
305 * Params:
306 * s = string for keyword
307 * value = TOK.xxxx for the keyword
308 */
309 extern (D) static void idPool(scope const(char)[] s, TOK value)
310 {
311 auto sv = stringtable.insert(s, null);
312 assert(sv);
313 auto id = new Identifier(sv.toString(), value);
314 sv.value = id;
315 }
316
317 /**********************************
318 * Determine if string is a valid Identifier.
319 * Params:
320 * str = string to check
321 * Returns:
322 * false for invalid
323 */
324 static bool isValidIdentifier(const(char)* str)
325 {
326 return str && isValidIdentifier(str.toDString);
327 }
328
329 /**********************************
330 * ditto
331 */
332 extern (D) static bool isValidIdentifier(const(char)[] str) @trusted
333 {
334 import dmd.common.charactertables;
335
336 if (str.length == 0 ||
337 (str[0] >= '0' && str[0] <= '9')) // beware of isdigit() on signed chars
338 {
339 return false;
340 }
341
342 // In a previous implementation this was implemented quite naively,
343 // by utilizing the libc.
344 // However we can do better, by copying the lexer approach to identifier validation.
345
346 const(char)* p = &str[0], pEnd = str.ptr + str.length;
347
348 // handle start characters
349 {
350 const c = *p;
351
352 if (isidchar(c))
353 p++;
354 else if (c & 0x80)
355 {
356 size_t countDecoded;
357 dchar decoded;
358
359 if (utf_decodeChar(p[0 .. pEnd - p], countDecoded, decoded) is null ||
360 isAnyStart(decoded))
361 p += countDecoded;
362 else
363 return false;
364 }
365 else
366 return false;
367 }
368
369 // handle continue characters
370 while(p !is pEnd)
371 {
372 const c = *p;
373
374 if (isidchar(c)) // handles ASCII subset
375 {
376 p++;
377 continue;
378 }
379 else if (c & 0x80)
380 {
381 size_t countDecoded;
382 dchar decoded;
383
384 if (utf_decodeChar(p[0 .. pEnd - p], countDecoded, decoded) is null ||
385 isAnyContinue(decoded))
386 {
387 p += countDecoded;
388 continue;
389 }
390 else
391 return false;
392 }
393 else
394 return false;
395 }
396
397 return true;
398 }
399
400 ///
401 unittest
402 {
403 assert(Identifier.isValidIdentifier("tes123_t".ptr));
404 assert(!Identifier.isValidIdentifier("tes123_^t".ptr));
405 assert(Identifier.isValidIdentifier("te123s_ğt".ptr));
406 assert(!Identifier.isValidIdentifier("t^e123s_ğt".ptr));
407 }
408
409 extern (D) static Identifier lookup(const(char)* s, size_t len)
410 {
411 return lookup(s[0 .. len]);
412 }
413
414 extern (D) static Identifier lookup(const(char)[] s)
415 {
416 auto sv = stringtable.lookup(s);
417 if (!sv)
418 return null;
419 return sv.value;
420 }
421
422 extern (D) static void initTable()
423 {
424 stringtable._init(28_000);
425 }
426 }