1 #!/usr/bin/env rdmd-dev-module 2 3 /** Various debug tools. 4 Copyright: Per Nordlöw 2014-. 5 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0). 6 Authors: $(WEB Per Nordlöw) 7 */ 8 module dbg; 9 10 mixin template dump(Names ... ) 11 { 12 auto _unused_dump = 13 { 14 import std.stdio : writeln, write; 15 foreach(i,name; Names) 16 { 17 write(name, " = ", mixin(name), (i<Names.length-1)?", ": "\n"); 18 } 19 return false; 20 }(); 21 } 22 23 // unittest 24 // { 25 // int x = 5; 26 // int y = 3; 27 // int z = 15; 28 // mixin dump!("x", "y"); // x = 5, y = 3 29 // mixin dump!("z"); // z = 15 30 // mixin dump!("x+y"); // x+y = 8 31 // mixin dump!("x+y < z"); // x+y < z = true 32 // } 33 34 @trusted: 35 36 /* http://stackoverflow.com/questions/19413340/escaping-safety-with-debug-statements */ 37 debug auto trustedPureDebugCall(alias fn, Arg...) (Arg args) pure 38 { 39 debug return fn(args); 40 } 41 42 nothrow: 43 44 void contextual_writeln(string file = __FILE__, uint line = __LINE__, string fun = __FUNCTION__, Arg...)(Arg t) 45 { 46 import std.stdio: writeln; 47 try { writeln(file, ":",line, ":"/* , ": in ",fun */, " debug: ", t); } 48 catch (Exception) { } 49 } 50 alias pln = contextual_writeln; 51 52 pure: 53 54 void debug_writeln(string file = __FILE__, uint line = __LINE__, string fun = __FUNCTION__, Arg...)(Arg t) 55 { 56 import std.stdio: writeln; 57 try { debug writeln(file, ":",line, ":"/* , ": in ",fun */, " debug: ", t); } 58 catch (Exception) { } 59 } 60 alias dln = debug_writeln; 61 62 void debug_writefln(string file = __FILE__, uint line = __LINE__, string fun = __FUNCTION__, Arg...)(Arg t) 63 { 64 import std.stdio: writefln; 65 try { debug writefln(file, ":",line, ":"/* , ": in ",fun */, " debug: ", t); } 66 catch (Exception) { } 67 } 68 alias dfln = debug_writefln; 69 70 /** Show the symbol name and variable of $(D Args). 71 See also: http://forum.dlang.org/thread/yczwqrbkxdiqijtiynrh@forum.dlang.org?page=1 72 */ 73 template show(Args...) 74 if (Args.length >= 1) 75 { 76 void show(string file = __FILE__, uint line = __LINE__, string fun = __FUNCTION__) 77 { 78 import std.stdio: write, writeln; 79 try 80 { 81 debug write(file, ":",line, ":" /* , ": in ",fun */, " debug: "); 82 foreach (const i, Arg; Args) 83 { 84 if (i) debug write(", "); // separator 85 debug write(Args[i].stringof, " is ", Arg); 86 } 87 debug writeln(); 88 } 89 catch (Exception) { } 90 } 91 } 92 93 // version = show; 94 95 version(show) unittest 96 { 97 int x = 11; 98 int y = 12; 99 int z = 13; 100 show!x; 101 show!y; 102 show!z; 103 } 104 105 version(show) unittest 106 { 107 int x = 11, y = 12, z = 13; 108 show!(x, y, z); 109 }