Debian Codegraph @

libphobos/libdruntime/core/internal/dassert.d

raw
1 /*
2 * Support for rich error messages generation with `assert`
3 *
4 * This module provides the `_d_assert_fail` hooks which are instantiated
5 * by the compiler whenever `-checkaction=context` is used.
6 * There are two hooks, one for unary expressions, and one for binary.
7 * When used, the compiler will rewrite `assert(a >= b)` as
8 * `assert(a >= b, _d_assert_fail!(typeof(a))(">=", a, b))`.
9 * Temporaries will be created to avoid side effects if deemed necessary
10 * by the compiler.
11 *
12 * For more information, refer to the implementation in DMD frontend
13 * for `AssertExpression`'s semantic analysis.
14 *
15 * Copyright: D Language Foundation 2018 - 2020
16 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
17 * Source: $(DRUNTIMESRC core/internal/_dassert.d)
18 * Documentation: https://dlang.org/phobos/core_internal_dassert.html
19 */
20 module core.internal.dassert;
21
22 /**
23 * Generates rich assert error messages for unary expressions
24 *
25 * The unary expression `assert(!una)` will be turned into
26 * `assert(!una, _d_assert_fail("!", una))`.
27 * This routine simply acts as if the user wrote `assert(una == false)`.
28 *
29 * Params:
30 * op = Operator that was used in the expression, currently only "!"
31 * is supported.
32 * a = Result of the expression that was used in `assert` before
33 * its implicit conversion to `bool`.
34 *
35 * Returns:
36 * A string such as "$a != true" or "$a == true".
37 */
38 string _d_assert_fail(A)(const scope string op, auto ref const scope A a)
39 {
40 // Prevent InvalidMemoryOperationError when triggered from a finalizer
41 if (inFinalizer())
42 return "Assertion failed (rich formatting is disabled in finalizers)";
43
44 string[2] vals = [ miniFormatFakeAttributes(a), "true" ];
45 immutable token = op == "!" ? "==" : "!=";
46 return combine(vals[0 .. 1], token, vals[1 .. $]);
47 }
48
49 /**
50 * Generates rich assert error messages for binary expressions
51 *
52 * The binary expression `assert(x == y)` will be turned into
53 * `assert(x == y, _d_assert_fail!(typeof(x))("==", x, y))`.
54 *
55 * Params:
56 * comp = Comparison operator that was used in the expression.
57 * a = Left hand side operand (can be a tuple).
58 * b = Right hand side operand (can be a tuple).
59 *
60 * Returns:
61 * A string such as "$a $comp $b".
62 */
63 template _d_assert_fail(A...)
64 {
65 string _d_assert_fail(B...)(
66 const scope string comp, auto ref const scope A a, auto ref const scope B b)
67 if (B.length != 0 || A.length != 1) // Resolve ambiguity with unary overload
68 {
69 // Prevent InvalidMemoryOperationError when triggered from a finalizer
70 if (inFinalizer())
71 return "Assertion failed (rich formatting is disabled in finalizers)";
72
73 string[A.length + B.length] vals;
74 static foreach (idx; 0 .. A.length)
75 vals[idx] = miniFormatFakeAttributes(a[idx]);
76 static foreach (idx; 0 .. B.length)
77 vals[A.length + idx] = miniFormatFakeAttributes(b[idx]);
78 immutable token = invertCompToken(comp);
79 return combine(vals[0 .. A.length], token, vals[A.length .. $]);
80 }
81 }
82
83 /// Combines the supplied arguments into one string `"valA token valB"`
84 private string combine(const scope string[] valA, const scope string token,
85 const scope string[] valB) pure nothrow @nogc @safe
86 {
87 // Each separator is 2 chars (", "), plus the two spaces around the token.
88 size_t totalLen = (valA.length - 1) * 2 +
89 (valB.length - 1) * 2 + 2 + token.length;
90
91 // Empty arrays are printed as ()
92 if (valA.length == 0) totalLen += 2;
93 if (valB.length == 0) totalLen += 2;
94
95 foreach (v; valA) totalLen += v.length;
96 foreach (v; valB) totalLen += v.length;
97
98 // Include braces when printing tuples
99 const printBraces = (valA.length + valB.length) != 2;
100 if (printBraces) totalLen += 4; // '(', ')' for both tuples
101
102 char[] buffer = cast(char[]) pureAlloc(totalLen)[0 .. totalLen];
103 // @nogc-concat of "<valA> <comp> <valB>"
104 static void formatTuple (scope char[] buffer, ref size_t n, in string[] vals, in bool printBraces)
105 {
106 if (printBraces) buffer[n++] = '(';
107 foreach (idx, v; vals)
108 {
109 if (idx)
110 {
111 buffer[n++] = ',';
112 buffer[n++] = ' ';
113 }
114 buffer[n .. n + v.length] = v;
115 n += v.length;
116 }
117 if (printBraces) buffer[n++] = ')';
118 }
119
120 size_t n;
121 formatTuple(buffer, n, valA, printBraces);
122 buffer[n++] = ' ';
123 buffer[n .. n + token.length] = token;
124 n += token.length;
125 buffer[n++] = ' ';
126 formatTuple(buffer, n, valB, printBraces);
127 return (() @trusted => cast(string) buffer)();
128 }
129
130 /// Yields the appropriate `printf` format token for a type `T`
131 private template getPrintfFormat(T)
132 {
133 static if (is(T == long))
134 {
135 enum getPrintfFormat = "%lld";
136 }
137 else static if (is(T == ulong))
138 {
139 enum getPrintfFormat = "%llu";
140 }
141 else static if (__traits(isIntegral, T))
142 {
143 static if (__traits(isUnsigned, T))
144 {
145 enum getPrintfFormat = "%u";
146 }
147 else
148 {
149 enum getPrintfFormat = "%d";
150 }
151 }
152 else
153 {
154 static assert(0, "Unknown format");
155 }
156 }
157
158 /**
159 * Generates a textual representation of `v` without relying on Phobos.
160 * The value is formatted as follows:
161 *
162 * - primitive types and arrays yield their respective literals
163 * - pointers are printed as hexadecimal numbers
164 * - enum members are represented by their name
165 * - user-defined types are formatted by either calling `toString`
166 * if defined or printing all members, e.g. `S(1, 2)`
167 *
168 * Note that unions are rejected because this method cannot determine which
169 * member is valid when calling this method.
170 *
171 * Params:
172 * v = the value to print
173 *
174 * Returns: a string respresenting `v` or `V.stringof` if `V` is not supported
175 */
176 private string miniFormat(V)(const scope ref V v)
177 {
178 import core.internal.traits: isAggregateType;
179
180 /// `shared` values are formatted as their base type
181 static if (is(V == shared T, T))
182 {
183 import core.atomic : atomicLoad;
184
185 // Use atomics to avoid race conditions whenever possible
186 static if (__traits(compiles, atomicLoad(v)))
187 {
188 if (!__ctfe)
189 {
190 T tmp = cast(T) atomicLoad(v);
191 return miniFormat(tmp);
192 }
193 }
194
195 // Fall back to a simple cast - we're violating the type system anyways
196 return miniFormat(*cast(const T*) &v);
197 }
198 // Format enum members using their name
199 else static if (is(V BaseType == enum))
200 {
201 // Always generate repeated if's instead of switch to skip the detection
202 // of non-integral enums. This method doesn't need to be fast.
203 static foreach (mem; __traits(allMembers, V))
204 {
205 if (v == __traits(getMember, V, mem))
206 return mem;
207 }
208
209 // Format invalid enum values as their base type
210 enum cast_ = "cast(" ~ V.stringof ~ ")";
211 const val = miniFormat(__ctfe ? cast(const BaseType) v : *cast(const BaseType*) &v);
212 return combine([ cast_ ], "", [ val ]);
213 }
214 else static if (is(V == bool))
215 {
216 return v ? "true" : "false";
217 }
218 // Detect vectors which match isIntegral / isFloating
219 else static if (is(V == __vector(ET[N]), ET, size_t N))
220 {
221 string msg = "[";
222 foreach (i; 0 .. N)
223 {
224 if (i > 0)
225 msg ~= ", ";
226
227 msg ~= miniFormat(v[i]);
228 }
229 msg ~= "]";
230 return msg;
231 }
232 else static if (__traits(isIntegral, V))
233 {
234 static if (is(V == char))
235 {
236 // Avoid invalid code points
237 if (v < 0x7F)
238 return ['\'', v, '\''];
239
240 uint tmp = v;
241 return "cast(char) " ~ miniFormat(tmp);
242 }
243 else static if (is(V == wchar) || is(V == dchar))
244 {
245 import core.internal.utf: isValidDchar, toUTF8;
246
247 // Avoid invalid code points
248 if (isValidDchar(v))
249 return toUTF8(['\'', v, '\'']);
250
251 uint tmp = v;
252 return "cast(" ~ V.stringof ~ ") " ~ miniFormat(tmp);
253 }
254 else
255 {
256 import core.internal.string;
257 static if (__traits(isUnsigned, V))
258 const val = unsignedToTempString(v);
259 else
260 const val = signedToTempString(v);
261 return val.get().idup();
262 }
263 }
264 else static if (__traits(isFloating, V))
265 {
266 import core.stdc.stdio : sprintf;
267 import core.stdc.config : LD = c_long_double;
268
269 // No suitable replacement for sprintf in druntime ATM
270 if (__ctfe)
271 return '<' ~ V.stringof ~ " not supported>";
272
273 // Workaround for https://issues.dlang.org/show_bug.cgi?id=20759
274 static if (is(LD == real))
275 enum realFmt = "%Lg";
276 else
277 enum realFmt = "%g";
278
279 char[60] val;
280 int len;
281 static if (is(V == float) || is(V == double))
282 len = sprintf(&val[0], "%g", v);
283 else static if (is(V == real))
284 len = sprintf(&val[0], realFmt, cast(LD) v);
285 else static if (is(V == cfloat) || is(V == cdouble))
286 len = sprintf(&val[0], "%g + %gi", v.re, v.im);
287 else static if (is(V == creal))
288 len = sprintf(&val[0], realFmt ~ " + " ~ realFmt ~ 'i', cast(LD) v.re, cast(LD) v.im);
289 else static if (is(V == ifloat) || is(V == idouble))
290 len = sprintf(&val[0], "%gi", v);
291 else // ireal
292 {
293 static assert(is(V == ireal));
294 static if (is(LD == real))
295 alias R = ireal;
296 else
297 alias R = idouble;
298 len = sprintf(&val[0], realFmt ~ 'i', cast(R) v);
299 }
300 return val.idup[0 .. len];
301 }
302 // special-handling for void-arrays
303 else static if (is(V == typeof(null)))
304 {
305 return "`null`";
306 }
307 else static if (is(V == U*, U))
308 {
309 // Format as ulong and prepend a 0x for pointers
310 import core.internal.string;
311 return cast(immutable) ("0x" ~ unsignedToTempString!16(cast(ulong) v));
312 }
313 // toString() isn't always const, e.g. classes inheriting from Object
314 else static if (__traits(compiles, { string s = V.init.toString(); }))
315 {
316 // Object references / struct pointers may be null
317 static if (is(V == class) || is(V == interface))
318 {
319 if (v is null)
320 return "`null`";
321 }
322
323 try
324 {
325 // Prefer const overload of toString
326 static if (__traits(compiles, { string s = v.toString(); }))
327 return v.toString();
328 else
329 return (cast() v).toString();
330 }
331 catch (Exception e)
332 {
333 return `<toString() failed: "` ~ e.msg ~ `", called on ` ~ formatMembers(v) ~`>`;
334 }
335 }
336 // Static arrays or slices (but not aggregates with `alias this`)
337 else static if (is(V : U[], U) && !isAggregateType!V)
338 {
339 import core.internal.traits: Unqual;
340 alias E = Unqual!U;
341
342 // special-handling for void-arrays
343 static if (is(E == void))
344 {
345 if (__ctfe)
346 return "<void[] not supported>";
347
348 const bytes = cast(byte[]) v;
349 return miniFormat(bytes);
350 }
351 // anything string-like
352 else static if (is(E == char) || is(E == dchar) || is(E == wchar))
353 {
354 const s = `"` ~ v ~ `"`;
355
356 // v could be a char[], dchar[] or wchar[]
357 static if (is(typeof(s) : const char[]))
358 return cast(immutable) s;
359 else
360 {
361 import core.internal.utf: toUTF8;
362 return toUTF8(s);
363 }
364 }
365 else
366 {
367 string msg = "[";
368 foreach (i, ref el; v)
369 {
370 if (i > 0)
371 msg ~= ", ";
372
373 // don't fully print big arrays
374 if (i >= 30)
375 {
376 msg ~= "...";
377 break;
378 }
379 msg ~= miniFormat(el);
380 }
381 msg ~= "]";
382 return msg;
383 }
384 }
385 else static if (is(V : Val[K], K, Val))
386 {
387 size_t i;
388 string msg = "[";
389 foreach (ref k, ref val; v)
390 {
391 if (i > 0)
392 msg ~= ", ";
393 // don't fully print big AAs
394 if (i++ >= 30)
395 {
396 msg ~= "...";
397 break;
398 }
399 msg ~= miniFormat(k) ~ ": " ~ miniFormat(val);
400 }
401 msg ~= "]";
402 return msg;
403 }
404 else static if (is(V == struct))
405 {
406 return formatMembers(v);
407 }
408 // Extern C++ classes don't have a toString by default
409 else static if (is(V == class) || is(V == interface))
410 {
411 if (v is null)
412 return "null";
413
414 // Extern classes might be opaque
415 static if (is(typeof(v.tupleof)))
416 return formatMembers(v);
417 else
418 return '<' ~ V.stringof ~ '>';
419 }
420 else
421 {
422 return V.stringof;
423 }
424 }
425
426 /// Formats `v`'s members as `V(<member 1>, <member 2>, ...)`
427 private string formatMembers(V)(const scope ref V v)
428 {
429 enum ctxPtr = __traits(isNested, V);
430 enum isOverlapped = calcFieldOverlap([ v.tupleof.offsetof ]);
431
432 string msg = V.stringof ~ "(";
433 foreach (i, ref field; v.tupleof)
434 {
435 if (i > 0)
436 msg ~= ", ";
437
438 static if (isOverlapped[i])
439 {
440 msg ~= "<overlapped field>";
441 }
442 else
443 {
444 // Mark context pointer
445 static if (ctxPtr && i == v.tupleof.length - 1)
446 msg ~= "<context>: ";
447
448 msg ~= miniFormat(field);
449 }
450 }
451 msg ~= ")";
452 return msg;
453 }
454
455 /**
456 * Calculates whether fields are overlapped based on the passed offsets.
457 *
458 * Params:
459 * offsets = offsets of all fields matching the order of `.tupleof`
460 *
461 * Returns: an array such that arr[n] = true indicates that the n'th field
462 * overlaps with an adjacent field
463 **/
464 private bool[] calcFieldOverlap(const scope size_t[] offsets)
465 {
466 bool[] overlaps = new bool[](offsets.length);
467
468 foreach (const idx; 1 .. overlaps.length)
469 {
470 if (offsets[idx - 1] == offsets[idx])
471 overlaps[idx - 1] = overlaps[idx] = true;
472 }
473
474 return overlaps;
475 }
476
477 /// Negates a comparison token, e.g. `==` is mapped to `!=`
478 private string invertCompToken(scope string comp) pure nothrow @nogc @safe
479 {
480 switch (comp)
481 {
482 case "==":
483 return "!=";
484 case "!=":
485 return "==";
486 case "<":
487 return ">=";
488 case "<=":
489 return ">";
490 case ">":
491 return "<=";
492 case ">=":
493 return "<";
494 case "is":
495 return "!is";
496 case "!is":
497 return "is";
498 case "in":
499 return "!in";
500 case "!in":
501 return "in";
502 default:
503 assert(0, combine(["Invalid comparison operator '"], comp, ["'"]));
504 }
505 }
506
507 /// Casts the function pointer to include `@safe`, `@nogc`, ...
508 private auto assumeFakeAttributes(T)(T t) @trusted
509 {
510 import core.internal.traits : Parameters, ReturnType;
511 alias RT = ReturnType!T;
512 alias P = Parameters!T;
513 alias type = RT function(P) nothrow @nogc @safe pure;
514 return cast(type) t;
515 }
516
517 /// Wrapper for `miniFormat` which assumes that the implementation is `@safe`, `@nogc`, ...
518 /// s.t. it does not violate the constraints of the function containing the `assert`.
519 private string miniFormatFakeAttributes(T)(const scope ref T t)
520 {
521 alias miniT = miniFormat!T;
522 return assumeFakeAttributes(&miniT)(t);
523 }
524
525 /// Allocates an array of `t` bytes while pretending to be `@safe`, `@nogc`, ...
526 private auto pureAlloc(size_t t)
527 {
528 static auto alloc(size_t len)
529 {
530 return new ubyte[len];
531 }
532 return assumeFakeAttributes(&alloc)(t);
533 }
534
535 /// Wrapper for GC.inFinalizer that fakes purity
536 private bool inFinalizer()() pure nothrow @nogc @safe
537 {
538 // CTFE doesn't trigger InvalidMemoryErrors
539 import core.memory : GC;
540 return !__ctfe && assumeFakeAttributes(&GC.inFinalizer)();
541 }
542
543 // https://issues.dlang.org/show_bug.cgi?id=21544
544 unittest
545 {
546 // Normal enum values
547 enum E { A, BCDE }
548 E e = E.A;
549 assert(miniFormat(e) == "A");
550 e = E.BCDE;
551 assert(miniFormat(e) == "BCDE");
552
553 // Invalid enum value is printed as their implicit base type (int)
554 e = cast(E) 3;
555 assert(miniFormat(e) == "cast(E) 3");
556
557 // Non-integral enums work as well
558 static struct S
559 {
560 int a;
561 string str;
562 }
563
564 enum E2 : S { a2 = S(1, "Hello") }
565 E2 es = E2.a2;
566 assert(miniFormat(es) == `a2`);
567
568 // Even invalid values
569 es = cast(E2) S(2, "World");
570 assert(miniFormat(es) == `cast(E2) S(2, "World")`);
571 }
572
573 // vectors
574 unittest
575 {
576 static if (is(__vector(float[4])))
577 {
578 __vector(float[4]) f = [-1.5f, 0.5f, 1.0f, 0.125f];
579 assert(miniFormat(f) == "[-1.5, 0.5, 1, 0.125]");
580 }
581
582 static if (is(__vector(int[4])))
583 {
584 __vector(int[4]) i = [-1, 0, 1, 3];
585 assert(miniFormat(i) == "[-1, 0, 1, 3]");
586 }
587 }