Debian Codegraph @

gcc/d/dmd/chkformat.d

raw
1 /**
2 * Check the arguments to `printf` and `scanf` against the `format` string.
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/chkformat.d, _chkformat.d)
8 * Documentation: https://dlang.org/phobos/dmd_chkformat.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/chkformat.d
10 */
11 module dmd.chkformat;
12
13 //import core.stdc.stdio : printf, scanf;
14 import core.stdc.ctype : isdigit;
15
16 import dmd.astenums;
17 import dmd.cond;
18 import dmd.errorsink;
19 import dmd.expression;
20 import dmd.globals;
21 import dmd.identifier;
22 import dmd.location;
23 import dmd.mtype;
24 import dmd.typesem;
25 import dmd.target;
26
27
28 /******************************************
29 * Check that arguments to a printf format string are compatible
30 * with that string. Issue errors for incompatibilities.
31 *
32 * Follows the C99 specification for printf.
33 *
34 * Takes a generous, rather than strict, view of compatiblity.
35 * For example, an unsigned value can be formatted with a signed specifier.
36 *
37 * Diagnosed incompatibilities are:
38 *
39 * 1. incompatible sizes which will cause argument misalignment
40 * 2. deferencing arguments that are not pointers
41 * 3. insufficient number of arguments
42 * 4. struct arguments
43 * 5. array and slice arguments
44 * 6. non-pointer arguments to `s` specifier
45 * 7. non-standard formats
46 * 8. undefined behavior per C99
47 *
48 * Per the C Standard, extra arguments are ignored.
49 *
50 * No attempt is made to fix the arguments or the format string.
51 *
52 * Params:
53 * loc = location for error messages
54 * format = format string
55 * args = arguments to match with format string
56 * isVa_list = if a "v" function (format check only)
57 * eSink = where the error messages go
58 *
59 * Returns:
60 * `true` if errors occurred
61 * References:
62 * C99 7.19.6.1
63 * https://www.cplusplus.com/reference/cstdio/printf/
64 */
65 public
66 bool checkPrintfFormat(Loc loc, scope const char[] format, scope Expression[] args, bool isVa_list, ErrorSink eSink)
67 {
68 //printf("checkPrintFormat('%.*s')\n", cast(int)format.length, format.ptr);
69 size_t n; // index in args
70 for (size_t i = 0; i < format.length;)
71 {
72 if (format[i] != '%')
73 {
74 ++i;
75 continue;
76 }
77 bool widthStar;
78 bool precisionStar;
79 size_t j = i;
80 const fmt = parsePrintfFormatSpecifier(format, j, widthStar, precisionStar);
81 const slice = format[i .. j];
82 i = j;
83
84 if (fmt == Format.percent)
85 continue; // "%%", no arguments
86 if (fmt == Format.GNU_m)
87 continue; // "%m", no arguments
88
89 if (isVa_list)
90 {
91 // format check only
92 if (fmt == Format.error)
93 eSink.deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr);
94 continue;
95 }
96
97 Expression getNextArg(ref bool skip)
98 {
99 if (n == args.length)
100 {
101 if (args.length < (n + 1))
102 eSink.deprecation(loc, "more format specifiers than %d arguments", cast(int)n);
103 else
104 skip = true;
105 return null;
106 }
107 return args[n++];
108 }
109
110 void errorMsg(const char* prefix, Expression arg, const char* texpect, Type tactual)
111 {
112 eSink.deprecation(arg.loc, "%sargument `%s` for format specification `\"%.*s\"` must be `%s`, not `%s`",
113 prefix ? prefix : "", arg.toChars(), cast(int)slice.length, slice.ptr, texpect, tactual.toChars());
114 }
115
116 if (widthStar)
117 {
118 bool skip;
119 auto e = getNextArg(skip);
120 if (skip)
121 continue;
122 if (!e)
123 return true;
124 auto t = e.type.toBasetype();
125 if (t.ty != Tint32 && t.ty != Tuns32)
126 errorMsg("width ", e, "int", t);
127 }
128
129 if (precisionStar)
130 {
131 bool skip;
132 auto e = getNextArg(skip);
133 if (skip)
134 continue;
135 if (!e)
136 return true;
137 auto t = e.type.toBasetype();
138 if (t.ty != Tint32 && t.ty != Tuns32)
139 errorMsg("precision ", e, "int", t);
140 }
141
142 bool skip;
143 auto e = getNextArg(skip);
144 if (skip)
145 continue;
146 if (!e)
147 return true;
148 auto t = e.type.toBasetype();
149 auto tnext = t.nextOf();
150 const c_longsize = target.c.longsize;
151 const ptrsize = target.ptrsize;
152
153 // Types which are promoted to int are allowed.
154 // Spec: C99 6.5.2.2.7
155 final switch (fmt)
156 {
157 case Format.u: // unsigned int
158 case Format.d: // int
159 if (t.ty != Tint32 && t.ty != Tuns32)
160 errorMsg(null, e, fmt == Format.u ? "uint" : "int", t);
161 break;
162
163 case Format.hhu: // unsigned char
164 case Format.hhd: // signed char
165 if (t.ty != Tint32 && t.ty != Tuns32 && t.ty != Tint8 && t.ty != Tuns8)
166 errorMsg(null, e, fmt == Format.hhu ? "ubyte" : "byte", t);
167 break;
168
169 case Format.hu: // unsigned short int
170 case Format.hd: // short int
171 if (t.ty != Tint32 && t.ty != Tuns32 && t.ty != Tint16 && t.ty != Tuns16)
172 errorMsg(null, e, fmt == Format.hu ? "ushort" : "short", t);
173 break;
174
175 case Format.lu: // unsigned long int
176 case Format.ld: // long int
177 if (!(t.isIntegral() && t.size() == c_longsize))
178 {
179 if (fmt == Format.lu)
180 errorMsg(null, e, (c_longsize == 4 ? "uint" : "ulong"), t);
181 else
182 errorMsg(null, e, (c_longsize == 4 ? "int" : "long"), t);
183 if (t.isIntegral() && t.size() != c_longsize)
184 eSink.errorSupplemental(e.loc, "C `long` is %d bytes on your system", c_longsize);
185 }
186 break;
187
188 case Format.llu: // unsigned long long int
189 case Format.lld: // long long int
190 if (t.ty != Tint64 && t.ty != Tuns64)
191 errorMsg(null, e, fmt == Format.llu ? "ulong" : "long", t);
192 break;
193
194 case Format.ju: // uintmax_t
195 case Format.jd: // intmax_t
196 if (t.ty != Tint64 && t.ty != Tuns64)
197 {
198 if (fmt == Format.ju)
199 errorMsg(null, e, "core.stdc.stdint.uintmax_t", t);
200 else
201 errorMsg(null, e, "core.stdc.stdint.intmax_t", t);
202 }
203 break;
204
205 case Format.zd: // size_t
206 if (!(t.isIntegral() && t.size() == ptrsize))
207 errorMsg(null, e, "size_t", t);
208 break;
209
210 case Format.td: // ptrdiff_t
211 if (!(t.isIntegral() && t.size() == ptrsize))
212 errorMsg(null, e, "ptrdiff_t", t);
213 break;
214
215 case Format.lg:
216 case Format.g: // double
217 if (t.ty != Tfloat64 && t.ty != Timaginary64)
218 errorMsg(null, e, "double", t);
219 break;
220
221 case Format.Lg: // long double
222 if (t.ty != Tfloat80 && t.ty != Timaginary80)
223 errorMsg(null, e, "real", t);
224 break;
225
226 case Format.p: // pointer
227 if (t.ty != Tpointer && t.ty != Tnull && t.ty != Tclass && t.ty != Tdelegate && t.ty != Taarray)
228 errorMsg(null, e, "void*", t);
229 break;
230
231 case Format.n: // pointer to int
232 if (!(t.ty == Tpointer && tnext.ty == Tint32 && tnext.isMutable()))
233 errorMsg(null, e, "int*", t);
234 break;
235
236 case Format.ln: // pointer to long int
237 if (!(t.ty == Tpointer && tnext.isIntegral() && tnext.size() == c_longsize))
238 errorMsg(null, e, (c_longsize == 4 ? "int*" : "long*"), t);
239 break;
240
241 case Format.lln: // pointer to long long int
242 if (!(t.ty == Tpointer && tnext.ty == Tint64))
243 errorMsg(null, e, "long*", t);
244 break;
245
246 case Format.hn: // pointer to short
247 if (!(t.ty == Tpointer && tnext.ty == Tint16))
248 errorMsg(null, e, "short*", t);
249 break;
250
251 case Format.hhn: // pointer to signed char
252 if (!(t.ty == Tpointer && tnext.ty == Tint16))
253 errorMsg(null, e, "byte*", t);
254 break;
255
256 case Format.jn: // pointer to intmax_t
257 if (!(t.ty == Tpointer && tnext.ty == Tint64))
258 errorMsg(null, e, "core.stdc.stdint.intmax_t*", t);
259 break;
260
261 case Format.zn: // pointer to size_t
262 if (!(t.ty == Tpointer && tnext.isIntegral() && tnext.isUnsigned() && tnext.size() == ptrsize))
263 errorMsg(null, e, "size_t*", t);
264 break;
265
266 case Format.tn: // pointer to ptrdiff_t
267 if (!(t.ty == Tpointer && tnext.isIntegral() && !tnext.isUnsigned() && tnext.size() == ptrsize))
268 errorMsg(null, e, "ptrdiff_t*", t);
269 break;
270
271 case Format.c: // char
272 if (t.ty != Tint32 && t.ty != Tuns32)
273 errorMsg(null, e, "char", t);
274 break;
275
276 case Format.lc: // wint_t
277 if (t.ty != Tint32 && t.ty != Tuns32)
278 errorMsg(null, e, "wchar_t", t);
279 break;
280
281 case Format.s: // pointer to char string
282 if (!(t.ty == Tpointer && (tnext.ty == Tchar || tnext.ty == Tint8 || tnext.ty == Tuns8)))
283 errorMsg(null, e, "char*", t);
284 break;
285
286 case Format.ls: // pointer to wchar_t string
287 if (!(t.ty == Tpointer && tnext.ty.isSomeChar && tnext.size() == target.c.wchar_tsize))
288 errorMsg(null, e, "wchar_t*", t);
289 break;
290
291 case Format.error:
292 eSink.deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr);
293 break;
294
295 case Format.GNU_m:
296 case Format.POSIX_ms:
297 case Format.POSIX_mls:
298 case Format.percent:
299 assert(0);
300 }
301 }
302 return false;
303 }
304
305 /******************************************
306 * Check that arguments to a scanf format string are compatible
307 * with that string. Issue errors for incompatibilities.
308 *
309 * Follows the C99 specification for scanf.
310 *
311 * Takes a generous, rather than strict, view of compatiblity.
312 * For example, an unsigned value can be formatted with a signed specifier.
313 *
314 * Diagnosed incompatibilities are:
315 *
316 * 1. incompatible sizes which will cause argument misalignment
317 * 2. deferencing arguments that are not pointers
318 * 3. insufficient number of arguments
319 * 4. struct arguments
320 * 5. array and slice arguments
321 * 6. non-standard formats
322 * 7. undefined behavior per C99
323 *
324 * Per the C Standard, extra arguments are ignored.
325 *
326 * No attempt is made to fix the arguments or the format string.
327 *
328 * Params:
329 * loc = location for error messages
330 * format = format string
331 * args = arguments to match with format string
332 * isVa_list = if a "v" function (format check only)
333 * eSink = where the error messages go
334 *
335 * Returns:
336 * `true` if errors occurred
337 * References:
338 * C99 7.19.6.2
339 * https://www.cplusplus.com/reference/cstdio/scanf/
340 */
341 public
342 bool checkScanfFormat(Loc loc, scope const char[] format, scope Expression[] args, bool isVa_list, ErrorSink eSink)
343 {
344 size_t n = 0;
345 for (size_t i = 0; i < format.length;)
346 {
347 if (format[i] != '%')
348 {
349 ++i;
350 continue;
351 }
352 bool asterisk;
353 size_t j = i;
354 const fmt = parseScanfFormatSpecifier(format, j, asterisk);
355 const slice = format[i .. j];
356 i = j;
357
358 if (fmt == Format.percent || asterisk)
359 continue; // "%%", "%*": no arguments
360
361 if (isVa_list)
362 {
363 // format check only
364 if (fmt == Format.error)
365 eSink.deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr);
366 continue;
367 }
368
369 Expression getNextArg()
370 {
371 if (n == args.length)
372 {
373 if (!asterisk)
374 eSink.deprecation(loc, "more format specifiers than %d arguments", cast(int)n);
375 return null;
376 }
377 return args[n++];
378 }
379
380 void errorMsg(const char* prefix, Expression arg, const char* texpect, Type tactual)
381 {
382 eSink.deprecation(arg.loc, "%sargument `%s` for format specification `\"%.*s\"` must be `%s`, not `%s`",
383 prefix ? prefix : "", arg.toChars(), cast(int)slice.length, slice.ptr, texpect, tactual.toChars());
384 }
385
386 auto e = getNextArg();
387 if (!e)
388 return true;
389
390 auto t = e.type.toBasetype();
391 auto tnext = t.nextOf();
392 const c_longsize = target.c.longsize;
393 const ptrsize = target.ptrsize;
394
395 final switch (fmt)
396 {
397 case Format.n:
398 case Format.d: // pointer to int
399 if (!(t.ty == Tpointer && tnext.ty == Tint32))
400 errorMsg(null, e, "int*", t);
401 break;
402
403 case Format.hhn:
404 case Format.hhd: // pointer to signed char
405 if (!(t.ty == Tpointer && tnext.ty == Tint16))
406 errorMsg(null, e, "byte*", t);
407 break;
408
409 case Format.hn:
410 case Format.hd: // pointer to short
411 if (!(t.ty == Tpointer && tnext.ty == Tint16))
412 errorMsg(null, e, "short*", t);
413 break;
414
415 case Format.ln:
416 case Format.ld: // pointer to long int
417 if (!(t.ty == Tpointer && tnext.isIntegral() && !tnext.isUnsigned() && tnext.size() == c_longsize))
418 errorMsg(null, e, (c_longsize == 4 ? "int*" : "long*"), t);
419 break;
420
421 case Format.lln:
422 case Format.lld: // pointer to long long int
423 if (!(t.ty == Tpointer && tnext.ty == Tint64))
424 errorMsg(null, e, "long*", t);
425 break;
426
427 case Format.jn:
428 case Format.jd: // pointer to intmax_t
429 if (!(t.ty == Tpointer && tnext.ty == Tint64))
430 errorMsg(null, e, "core.stdc.stdint.intmax_t*", t);
431 break;
432
433 case Format.zn:
434 case Format.zd: // pointer to size_t
435 if (!(t.ty == Tpointer && tnext.isIntegral() && tnext.isUnsigned() && tnext.size() == ptrsize))
436 errorMsg(null, e, "size_t*", t);
437 break;
438
439 case Format.tn:
440 case Format.td: // pointer to ptrdiff_t
441 if (!(t.ty == Tpointer && tnext.isIntegral() && !tnext.isUnsigned() && tnext.size() == ptrsize))
442 errorMsg(null, e, "ptrdiff_t*", t);
443 break;
444
445 case Format.u: // pointer to unsigned int
446 if (!(t.ty == Tpointer && tnext.ty == Tuns32))
447 errorMsg(null, e, "uint*", t);
448 break;
449
450 case Format.hhu: // pointer to unsigned char
451 if (!(t.ty == Tpointer && tnext.ty == Tuns8))
452 errorMsg(null, e, "ubyte*", t);
453 break;
454
455 case Format.hu: // pointer to unsigned short int
456 if (!(t.ty == Tpointer && tnext.ty == Tuns16))
457 errorMsg(null, e, "ushort*", t);
458 break;
459
460 case Format.lu: // pointer to unsigned long int
461 if (!(t.ty == Tpointer && tnext.isIntegral() && tnext.isUnsigned() && tnext.size() == c_longsize))
462 errorMsg(null, e, (c_longsize == 4 ? "uint*" : "ulong*"), t);
463 break;
464
465 case Format.llu: // pointer to unsigned long long int
466 if (!(t.ty == Tpointer && tnext.ty == Tuns64))
467 errorMsg(null, e, "ulong*", t);
468 break;
469
470 case Format.ju: // pointer to uintmax_t
471 if (!(t.ty == Tpointer && tnext.ty == Tuns64))
472 errorMsg(null, e, "core.stdc.stdint.uintmax_t*", t);
473 break;
474
475 case Format.g: // pointer to float
476 if (!(t.ty == Tpointer && tnext.ty == Tfloat32))
477 errorMsg(null, e, "float*", t);
478 break;
479
480 case Format.lg: // pointer to double
481 if (!(t.ty == Tpointer && tnext.ty == Tfloat64))
482 errorMsg(null, e, "double*", t);
483 break;
484
485 case Format.Lg: // pointer to long double
486 if (!(t.ty == Tpointer && tnext.ty == Tfloat80))
487 errorMsg(null, e, "real*", t);
488 break;
489
490 case Format.c:
491 case Format.s: // pointer to char string
492 if (!(t.ty == Tpointer && (tnext.ty == Tchar || tnext.ty == Tint8 || tnext.ty == Tuns8)))
493 errorMsg(null, e, "char*", t);
494 break;
495
496 case Format.lc:
497 case Format.ls: // pointer to wchar_t string
498 if (!(t.ty == Tpointer && tnext.ty.isSomeChar && tnext.size() == target.c.wchar_tsize))
499 errorMsg(null, e, "wchar_t*", t);
500 break;
501
502 case Format.p: // double pointer
503 if (!(t.ty == Tpointer && tnext.ty == Tpointer))
504 errorMsg(null, e, "void**", t);
505 break;
506
507 case Format.POSIX_ms: // pointer to pointer to char string
508 Type tnext2 = tnext ? tnext.nextOf() : null;
509 if (!(t.ty == Tpointer && tnext.ty == Tpointer && (tnext2.ty == Tchar || tnext2.ty == Tint8 || tnext2.ty == Tuns8)))
510 errorMsg(null, e, "char**", t);
511 break;
512
513 case Format.POSIX_mls: // pointer to pointer to wchar_t string
514 Type tnext2 = tnext ? tnext.nextOf() : null;
515 if (!(t.ty == Tpointer && tnext.ty == Tpointer && tnext2.ty.isSomeChar && tnext2.size() == target.c.wchar_tsize))
516 errorMsg(null, e, "wchar_t**", t);
517 break;
518
519 case Format.error:
520 eSink.deprecation(loc, "format specifier `\"%.*s\"` is invalid", cast(int)slice.length, slice.ptr);
521 break;
522
523 case Format.GNU_m:
524 case Format.percent:
525 assert(0);
526 }
527 }
528 return false;
529 }
530
531 /*****************************************************************************************************/
532
533 private:
534
535 /**************************************
536 * Parse the *format specifier* which is of the form:
537 *
538 * `%[*][width][length]specifier`
539 *
540 * Params:
541 * format = format string
542 * idx = index of `%` of start of format specifier,
543 * which gets updated to index past the end of it,
544 * even if `Format.error` is returned
545 * asterisk = set if there is a `*` sub-specifier
546 * Returns:
547 * Format
548 */
549 Format parseScanfFormatSpecifier(scope const char[] format, ref size_t idx,
550 out bool asterisk) nothrow pure @safe
551 {
552 auto i = idx;
553 assert(format[i] == '%');
554 const length = format.length;
555
556 Format error()
557 {
558 idx = i;
559 return Format.error;
560 }
561
562 ++i;
563 if (i == length)
564 return error();
565
566 if (format[i] == '%')
567 {
568 idx = i + 1;
569 return Format.percent;
570 }
571
572 // * sub-specifier
573 if (format[i] == '*')
574 {
575 ++i;
576 if (i == length)
577 return error();
578 asterisk = true;
579 }
580
581 // fieldWidth
582 while (isdigit(format[i]))
583 {
584 i++;
585 if (i == length)
586 return error();
587 }
588
589 /* Read the specifier
590 */
591 Format specifier;
592 Modifier flags = Modifier.none;
593 switch (format[i])
594 {
595 case 'm':
596 // https://pubs.opengroup.org/onlinepubs/9699919799/functions/scanf.html
597 // POSIX.1-2017 C Extension (CX)
598 flags = Modifier.m;
599 ++i;
600 if (i == length)
601 return error();
602 if (format[i] == 'l')
603 {
604 ++i;
605 if (i == length)
606 return error();
607 flags = Modifier.ml;
608 }
609
610 // Check valid conversion types for %m.
611 if (format[i] == 'c' || format[i] == 's')
612 specifier = flags == Modifier.ml ? Format.POSIX_mls :
613 Format.POSIX_ms;
614 else if (format[i] == 'C' || format[i] == 'S')
615 specifier = flags == Modifier.m ? Format.POSIX_mls :
616 Format.error;
617 else if (format[i] == '[')
618 goto case '[';
619 else
620 specifier = Format.error;
621 ++i;
622 break;
623
624 case 'l':
625 // Look for wchar_t scanset %l[..]
626 immutable j = i + 1;
627 if (j < length && format[j] == '[')
628 {
629 i = j;
630 flags = Modifier.l;
631 goto case '[';
632 }
633 goto default;
634
635 case '[':
636 // Read the scanset
637 i++;
638 if (i == length)
639 return error();
640 // If the conversion specifier begins with `[]` or `[^]`, the right
641 // bracket character is not the terminator, but in the scanlist.
642 if (format[i] == '^')
643 {
644 i++;
645 if (i == length)
646 return error();
647 }
648 if (format[i] == ']')
649 {
650 i++;
651 if (i == length)
652 return error();
653 }
654 // A scanset can be anything, so we just check that it is paired
655 while (i < length)
656 {
657 if (format[i] == ']')
658 break;
659 ++i;
660 }
661 // no `]` found
662 if (i == length)
663 return error();
664
665 specifier = flags == Modifier.none ? Format.s :
666 flags == Modifier.l ? Format.ls :
667 flags == Modifier.m ? Format.POSIX_ms :
668 flags == Modifier.ml ? Format.POSIX_mls :
669 Format.error;
670 ++i;
671 break;
672
673 default:
674 char genSpec;
675 specifier = parseGenericFormatSpecifier(format, i, genSpec);
676 if (specifier == Format.error)
677 return error();
678 break;
679 }
680
681 idx = i;
682 return specifier; // success
683 }
684
685 /**************************************
686 * Parse the *format specifier* which is of the form:
687 *
688 * `%[flags][field width][.precision][length modifier]specifier`
689 *
690 * Params:
691 * format = format string
692 * idx = index of `%` of start of format specifier,
693 * which gets updated to index past the end of it,
694 * even if `Format.error` is returned
695 * widthStar = set if * for width
696 * precisionStar = set if * for precision
697 * useGNUExts = true if parsing GNU format extensions
698 * Returns:
699 * Format
700 */
701 Format parsePrintfFormatSpecifier(scope const char[] format, ref size_t idx,
702 out bool widthStar, out bool precisionStar, bool useGNUExts =
703 findCondition(global.versionids, Identifier.idPool("CRuntime_Glibc"))) nothrow pure @safe
704 {
705 auto i = idx;
706 assert(format[i] == '%');
707 const length = format.length;
708 bool hash;
709 bool zero;
710 bool flags;
711 bool width;
712 bool precision;
713
714 Format error()
715 {
716 idx = i;
717 return Format.error;
718 }
719
720 ++i;
721 if (i == length)
722 return error();
723
724 if (format[i] == '%')
725 {
726 idx = i + 1;
727 return Format.percent;
728 }
729
730 /* Read the `flags`
731 */
732 while (1)
733 {
734 const c = format[i];
735 if (c == '-' ||
736 c == '+' ||
737 c == ' ')
738 {
739 flags = true;
740 }
741 else if (c == '#')
742 {
743 hash = true;
744 }
745 else if (c == '0')
746 {
747 zero = true;
748 }
749 else
750 break;
751 ++i;
752 if (i == length)
753 return error();
754 }
755
756 /* Read the `field width`
757 */
758 {
759 const c = format[i];
760 if (c == '*')
761 {
762 width = true;
763 widthStar = true;
764 ++i;
765 if (i == length)
766 return error();
767 }
768 else if ('1' <= c && c <= '9')
769 {
770 width = true;
771 ++i;
772 if (i == length)
773 return error();
774 while ('0' <= format[i] && format[i] <= '9')
775 {
776 ++i;
777 if (i == length)
778 return error();
779 }
780 }
781 }
782
783 /* Read the `precision`
784 */
785 if (format[i] == '.')
786 {
787 precision = true;
788 ++i;
789 if (i == length)
790 return error();
791 const c = format[i];
792 if (c == '*')
793 {
794 precisionStar = true;
795 ++i;
796 if (i == length)
797 return error();
798 }
799 else if ('0' <= c && c <= '9')
800 {
801 ++i;
802 if (i == length)
803 return error();
804 while ('0' <= format[i] && format[i] <= '9')
805 {
806 ++i;
807 if (i == length)
808 return error();
809 }
810 }
811 }
812
813 /* Read the specifier
814 */
815 char genSpec;
816 Format specifier;
817 switch (format[i])
818 {
819 case 'm':
820 // https://www.gnu.org/software/libc/manual/html_node/Other-Output-Conversions.html
821 if (useGNUExts)
822 {
823 specifier = Format.GNU_m;
824 genSpec = format[i];
825 ++i;
826 break;
827 }
828 goto default;
829
830 default:
831 specifier = parseGenericFormatSpecifier(format, i, genSpec);
832 if (specifier == Format.error)
833 return error();
834 break;
835 }
836
837 switch (genSpec)
838 {
839 case 'c':
840 case 's':
841 case 'C':
842 case 'S':
843 if (hash || zero)
844 return error();
845 break;
846
847 case 'd':
848 case 'i':
849 if (hash)
850 return error();
851 break;
852
853 case 'm':
854 if (hash || zero || flags)
855 return error();
856 break;
857
858 case 'n':
859 if (hash || zero || precision || width || flags)
860 return error();
861 break;
862
863 default:
864 break;
865 }
866
867 idx = i;
868 return specifier; // success
869 }
870
871 /* Different kinds of conversion modifiers. */
872 enum Modifier
873 {
874 none,
875 h, // short
876 hh, // char
877 j, // intmax_t
878 l, // wint_t/wchar_t
879 ll, // long long int
880 L, // long double
881 m, // char**
882 ml, // wchar_t**
883 t, // ptrdiff_t
884 z // size_t
885 }
886
887 /* Different kinds of formatting specifications, variations we don't
888 care about are merged. (Like we don't care about the difference between
889 f, e, g, a, etc.)
890
891 For `scanf`, every format is a pointer.
892 */
893 enum Format
894 {
895 d, // int
896 hhd, // signed char
897 hd, // short int
898 ld, // long int
899 lld, // long long int
900 jd, // intmax_t
901 zd, // size_t
902 td, // ptrdiff_t
903 u, // unsigned int
904 hhu, // unsigned char
905 hu, // unsigned short int
906 lu, // unsigned long int
907 llu, // unsigned long long int
908 ju, // uintmax_t
909 g, // float (scanf) / double (printf)
910 lg, // double (scanf)
911 Lg, // long double (both)
912 s, // char string (both)
913 ls, // wchar_t string (both)
914 c, // char (printf)
915 lc, // wint_t (printf)
916 p, // pointer
917 n, // pointer to int
918 hhn, // pointer to signed char
919 hn, // pointer to short
920 ln, // pointer to long int
921 lln, // pointer to long long int
922 jn, // pointer to intmax_t
923 zn, // pointer to size_t
924 tn, // pointer to ptrdiff_t
925 GNU_m, // GNU ext. : string corresponding to the error code in errno (printf)
926 POSIX_ms, // POSIX ext. : dynamically allocated char string (scanf)
927 POSIX_mls, // POSIX ext. : dynamically allocated wchar_t string (scanf)
928 percent, // %% (i.e. no argument)
929 error, // invalid format specification
930 }
931
932 /**************************************
933 * Parse the *length specifier* and the *specifier* of the following form:
934 * `[length]specifier`
935 *
936 * Params:
937 * format = format string
938 * idx = index of of start of format specifier,
939 * which gets updated to index past the end of it,
940 * even if `Format.error` is returned
941 * genSpecifier = Generic specifier. For instance, it will be set to `d` if the
942 * format is `hdd`.
943 * Returns:
944 * Format
945 */
946 Format parseGenericFormatSpecifier(scope const char[] format,
947 ref size_t idx, out char genSpecifier) nothrow pure @safe
948 {
949 const length = format.length;
950
951 /* Read the `length modifier`
952 */
953 const lm = format[idx];
954 Modifier flags;
955 switch (lm)
956 {
957 case 'j':
958 case 'z':
959 case 't':
960 case 'L':
961 flags = lm == 'j' ? Modifier.j :
962 lm == 'z' ? Modifier.z :
963 lm == 't' ? Modifier.t :
964 Modifier.L;
965 ++idx;
966 if (idx == length)
967 return Format.error;
968 break;
969
970 case 'h':
971 case 'l':
972 ++idx;
973 if (idx == length)
974 return Format.error;
975 if (lm == format[idx])
976 {
977 flags = lm == 'h' ? Modifier.hh : Modifier.ll;
978 ++idx;
979 if (idx == length)
980 return Format.error;
981 }
982 else
983 flags = lm == 'h' ? Modifier.h : Modifier.l;
984 break;
985
986 default:
987 flags = Modifier.none;
988 break;
989 }
990
991 /* Read the `specifier`
992 */
993 Format specifier;
994 const sc = format[idx];
995 genSpecifier = sc;
996 switch (sc)
997 {
998 case 'd':
999 case 'i':
1000 specifier = flags == Modifier.none ? Format.d :
1001 flags == Modifier.hh ? Format.hhd :
1002 flags == Modifier.h ? Format.hd :
1003 flags == Modifier.ll ? Format.lld :
1004 flags == Modifier.l ? Format.ld :
1005 flags == Modifier.j ? Format.jd :
1006 flags == Modifier.z ? Format.zd :
1007 flags == Modifier.t ? Format.td :
1008 Format.error;
1009 break;
1010
1011 case 'u':
1012 case 'o':
1013 case 'x':
1014 case 'X':
1015 specifier = flags == Modifier.none ? Format.u :
1016 flags == Modifier.hh ? Format.hhu :
1017 flags == Modifier.h ? Format.hu :
1018 flags == Modifier.ll ? Format.llu :
1019 flags == Modifier.l ? Format.lu :
1020 flags == Modifier.j ? Format.ju :
1021 flags == Modifier.z ? Format.zd :
1022 flags == Modifier.t ? Format.td :
1023 Format.error;
1024 break;
1025
1026 case 'f':
1027 case 'F':
1028 case 'e':
1029 case 'E':
1030 case 'g':
1031 case 'G':
1032 case 'a':
1033 case 'A':
1034 specifier = flags == Modifier.none ? Format.g :
1035 flags == Modifier.L ? Format.Lg :
1036 flags == Modifier.l ? Format.lg :
1037 Format.error;
1038 break;
1039
1040 case 'c':
1041 specifier = flags == Modifier.none ? Format.c :
1042 flags == Modifier.l ? Format.lc :
1043 Format.error;
1044 break;
1045
1046 case 's':
1047 specifier = flags == Modifier.none ? Format.s :
1048 flags == Modifier.l ? Format.ls :
1049 Format.error;
1050 break;
1051
1052 case 'p':
1053 specifier = flags == Modifier.none ? Format.p :
1054 Format.error;
1055 break;
1056
1057 case 'n':
1058 specifier = flags == Modifier.none ? Format.n :
1059 flags == Modifier.ll ? Format.lln :
1060 flags == Modifier.l ? Format.ln :
1061 flags == Modifier.hh ? Format.hhn :
1062 flags == Modifier.h ? Format.hn :
1063 flags == Modifier.j ? Format.jn :
1064 flags == Modifier.z ? Format.zn :
1065 flags == Modifier.t ? Format.tn :
1066 Format.error;
1067 break;
1068
1069 case 'C':
1070 // POSIX.1-2017 X/Open System Interfaces (XSI)
1071 // %C format is equivalent to %lc
1072 specifier = flags == Modifier.none ? Format.lc :
1073 Format.error;
1074 break;
1075
1076 case 'S':
1077 // POSIX.1-2017 X/Open System Interfaces (XSI)
1078 // %S format is equivalent to %ls
1079 specifier = flags == Modifier.none ? Format.ls :
1080 Format.error;
1081 break;
1082
1083 default:
1084 specifier = Format.error;
1085 break;
1086 }
1087
1088 ++idx;
1089 return specifier; // success
1090 }
1091
1092 @("parseGenericFormatSpecifier") unittest
1093 {
1094 char genSpecifier;
1095 size_t idx;
1096
1097 void testG(string fmtStr, Format expectedFormat, char expectedGenSpecifier)
1098 {
1099 idx = 0;
1100 assert(parseGenericFormatSpecifier(fmtStr, idx, genSpecifier) == expectedFormat);
1101 assert(genSpecifier == expectedGenSpecifier);
1102 }
1103
1104 testG("hhd", Format.hhd, 'd');
1105 testG("hn", Format.hn, 'n');
1106 testG("ji", Format.jd, 'i');
1107 testG("lu", Format.lu, 'u');
1108
1109 idx = 0;
1110 assert(parseGenericFormatSpecifier("k", idx, genSpecifier) == Format.error);
1111 }
1112
1113 @("parsePrintfFormatSpecifier") unittest
1114 {
1115 bool useGNUExts = false;
1116
1117 size_t idx = 0;
1118 bool widthStar;
1119 bool precisionStar;
1120
1121 void testP(string fmtStr, Format expectedFormat, size_t expectedIdx)
1122 {
1123 idx = 0;
1124 assert(parsePrintfFormatSpecifier(fmtStr, idx, widthStar, precisionStar, useGNUExts) == expectedFormat);
1125 assert(idx == expectedIdx);
1126 }
1127
1128 // one for each Format
1129 testP("%d", Format.d, 2);
1130 assert(!widthStar && !precisionStar);
1131
1132 testP("%ld", Format.ld, 3);
1133 testP("%lld", Format.lld, 4);
1134 testP("%jd", Format.jd, 3);
1135 testP("%zd", Format.zd, 3);
1136 testP("%td", Format.td, 3);
1137 testP("%g", Format.g, 2);
1138 testP("%Lg", Format.Lg, 3);
1139 testP("%p", Format.p, 2);
1140 testP("%n", Format.n, 2);
1141 testP("%ln", Format.ln, 3);
1142 testP("%lln", Format.lln, 4);
1143 testP("%hn", Format.hn, 3);
1144 testP("%hhn", Format.hhn, 4);
1145 testP("%jn", Format.jn, 3);
1146 testP("%zn", Format.zn, 3);
1147 testP("%tn", Format.tn, 3);
1148 testP("%c", Format.c, 2);
1149 testP("%lc", Format.lc, 3);
1150 testP("%s", Format.s, 2);
1151 testP("%ls", Format.ls, 3);
1152 testP("%%", Format.percent, 2);
1153
1154 // Synonyms
1155 testP("%i", Format.d, 2);
1156 testP("%u", Format.u, 2);
1157 testP("%o", Format.u, 2);
1158 testP("%x", Format.u, 2);
1159 testP("%X", Format.u, 2);
1160 testP("%f", Format.g, 2);
1161 testP("%F", Format.g, 2);
1162 testP("%G", Format.g, 2);
1163 testP("%a", Format.g, 2);
1164 testP("%La", Format.Lg, 3);
1165 testP("%A", Format.g, 2);
1166 testP("%lg", Format.lg, 3);
1167
1168 // width, precision
1169 testP("%*d", Format.d, 3);
1170 assert(widthStar && !precisionStar);
1171
1172 testP("%.*d", Format.d, 4);
1173 assert(!widthStar && precisionStar);
1174
1175 testP("%*.*d", Format.d, 5);
1176 assert(widthStar && precisionStar);
1177
1178 // Too short formats
1179 foreach (s; ["%", "%-", "%+", "% ", "%#", "%0", "%*", "%1", "%19", "%.", "%.*", "%.1", "%.12",
1180 "%j", "%z", "%t", "%l", "%h", "%ll", "%hh"])
1181 {
1182 testP(s, Format.error, s.length);
1183 }
1184
1185 // Undefined format combinations
1186 foreach (s; ["%#d", "%llg", "%jg", "%zg", "%tg", "%hg", "%hhg",
1187 "%#c", "%0c", "%jc", "%zc", "%tc", "%Lc", "%hc", "%hhc", "%llc",
1188 "%#s", "%0s", "%js", "%zs", "%ts", "%Ls", "%hs", "%hhs", "%lls",
1189 "%jp", "%zp", "%tp", "%Lp", "%hp", "%lp", "%hhp", "%llp",
1190 "%-n", "%+n", "% n", "%#n", "%0n", "%*n", "%1n", "%19n", "%.n", "%.*n", "%.1n", "%.12n", "%Ln", "%K"])
1191 {
1192 testP(s, Format.error, s.length);
1193 }
1194
1195 testP("%C", Format.lc, 2);
1196 testP("%S", Format.ls, 2);
1197
1198 // GNU extensions: explicitly toggle ISO/GNU flag.
1199 foreach (s; ["%jm", "%zm", "%tm", "%Lm", "%hm", "%hhm", "%lm", "%llm",
1200 "%#m", "%+m", "%-m", "% m", "%0m"])
1201 {
1202 useGNUExts = false;
1203 testP(s, Format.error, s.length);
1204 useGNUExts = true;
1205 testP(s, Format.error, s.length);
1206 }
1207
1208 foreach (s; ["%m", "%md", "%mz", "%mc", "%mm", "%msyz", "%ml", "%mlz", "%mlc", "%mlm"])
1209 {
1210 // valid cases, all parsed as `%m`
1211 // GNU printf()
1212 useGNUExts = true;
1213 testP(s, Format.GNU_m, 2);
1214
1215 // ISO printf()
1216 useGNUExts = false;
1217 testP(s, Format.error, 2);
1218 }
1219 }
1220
1221 @("parseScanfFormatSpecifier") unittest
1222 {
1223 size_t idx;
1224 bool asterisk;
1225
1226 void testS(string fmtStr, Format expectedFormat, size_t expectedIdx)
1227 {
1228 idx = 0;
1229 assert(parseScanfFormatSpecifier(fmtStr, idx, asterisk) == expectedFormat);
1230 assert(idx == expectedIdx);
1231 }
1232
1233 // one for each Format
1234 testS("%d", Format.d, 2);
1235 testS("%hhd", Format.hhd, 4);
1236 testS("%hd", Format.hd, 3);
1237 testS("%ld", Format.ld, 3);
1238 testS("%lld", Format.lld, 4);
1239 testS("%jd", Format.jd, 3);
1240 testS("%zd", Format.zd, 3);
1241 testS("%td", Format.td, 3);
1242 testS("%u", Format.u, 2);
1243 testS("%hhu", Format.hhu, 4);
1244 testS("%hu", Format.hu, 3);
1245 testS("%lu", Format.lu, 3);
1246 testS("%llu", Format.llu, 4);
1247 testS("%ju", Format.ju, 3);
1248 testS("%g", Format.g, 2);
1249 testS("%lg", Format.lg, 3);
1250 testS("%Lg", Format.Lg, 3);
1251 testS("%p", Format.p, 2);
1252 testS("%s", Format.s, 2);
1253 testS("%ls", Format.ls, 3);
1254 testS("%%", Format.percent, 2);
1255
1256 // Synonyms
1257 testS("%i", Format.d, 2);
1258 testS("%n", Format.n, 2);
1259
1260 testS("%o", Format.u, 2);
1261 testS("%x", Format.u, 2);
1262 testS("%f", Format.g, 2);
1263 testS("%e", Format.g, 2);
1264 testS("%a", Format.g, 2);
1265 testS("%c", Format.c, 2);
1266
1267 // asterisk
1268 testS("%*d", Format.d, 3);
1269 assert(asterisk);
1270
1271 testS("%9ld", Format.ld, 4);
1272 assert(!asterisk);
1273
1274 testS("%*25984hhd", Format.hhd, 10);
1275 assert(asterisk);
1276
1277 // scansets
1278 testS("%[a-zA-Z]", Format.s, 9);
1279 assert(!asterisk);
1280
1281 testS("%*25l[a-z]", Format.ls, 10);
1282 assert(asterisk);
1283
1284 testS("%[]]", Format.s, 4);
1285 assert(!asterisk);
1286
1287 testS("%[^]]", Format.s, 5);
1288 assert(!asterisk);
1289
1290 // Too short formats
1291 foreach (s; ["%", "% ", "%#", "%0", "%*", "%1", "%19",
1292 "%j", "%z", "%t", "%l", "%h", "%ll", "%hh", "%K"])
1293 {
1294
1295 testS(s, Format.error, s.length);
1296 }
1297
1298
1299 // Undefined format combinations
1300 foreach (s; ["%Ld", "%llg", "%jg", "%zg", "%tg", "%hg", "%hhg",
1301 "%jc", "%zc", "%tc", "%Lc", "%hc", "%hhc", "%llc",
1302 "%jp", "%zp", "%tp", "%Lp", "%hp", "%lp", "%hhp", "%llp",
1303 "%-", "%+", "%#", "%0", "%.", "%Ln"])
1304 {
1305
1306 testS(s, Format.error, s.length);
1307
1308 }
1309
1310 // Invalid scansets
1311 foreach (s; ["%[]", "%[^", "%[^]", "%[s", "%[0-9lld", "%[", "%l[^]"])
1312 {
1313
1314 testS(s, Format.error, s.length);
1315 }
1316
1317 // Posix extensions
1318 foreach (s; ["%jm", "%zm", "%tm", "%Lm", "%hm", "%hhm", "%lm", "%llm",
1319 "%m", "%ma", "%md", "%ml", "%mm", "%mlb", "%mlj", "%mlr", "%mlz",
1320 "%LC", "%lC", "%llC", "%jC", "%tC", "%hC", "%hhC", "%zC",
1321 "%LS", "%lS", "%llS", "%jS", "%tS", "%hS", "%hhS", "%zS"])
1322 {
1323
1324 testS(s, Format.error, s.length);
1325 }
1326
1327 testS("%mc", Format.POSIX_ms, 3);
1328 testS("%ms", Format.POSIX_ms, 3);
1329 testS("%m[0-9]", Format.POSIX_ms, 7);
1330 testS("%mlc", Format.POSIX_mls, 4);
1331 testS("%mls", Format.POSIX_mls, 4);
1332 testS("%ml[^0-9]", Format.POSIX_mls, 9);
1333 testS("%mC", Format.POSIX_mls, 3);
1334 testS("%mS", Format.POSIX_mls, 3);
1335
1336 testS("%C", Format.lc, 2);
1337 testS("%S", Format.ls, 2);
1338 }