-
Notifications
You must be signed in to change notification settings - Fork 81
/
kprintf.d
447 lines (367 loc) · 12 KB
/
kprintf.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// This module implements the print logic for the kernel
module kernel.core.kprintf;
// Contains the interface to the VGA textmode driver.
import kernel.dev.console;
// Contains some nice logic and cool templates.
import kernel.core.util;
import architecture.mutex;
/* This template will generate code for printing and will do
* all parsing of the format string at compile time
*
* USAGE:
* kprintf!("format string {specifier} ... ")(args...);
*
* EXAMPLES:
* kprintf!("Integer: {}")(10);
* kprintf!("{!cls}Cleared the screen.")();
* kprintf!("{!pos:2,3}At position (2,3)")();
* kprintf!("{!fg:LightBlue!bg:Gray}{}")(25);
* kprintf!("{!fg:Red}redness")();
* kprintf!("{x} Hex!")(145);
* kprintf!("Curly Brace: {{")();
*
* COMMANDS:
* !cls - Clears the screen.
* !fg - Sets the foreground color, see the Color enum
* in kernel/dev/console.d.
* !bg - Sets the background color, same as above.
* !pos - Moves the cursor to the x and y given, see example above.
*
* SPECIFIERS:
* {x} - Prints the hex value.
* {u} - Treats as unsigned.
* {} - Prints common form.
*
* WHY IS IT COOL?
* - Compile time parsing of format strings
* - Type checking at compile time as well
* - That means it can tell you that you are dumb before you execute.
* - No need to specify type information.
*
* - So we can do this and not care about the
* output of the function:
*
* auto blah = someFunction();
* kprintf!("Some Arbitrary Info: {}")(blah);
*
* WOWWY WOW WOW!
*
*/
static Mutex lock;
template kprintf(char[] Format)
{
void kprintf(Args...)(Args args)
{
lock.lock();
mixin(ConvertFormat!(Format, Args));
lock.unlock();
}
}
/* This template will generate code like kprintf but will also
* print a newline afterward.
*
* USAGE: See kprintf above.
*
*/
template kprintfln(char[] Format)
{
void kprintfln(Args...)(Args args)
{
lock.lock();
mixin(ConvertFormat!(Format, Args));
Console.putChar('\n');
lock.unlock();
}
}
// The crazy D templating logic that implements the kprintf
private
{
// The following are functions that implement logic for printing different primatives.
void printInt(long i, char[] fmt)
{
char[20] buf;
if(fmt.length is 0)
Console.putString(itoa(buf, 'd', i));
else if(fmt[0] is 'd' || fmt[0] is 'D')
Console.putString(itoa(buf, 'd', i));
else if(fmt[0] is 'u' || fmt[0] is 'U')
Console.putString(itoa(buf, 'u', i));
else if(fmt[0] is 'x' || fmt[0] is 'X')
Console.putString(itoa(buf, 'x', i));
else if(fmt[0] is 'b' || fmt[0] is 'B')
Console.putString(itoa(buf, 'b', i));
}
// Floats are not supported by the kernel, but the interface to this exists anyway.
void printFloat(real f, char[] fmt)
{
Console.putString("?float?");
}
void printChar(dchar c, char[] fmt)
{
Console.putChar(c);
}
void printString(T)(T s, char[] fmt)
{
static assert(isStringType!(T));
Console.putString(s);
}
void printPointer(void* p, char[] fmt)
{
Console.putString("0x");
char[20] buf;
Console.putString(itoa(buf, 'x', cast(ulong)p));
}
void printBoolean(bool b, char[] fmt) {
if (b) {
Console.putString("true");
}
else {
Console.putString("false");
}
}
// The core template that will parse the format to find the string until a format specifier and return the length.
template ExtractString(char[] format)
{
static if(format.length == 0)
{
const size_t ExtractString = 0;
}
else static if(format[0] is '{')
{
static if(format.length > 1 && format[1] is '{')
const size_t ExtractString = 2 + ExtractString!(format[2 .. $]);
else
const size_t ExtractString = 0;
}
else
const size_t ExtractString = 1 + ExtractString!(format[1 .. $]);
}
// Extracts the format string and returns the length of that string.
template ExtractFormatStringImpl(char[] format)
{
static assert(format.length !is 0, "Unterminated format specifier");
static if(format[0] is '}')
const ExtractFormatStringImpl = 0;
else
const ExtractFormatStringImpl = 1 + ExtractFormatStringImpl!(format[1 .. $]);
}
// This template compares the format given (eg {x} would be "x") against the type of the argument passed.
template CheckFormatAgainstType(char[] rawFormat, size_t idx, T)
{
const char[] format = rawFormat[1 .. idx];
static if(isIntType!(T))
{
static assert(format == "" || format == "b" || format == "B" || format == "x" || format == "X" || format == "u" || format == "U",
"Invalid integer format specifier '" ~ format ~ "'");
}
// This is an inherited attribute to describe the length of the format string
const size_t res = idx;
}
// This template will compare a format with a type.
template ExtractFormatString(char[] format, T)
{
const ExtractFormatString = CheckFormatAgainstType!(format, ExtractFormatStringImpl!(format), T).res;
}
// This will get the length of a single command
template ExtractCommandStringImpl(char[] format)
{
static if (format.length == 0 || format[0] is '}')
{
const int ExtractCommandStringImpl = 0;
}
else
{
const int ExtractCommandStringImpl = 1 + ExtractCommandStringImpl!(format[1..$]);
}
}
// This template will extract a command string, or set of command strings
template ExtractCommandString(char[] format)
{
const ExtractCommandString = ExtractCommandStringImpl!(format);
}
// This template will take a string 's' and convert any '{{' to a single '{'.
// This is done after parsing the format string.
template StripDoubleLeftBrace(char[] s)
{
static if(s.length is 0)
const char[] StripDoubleLeftBrace = "";
else static if(s.length is 1)
const char[] StripDoubleLeftBrace = s;
else
{
static if(s[0 .. 2] == "{{")
const char[] StripDoubleLeftBrace = "{" ~ StripDoubleLeftBrace!(s[2 .. $]);
else
const char[] StripDoubleLeftBrace = s[0] ~ StripDoubleLeftBrace!(s[1 .. $]);
}
}
// Generates the code to print the string.
template MakePrintString(char[] s)
{
const char[] MakePrintString = "printString(\"" ~ StripDoubleLeftBrace!(s) ~ "\", \"\");\n";
}
// This template will generate the code to print out the string.
template MakePrintOther(T, char[] fmt, size_t idx)
{
static if(isIntType!(T))
const char[] MakePrintOther = "printInt(args[" ~ idx.stringof ~ "], \"" ~ fmt ~ "\");\n";
else static if(isCharType!(T))
const char[] MakePrintOther = "printChar(args[" ~ idx.stringof ~ "], \"" ~ fmt ~ "\");\n";
else static if(isStringType!(T))
const char[] MakePrintOther = "printString(args[" ~ idx.stringof ~ "], \"" ~ fmt ~ "\");\n";
else static if(isFloatType!(T))
const char[] MakePrintOther = "printFloat(args[" ~ idx.stringof ~ "], \"" ~ fmt ~ "\");\n";
else static if(isPointerType!(T))
const char[] MakePrintOther = "printPointer(args[" ~ idx.stringof ~ "], \"" ~ fmt ~ "\");\n";
else static if(isArrayType!(T))
const char[] MakePrintOther = "printArray(args[" ~ idx.stringof ~ "], true, false);\n";
else static if(is(T == bool)) {
const char[] MakePrintOther = "printBoolean(args[" ~ idx.stringof ~ "], \"" ~ fmt ~ "\");\n";
}
else
static assert(false, "I don't know how to handle argument " ~ idx.stringof ~ " of type '" ~ T.stringof ~ "'.");
}
// For the !fg command
template MakePrintCommand_fg(char[] format)
{
static if (format.length <= 1)
{
static assert(false, "Not enough parameters to the !fg command.");
}
else
{
const char[] MakePrintCommand_fg = "Console.setForeColor(Color." ~ format[1..$] ~ ");\n";
}
}
// For the !bg command
template MakePrintCommand_bg(char[] format)
{
static if (format.length <= 1)
{
static assert(false, "Not enough parameters to the !bg command.");
}
else
{
const char[] MakePrintCommand_bg = "Console.setBackColor(Color." ~ format[1..$] ~ ");\n";
}
}
template MakePrintCommand_pos(char[] format)
{
static if (format.length <= 3)
{
static assert(false, "Not enough parameters to the !pos command. USAGE: {!pos:x,y} where x and y are integers.");
}
else
{
const char[] MakePrintCommand_pos = "Console.setPosition(" ~ format[1..$] ~ ");\n";
}
}
// Output code to do the command.
template MakePrintCommandGenerate(char[] format)
{
static if (format.length >= 3 && format[0..3] == "cls")
{
const char[] MakePrintCommandGenerate = "Console.clearScreen();\n";
}
else static if (format.length >= 2 && format[0..2] == "fg")
{
const char[] MakePrintCommandGenerate = MakePrintCommand_fg!(format[2..$]);
}
else static if (format.length >= 2 && format[0..2] == "bg")
{
const char[] MakePrintCommandGenerate = MakePrintCommand_bg!(format[2..$]);
}
else static if (format.length >= 3 && format[0..3] == "pos")
{
const char[] MakePrintCommandGenerate = MakePrintCommand_pos!(format[3..$]);
}
else
{
static assert(false, "Unknown Command, !" ~ format ~ ", for kprintf.");
}
}
// Finds the length of the command string
template ExtractCommand(char[] format)
{
static if (format.length == 0 || format[0] is '}' || format[0] is '!')
{
const ExtractCommand = 0;
}
else
{
const ExtractCommand = 1 + ExtractCommand!(format[1..$]);
}
}
// This template will take everything up to a ! or a } and generate the code for that command
template MakePrintCommandImpl(char[] format)
{
static if (format.length == 0)
{
const char[] res = "";
}
else
{
static if (format[0] is '!')
{
const char[] res = MakePrintCommandImpl!(format[1..$]).res;
}
else
{
const lengthOfString = ExtractCommand!(format);
const char[] res = MakePrintCommandGenerate!(format[0..lengthOfString]) ~
MakePrintCommandImpl!(format[lengthOfString..$]).res;
}
}
}
// commands: !cls, !fg:color, !bg:color
// This template parses the command string (excluding the initial !) and generates the commands necessary.
template MakePrintCommand(char[] format)
{
const char[] MakePrintCommand = MakePrintCommandImpl!(format).res;
}
// This template implements the logic behind format extraction.
template ConvertFormatImpl(char[] format, size_t argIdx, Types...)
{
static if(format.length == 0)
{
static assert(argIdx == Types.length, "More parameters than format specifiers");
const char[] res = "";
}
else
{
// Look for a token that starts with a left curly brace that would signify a format specifier.
static if (format[0] is '{' && (!(format.length > 1 && (format[1] is '{' || format[1] is '!'))))
{
// We have a format specifier, but no arguments to convert?
static assert(argIdx < Types.length, "More format specifiers than parameters");
// We will convert the string and generate code for the print.
// Get the format string
const lengthOfString = ExtractFormatString!(format, Types[argIdx]);
// Generate the code and recall this template.
const char[] res = MakePrintOther!(Types[argIdx], format[1 .. lengthOfString] , argIdx) ~
ConvertFormatImpl!(format[lengthOfString + 1 .. $], argIdx + 1, Types).res;
}
else static if (format[0] is '{' && format.length > 1 && format[1] is '!')
{
// Command Token found, acts very similarly to a normal format specifier, expect it doesn't compare the types from the arguments.
const lengthOfString = ExtractCommandString!(format);
// Generate the code and recall this template.
const char[] res = MakePrintCommand!(format[2..lengthOfString])
~ ConvertFormatImpl!(format[lengthOfString + 1 .. $], argIdx, Types).res;
}
else
{
// We want to know how long of a string we can print out without intervention
const lengthOfString = ExtractString!(format);
// Then we can generate the code to print it out with the console and recall this template.
const char[] res = MakePrintString!(format[0..lengthOfString]) ~
ConvertFormatImpl!(format[lengthOfString..$], argIdx, Types).res;
}
}
}
// This template is the core routine. It will take the format and the arguments and generate the code to logically print out the string.
template ConvertFormat(char[] format, Types...)
{
const char[] ConvertFormat = ConvertFormatImpl!(format, 0, Types).res;
}
}