Skip to content

Commit 664b949

Browse files
committed
Better error messages in scanf.
1 parent 1bbd83d commit 664b949

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

lib/pure/strscans.nim

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,9 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
316316
conds.add resLen
317317

318318
template at(s: string; i: int): char = (if i < s.len: s[i] else: '\0')
319+
template matchError() =
320+
error("type mismatch between pattern '$" & pattern[p] & "' (position: " & $p & ") and " & $getType(results[i]) &
321+
" var '" & repr(results[i]) & "'")
319322

320323
var i = 0
321324
var p = 0
@@ -338,37 +341,37 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
338341
if i < results.len and getType(results[i]).typeKind == ntyString:
339342
matchBind "parseIdent"
340343
else:
341-
error("no string var given for $w")
344+
matchError
342345
inc i
343346
of 'b':
344347
if i < results.len and getType(results[i]).typeKind == ntyInt:
345348
matchBind "parseBin"
346349
else:
347-
error("no int var given for $b")
350+
matchError
348351
inc i
349352
of 'o':
350353
if i < results.len and getType(results[i]).typeKind == ntyInt:
351354
matchBind "parseOct"
352355
else:
353-
error("no int var given for $o")
356+
matchError
354357
inc i
355358
of 'i':
356359
if i < results.len and getType(results[i]).typeKind == ntyInt:
357360
matchBind "parseInt"
358361
else:
359-
error("no int var given for $i")
362+
matchError
360363
inc i
361364
of 'h':
362365
if i < results.len and getType(results[i]).typeKind == ntyInt:
363366
matchBind "parseHex"
364367
else:
365-
error("no int var given for $h")
368+
matchError
366369
inc i
367370
of 'f':
368371
if i < results.len and getType(results[i]).typeKind == ntyFloat:
369372
matchBind "parseFloat"
370373
else:
371-
error("no float var given for $f")
374+
matchError
372375
inc i
373376
of 's':
374377
conds.add newCall(bindSym"inc", idx, newCall(bindSym"skipWhitespace", inp, idx))
@@ -392,7 +395,7 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
392395
conds.add newCall(bindSym"!=", resLen, newLit min)
393396
conds.add resLen
394397
else:
395-
error("no string var given for $" & pattern[p])
398+
matchError
396399
inc i
397400
of '{':
398401
inc p
@@ -414,7 +417,7 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
414417
conds.add newCall(bindSym"!=", resLen, newLit 0)
415418
conds.add resLen
416419
else:
417-
error("no var given for $" & expr)
420+
error("no var given for $" & expr & " (position: " & $p & ")")
418421
inc i
419422
of '[':
420423
inc p

0 commit comments

Comments
 (0)