summary refs log tree commit diff stats
path: root/compiler/commands.nim
blob: b6ebb6bcb795aa10dc554a4d1909d4bdb5355a3d (plain) (blame)
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#
#
#           The Nim Compiler
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# This module handles the parsing of command line arguments.


# We do this here before the 'import' statement so 'defined' does not get
# confused with 'TGCMode.gcGenerational' etc.
template bootSwitch(name, expr, userString: expr): expr =
  # Helper to build boot constants, for debugging you can 'echo' the else part.
  const name = if expr: " " & userString else: ""

bootSwitch(usedRelease, defined(release), "-d:release")
bootSwitch(usedGnuReadline, defined(useGnuReadline), "-d:useGnuReadline")
bootSwitch(usedNoCaas, defined(noCaas), "-d:noCaas")
bootSwitch(usedBoehm, defined(boehmgc), "--gc:boehm")
bootSwitch(usedMarkAndSweep, defined(gcmarkandsweep), "--gc:markAndSweep")
bootSwitch(usedGenerational, defined(gcgenerational), "--gc:generational")
bootSwitch(usedNoGC, defined(nogc), "--gc:none")

import
  os, msgs, options, nversion, condsyms, strutils, extccomp, platform, lists,
  wordrecg, parseutils, nimblecmd, idents, parseopt

# but some have deps to imported modules. Yay.
bootSwitch(usedTinyC, hasTinyCBackend, "-d:tinyc")
bootSwitch(usedAvoidTimeMachine, noTimeMachine, "-d:avoidTimeMachine")
bootSwitch(usedNativeStacktrace,
  defined(nativeStackTrace) and nativeStackTraceSupported,
  "-d:nativeStackTrace")
bootSwitch(usedFFI, hasFFI, "-d:useFFI")


proc writeCommandLineUsage*()

type
  TCmdLinePass* = enum
    passCmd1,                 # first pass over the command line
    passCmd2,                 # second pass over the command line
    passPP                    # preprocessor called processCommand()

proc processCommand*(switch: string, pass: TCmdLinePass)
proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo)

# implementation

const
  HelpMessage = "Nim Compiler Version $1 (" & CompileDate & ") [$2: $3]\n" &
      "Copyright (c) 2006-2015 by Andreas Rumpf\n"

const
  Usage = slurp"doc/basicopt.txt".replace("//", "")
  AdvancedUsage = slurp"doc/advopt.txt".replace("//", "")

proc getCommandLineDesc(): string =
  result = (HelpMessage % [VersionAsString, platform.OS[platform.hostOS].name,
                           CPU[platform.hostCPU].name]) & Usage

proc helpOnError(pass: TCmdLinePass) =
  if pass == passCmd1:
    msgWriteln(getCommandLineDesc())
    msgQuit(0)

proc writeAdvancedUsage(pass: TCmdLinePass) =
  if pass == passCmd1:
    msgWriteln(`%`(HelpMessage, [VersionAsString,
                                 platform.OS[platform.hostOS].name,
                                 CPU[platform.hostCPU].name]) & AdvancedUsage)
    msgQuit(0)

proc writeVersionInfo(pass: TCmdLinePass) =
  if pass == passCmd1:
    msgWriteln(`%`(HelpMessage, [VersionAsString,
                                 platform.OS[platform.hostOS].name,
                                 CPU[platform.hostCPU].name]))

    const gitHash = gorge("git log -n 1 --format=%H").strip
    when gitHash.len == 40:
      msgWriteln("git hash: " & gitHash)

    msgWriteln("active boot switches:" & usedRelease & usedAvoidTimeMachine &
      usedTinyC & usedGnuReadline & usedNativeStacktrace & usedNoCaas &
      usedFFI & usedBoehm & usedMarkAndSweep & usedGenerational & usedNoGC)
    msgQuit(0)

var
  helpWritten: bool

proc writeCommandLineUsage() =
  if not helpWritten:
    msgWriteln(getCommandLineDesc())
    helpWritten = true

proc addPrefix(switch: string): string =
  if len(switch) == 1: result = "-" & switch
  else: result = "--" & switch

proc invalidCmdLineOption(pass: TCmdLinePass, switch: string, info: TLineInfo) =
  if switch == " ": localError(info, errInvalidCmdLineOption, "-")
  else: localError(info, errInvalidCmdLineOption, addPrefix(switch))

proc splitSwitch(switch: string, cmd, arg: var string, pass: TCmdLinePass,
                 info: TLineInfo) =
  cmd = ""
  var i = 0
  if i < len(switch) and switch[i] == '-': inc(i)
  if i < len(switch) and switch[i] == '-': inc(i)
  while i < len(switch):
    case switch[i]
    of 'a'..'z', 'A'..'Z', '0'..'9', '_', '.': add(cmd, switch[i])
    else: break
    inc(i)
  if i >= len(switch): arg = ""
  elif switch[i] in {':', '=', '['}: arg = substr(switch, i + 1)
  else: invalidCmdLineOption(pass, switch, info)

proc processOnOffSwitch(op: TOptions, arg: string, pass: TCmdLinePass,
                        info: TLineInfo) =
  case whichKeyword(arg)
  of wOn: gOptions = gOptions + op
  of wOff: gOptions = gOptions - op
  else: localError(info, errOnOrOffExpectedButXFound, arg)

proc processOnOffSwitchG(op: TGlobalOptions, arg: string, pass: TCmdLinePass,
                         info: TLineInfo) =
  case whichKeyword(arg)
  of wOn: gGlobalOptions = gGlobalOptions + op
  of wOff: gGlobalOptions = gGlobalOptions - op
  else: localError(info, errOnOrOffExpectedButXFound, arg)

proc expectArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  if arg == "": localError(info, errCmdLineArgExpected, addPrefix(switch))

proc expectNoArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  if arg != "": localError(info, errCmdLineNoArgExpected, addPrefix(switch))

proc processSpecificNote(arg: string, state: TSpecialWord, pass: TCmdLinePass,
                         info: TLineInfo; orig: string) =
  var id = ""  # arg = "X]:on|off"
  var i = 0
  var n = hintMin
  while i < len(arg) and (arg[i] != ']'):
    add(id, arg[i])
    inc(i)
  if i < len(arg) and (arg[i] == ']'): inc(i)
  else: invalidCmdLineOption(pass, orig, info)
  if i < len(arg) and (arg[i] in {':', '='}): inc(i)
  else: invalidCmdLineOption(pass, orig, info)
  if state == wHint:
    var x = findStr(msgs.HintsToStr, id)
    if x >= 0: n = TNoteKind(x + ord(hintMin))
    else: localError(info, "unknown hint: " & id)
  else:
    var x = findStr(msgs.WarningsToStr, id)
    if x >= 0: n = TNoteKind(x + ord(warnMin))
    else: localError(info, "unknown warning: " & id)
  case whichKeyword(substr(arg, i))
  of wOn: incl(gNotes, n)
  of wOff: excl(gNotes, n)
  else: localError(info, errOnOrOffExpectedButXFound, arg)

proc processCompile(filename: string) =
  var found = findFile(filename)
  if found == "": found = filename
  var trunc = changeFileExt(found, "")
  extccomp.addExternalFileToCompile(found)
  extccomp.addFileToLink(completeCFilePath(trunc, false))

proc testCompileOptionArg*(switch, arg: string, info: TLineInfo): bool =
  case switch.normalize
  of "gc":
    case arg.normalize
    of "boehm":        result = gSelectedGC == gcBoehm
    of "refc":         result = gSelectedGC == gcRefc
    of "v2":           result = gSelectedGC == gcV2
    of "markandsweep": result = gSelectedGC == gcMarkAndSweep
    of "generational": result = gSelectedGC == gcGenerational
    of "none":         result = gSelectedGC == gcNone
    else: localError(info, errNoneBoehmRefcExpectedButXFound, arg)
  of "opt":
    case arg.normalize
    of "speed": result = contains(gOptions, optOptimizeSpeed)
    of "size": result = contains(gOptions, optOptimizeSize)
    of "none": result = gOptions * {optOptimizeSpeed, optOptimizeSize} == {}
    else: localError(info, errNoneSpeedOrSizeExpectedButXFound, arg)
  else: invalidCmdLineOption(passCmd1, switch, info)

proc testCompileOption*(switch: string, info: TLineInfo): bool =
  case switch.normalize
  of "debuginfo": result = contains(gGlobalOptions, optCDebug)
  of "compileonly", "c": result = contains(gGlobalOptions, optCompileOnly)
  of "nolinking": result = contains(gGlobalOptions, optNoLinking)
  of "nomain": result = contains(gGlobalOptions, optNoMain)
  of "forcebuild", "f": result = contains(gGlobalOptions, optForceFullMake)
  of "warnings", "w": result = contains(gOptions, optWarns)
  of "hints": result = contains(gOptions, optHints)
  of "threadanalysis": result = contains(gGlobalOptions, optThreadAnalysis)
  of "stacktrace": result = contains(gOptions, optStackTrace)
  of "linetrace": result = contains(gOptions, optLineTrace)
  of "debugger": result = contains(gOptions, optEndb)
  of "profiler": result = contains(gOptions, optProfiler)
  of "checks", "x": result = gOptions * ChecksOptions == ChecksOptions
  of "floatchecks":
    result = gOptions * {optNaNCheck, optInfCheck} == {optNaNCheck, optInfCheck}
  of "infchecks": result = contains(gOptions, optInfCheck)
  of "nanchecks": result = contains(gOptions, optNaNCheck)
  of "objchecks": result = contains(gOptions, optObjCheck)
  of "fieldchecks": result = contains(gOptions, optFieldCheck)
  of "rangechecks": result = contains(gOptions, optRangeCheck)
  of "boundchecks": result = contains(gOptions, optBoundsCheck)
  of "overflowchecks": result = contains(gOptions, optOverflowCheck)
  of "linedir": result = contains(gOptions, optLineDir)
  of "assertions", "a": result = contains(gOptions, optAssert)
  of "deadcodeelim": result = contains(gGlobalOptions, optDeadCodeElim)
  of "run", "r": result = contains(gGlobalOptions, optRun)
  of "symbolfiles": result = contains(gGlobalOptions, optSymbolFiles)
  of "genscript": result = contains(gGlobalOptions, optGenScript)
  of "threads": result = contains(gGlobalOptions, optThreads)
  of "taintmode": result = contains(gGlobalOptions, optTaintMode)
  of "tlsemulation": result = contains(gGlobalOptions, optTlsEmulation)
  of "implicitstatic": result = contains(gOptions, optImplicitStatic)
  of "patterns": result = contains(gOptions, optPatterns)
  of "experimental": result = gExperimentalMode
  else: invalidCmdLineOption(passCmd1, switch, info)

proc processPath(path: string, notRelativeToProj = false): string =
  let p = if notRelativeToProj or os.isAbsolute(path) or
              '$' in path or path[0] == '.':
            path
          else:
            options.gProjectPath / path
  result = unixToNativePath(p % ["nimrod", getPrefixDir(),
    "nim", getPrefixDir(),
    "lib", libpath,
    "home", removeTrailingDirSep(os.getHomeDir()),
    "projectname", options.gProjectName,
    "projectpath", options.gProjectPath])

proc trackDirty(arg: string, info: TLineInfo) =
  var a = arg.split(',')
  if a.len != 4: localError(info, errTokenExpected,
                            "DIRTY_BUFFER,ORIGINAL_FILE,LINE,COLUMN")
  var line, column: int
  if parseUtils.parseInt(a[2], line) <= 0:
    localError(info, errInvalidNumber, a[1])
  if parseUtils.parseInt(a[3], column) <= 0:
    localError(info, errInvalidNumber, a[2])

  let dirtyOriginalIdx = a[1].fileInfoIdx
  if dirtyOriginalIdx >= 0:
    msgs.setDirtyFile(dirtyOriginalIdx, a[0])

  gTrackPos = newLineInfo(dirtyOriginalIdx, line, column)

proc track(arg: string, info: TLineInfo) =
  var a = arg.split(',')
  if a.len != 3: localError(info, errTokenExpected, "FILE,LINE,COLUMN")
  var line, column: int
  if parseUtils.parseInt(a[1], line) <= 0:
    localError(info, errInvalidNumber, a[1])
  if parseUtils.parseInt(a[2], column) <= 0:
    localError(info, errInvalidNumber, a[2])
  gTrackPos = newLineInfo(a[0], line, column)

proc dynlibOverride(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  if pass in {passCmd2, passPP}:
    expectArg(switch, arg, pass, info)
    options.inclDynlibOverride(arg)

proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
  var
    theOS: TSystemOS
    cpu: TSystemCPU
    key, val: string
  case switch.normalize
  of "path", "p":
    expectArg(switch, arg, pass, info)
    addPath(processPath(arg), info)
  of "nimblepath", "babelpath":
    # keep the old name for compat
    if pass in {passCmd2, passPP} and not options.gNoNimblePath:
      expectArg(switch, arg, pass, info)
      let path = processPath(arg, notRelativeToProj=true)
      nimblePath(path, info)
  of "nonimblepath", "nobabelpath":
    expectNoArg(switch, arg, pass, info)
    options.gNoNimblePath = true
  of "excludepath":
    expectArg(switch, arg, pass, info)
    let path = processPath(arg)
    lists.excludePath(options.searchPaths, path)
    lists.excludePath(options.lazyPaths, path)
    if (len(path) > 0) and (path[len(path) - 1] == DirSep):
      let strippedPath = path[0 .. (len(path) - 2)]
      lists.excludePath(options.searchPaths, strippedPath)
      lists.excludePath(options.lazyPaths, strippedPath)
  of "nimcache":
    expectArg(switch, arg, pass, info)
    options.nimcacheDir = processPath(arg)
  of "out", "o":
    expectArg(switch, arg, pass, info)
    options.outFile = arg
  of "docseesrcurl":
    expectArg(switch, arg, pass, info)
    options.docSeeSrcUrl = arg
  of "mainmodule", "m":
    discard "allow for backwards compatibility, but don't do anything"
  of "define", "d":
    expectArg(switch, arg, pass, info)
    defineSymbol(arg)
  of "undef", "u":
    expectArg(switch, arg, pass, info)
    undefSymbol(arg)
  of "symbol":
    expectArg(switch, arg, pass, info)
    # deprecated, do nothing
  of "compile":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: processCompile(arg)
  of "link":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: addFileToLink(arg)
  of "debuginfo":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optCDebug)
  of "embedsrc":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optEmbedOrigSrc)
  of "compileonly", "c":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optCompileOnly)
  of "nolinking":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optNoLinking)
  of "nomain":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optNoMain)
  of "forcebuild", "f":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optForceFullMake)
  of "project":
    expectNoArg(switch, arg, pass, info)
    gWholeProject = true
  of "gc":
    expectArg(switch, arg, pass, info)
    case arg.normalize
    of "boehm":
      gSelectedGC = gcBoehm
      defineSymbol("boehmgc")
    of "refc":
      gSelectedGC = gcRefc
    of "v2":
      gSelectedGC = gcV2
    of "markandsweep":
      gSelectedGC = gcMarkAndSweep
      defineSymbol("gcmarkandsweep")
    of "generational":
      gSelectedGC = gcGenerational
      defineSymbol("gcgenerational")
    of "none":
      gSelectedGC = gcNone
      defineSymbol("nogc")
    else: localError(info, errNoneBoehmRefcExpectedButXFound, arg)
  of "warnings", "w": processOnOffSwitch({optWarns}, arg, pass, info)
  of "warning": processSpecificNote(arg, wWarning, pass, info, switch)
  of "hint": processSpecificNote(arg, wHint, pass, info, switch)
  of "hints": processOnOffSwitch({optHints}, arg, pass, info)
  of "threadanalysis": processOnOffSwitchG({optThreadAnalysis}, arg, pass, info)
  of "stacktrace": processOnOffSwitch({optStackTrace}, arg, pass, info)
  of "linetrace": processOnOffSwitch({optLineTrace}, arg, pass, info)
  of "debugger":
    case arg.normalize
    of "on", "endb":
      gOptions.incl optEndb
      defineSymbol("endb")
    of "off":
      gOptions.excl optEndb
      undefSymbol("endb")
    of "native", "gdb":
      incl(gGlobalOptions, optCDebug)
      gOptions = gOptions + {optLineDir} - {optEndb}
      undefSymbol("endb")
    else:
      localError(info, "expected endb|gdb but found " & arg)
  of "profiler":
    processOnOffSwitch({optProfiler}, arg, pass, info)
    if optProfiler in gOptions: defineSymbol("profiler")
    else: undefSymbol("profiler")
  of "checks", "x": processOnOffSwitch(ChecksOptions, arg, pass, info)
  of "floatchecks":
    processOnOffSwitch({optNaNCheck, optInfCheck}, arg, pass, info)
  of "infchecks": processOnOffSwitch({optInfCheck}, arg, pass, info)
  of "nanchecks": processOnOffSwitch({optNaNCheck}, arg, pass, info)
  of "objchecks": processOnOffSwitch({optObjCheck}, arg, pass, info)
  of "fieldchecks": processOnOffSwitch({optFieldCheck}, arg, pass, info)
  of "rangechecks": processOnOffSwitch({optRangeCheck}, arg, pass, info)
  of "boundchecks": processOnOffSwitch({optBoundsCheck}, arg, pass, info)
  of "overflowchecks": processOnOffSwitch({optOverflowCheck}, arg, pass, info)
  of "linedir": processOnOffSwitch({optLineDir}, arg, pass, info)
  of "assertions", "a": processOnOffSwitch({optAssert}, arg, pass, info)
  of "deadcodeelim": processOnOffSwitchG({optDeadCodeElim}, arg, pass, info)
  of "threads":
    processOnOffSwitchG({optThreads}, arg, pass, info)
    #if optThreads in gGlobalOptions: incl(gNotes, warnGcUnsafe)
  of "tlsemulation": processOnOffSwitchG({optTlsEmulation}, arg, pass, info)
  of "taintmode": processOnOffSwitchG({optTaintMode}, arg, pass, info)
  of "implicitstatic":
    processOnOffSwitch({optImplicitStatic}, arg, pass, info)
  of "patterns":
    processOnOffSwitch({optPatterns}, arg, pass, info)
  of "opt":
    expectArg(switch, arg, pass, info)
    case arg.normalize
    of "speed":
      incl(gOptions, optOptimizeSpeed)
      excl(gOptions, optOptimizeSize)
    of "size":
      excl(gOptions, optOptimizeSpeed)
      incl(gOptions, optOptimizeSize)
    of "none":
      excl(gOptions, optOptimizeSpeed)
      excl(gOptions, optOptimizeSize)
    else: localError(info, errNoneSpeedOrSizeExpectedButXFound, arg)
  of "app":
    expectArg(switch, arg, pass, info)
    case arg.normalize
    of "gui":
      incl(gGlobalOptions, optGenGuiApp)
      defineSymbol("executable")
      defineSymbol("guiapp")
    of "console":
      excl(gGlobalOptions, optGenGuiApp)
      defineSymbol("executable")
      defineSymbol("consoleapp")
    of "lib":
      incl(gGlobalOptions, optGenDynLib)
      excl(gGlobalOptions, optGenGuiApp)
      defineSymbol("library")
      defineSymbol("dll")
    of "staticlib":
      incl(gGlobalOptions, optGenStaticLib)
      excl(gGlobalOptions, optGenGuiApp)
      defineSymbol("library")
      defineSymbol("staticlib")
    else: localError(info, errGuiConsoleOrLibExpectedButXFound, arg)
  of "passc", "t":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: extccomp.addCompileOption(arg)
  of "passl", "l":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: extccomp.addLinkOption(arg)
  of "cincludes":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: cIncludes.add arg.processPath
  of "clibdir":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: cLibs.add arg.processPath
  of "clib":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: cLinkedLibs.add arg.processPath
  of "header":
    headerFile = arg
    incl(gGlobalOptions, optGenIndex)
  of "index":
    processOnOffSwitchG({optGenIndex}, arg, pass, info)
  of "import":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: implicitImports.add arg
  of "include":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd2, passPP}: implicitIncludes.add arg
  of "listcmd":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optListCmd)
  of "genmapping":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optGenMapping)
  of "os":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd1, passPP}:
      theOS = platform.nameToOS(arg)
      if theOS == osNone: localError(info, errUnknownOS, arg)
      elif theOS != platform.hostOS:
        setTarget(theOS, targetCPU)
  of "cpu":
    expectArg(switch, arg, pass, info)
    if pass in {passCmd1, passPP}:
      cpu = platform.nameToCPU(arg)
      if cpu == cpuNone: localError(info, errUnknownCPU, arg)
      elif cpu != platform.hostCPU:
        setTarget(targetOS, cpu)
  of "run", "r":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optRun)
  of "verbosity":
    expectArg(switch, arg, pass, info)
    gVerbosity = parseInt(arg)
  of "parallelbuild":
    expectArg(switch, arg, pass, info)
    gNumberOfProcessors = parseInt(arg)
  of "version", "v":
    expectNoArg(switch, arg, pass, info)
    writeVersionInfo(pass)
  of "advanced":
    expectNoArg(switch, arg, pass, info)
    writeAdvancedUsage(pass)
  of "help", "h":
    expectNoArg(switch, arg, pass, info)
    helpOnError(pass)
  of "symbolfiles":
    processOnOffSwitchG({optSymbolFiles}, arg, pass, info)
  of "skipcfg":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optSkipConfigFile)
  of "skipprojcfg":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optSkipProjConfigFile)
  of "skipusercfg":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optSkipUserConfigFile)
  of "skipparentcfg":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optSkipParentConfigFiles)
  of "genscript":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optGenScript)
  of "lib":
    expectArg(switch, arg, pass, info)
    libpath = processPath(arg, notRelativeToProj=true)
  of "putenv":
    expectArg(switch, arg, pass, info)
    splitSwitch(arg, key, val, pass, info)
    os.putEnv(key, val)
  of "cc":
    expectArg(switch, arg, pass, info)
    setCC(arg)
  of "track":
    expectArg(switch, arg, pass, info)
    track(arg, info)
  of "trackdirty":
    expectArg(switch, arg, pass, info)
    trackDirty(arg, info)
  of "suggest":
    expectNoArg(switch, arg, pass, info)
    gIdeCmd = ideSug
  of "def":
    expectNoArg(switch, arg, pass, info)
    gIdeCmd = ideDef
  of "eval":
    expectArg(switch, arg, pass, info)
    gEvalExpr = arg
  of "context":
    expectNoArg(switch, arg, pass, info)
    gIdeCmd = ideCon
  of "usages":
    expectNoArg(switch, arg, pass, info)
    gIdeCmd = ideUse
  of "stdout":
    expectNoArg(switch, arg, pass, info)
    incl(gGlobalOptions, optStdout)
  of "listfullpaths":
    expectNoArg(switch, arg, pass, info)
    gListFullPaths = true
  of "dynliboverride":
    dynlibOverride(switch, arg, pass, info)
  of "cs":
    expectArg(switch, arg, pass, info)
    case arg
    of "partial": idents.firstCharIsCS = true
    of "none": idents.firstCharIsCS = false
    else: localError(info, errGenerated,
      "'partial' or 'none' expected, but found " & arg)
  of "experimental":
    expectNoArg(switch, arg, pass, info)
    gExperimentalMode = true
  else:
    if strutils.find(switch, '.') >= 0: options.setConfigVar(switch, arg)
    else: invalidCmdLineOption(pass, switch, info)

proc processCommand(switch: string, pass: TCmdLinePass) =
  var cmd, arg: string
  splitSwitch(switch, cmd, arg, pass, gCmdLineInfo)
  processSwitch(cmd, arg, pass, gCmdLineInfo)


var
  arguments* = ""
    # the arguments to be passed to the program that
    # should be run

proc processSwitch*(pass: TCmdLinePass; p: OptParser) =
  # hint[X]:off is parsed as (p.key = "hint[X]", p.val = "off")
  # we fix this here
  var bracketLe = strutils.find(p.key, '[')
  if bracketLe >= 0:
    var key = substr(p.key, 0, bracketLe - 1)
    var val = substr(p.key, bracketLe + 1) & ':' & p.val
    processSwitch(key, val, pass, gCmdLineInfo)
  else:
    processSwitch(p.key, p.val, pass, gCmdLineInfo)

proc processArgument*(pass: TCmdLinePass; p: OptParser;
                      argsCount: var int): bool =
  if argsCount == 0:
    options.command = p.key
  else:
    if pass == passCmd1: options.commandArgs.add p.key
    if argsCount == 1:
      # support UNIX style filenames anywhere for portable build scripts:
      options.gProjectName = unixToNativePath(p.key)
      arguments = cmdLineRest(p)
      result = true
  inc argsCount
evision' href='/ahoang/Nim/blame/compiler/semtypes.nim?h=devel&id=6216046bc6b2794d15705f5d2621f602bda636c4'>^
af7c92c00 ^

12bac28d2 ^




e25474154 ^
dc669155e ^
e25474154 ^






8805829d7 ^
af7c92c00 ^





e25474154 ^

dc669155e ^
b595fc834 ^
c7158af75 ^
79aaf213d ^
b595fc834 ^
e25474154 ^


3f82352c2 ^



e25474154 ^
b595fc834 ^
dd99fe61c ^
dc669155e ^
e25474154 ^





b595fc834 ^
c7158af75 ^
79aaf213d ^
6c2050912 ^

064f29621 ^

6c2050912 ^

019d6e412 ^
ccd2934e4 ^

8d99753d6 ^
ccd2934e4 ^















dc669155e ^



ccd2934e4 ^



7d6500f1d ^
b595fc834 ^
79aaf213d ^
e25474154 ^



4741e8f9a ^
e25474154 ^

4741e8f9a ^
6c2050912 ^




e2d38a57e ^




6c2050912 ^


e2d38a57e ^
6c2050912 ^

e25474154 ^

049de0ef6 ^
e25474154 ^

049de0ef6 ^
6c2050912 ^
e25474154 ^

049de0ef6 ^
4741e8f9a ^
6c2050912 ^



6a8a409f1 ^
0d8e6dda6 ^
8805829d7 ^

0d8e6dda6 ^

bcbfa3aaa ^

be1154106 ^
b595fc834 ^
13c69f554 ^
4741e8f9a ^
251c44ff0 ^



049de0ef6 ^
4741e8f9a ^


674c05f42 ^
5e15dec17 ^
674c05f42 ^
4741e8f9a ^








b38c7adad ^

4741e8f9a ^




5e15dec17 ^
4741e8f9a ^



5e15dec17 ^
4741e8f9a ^

869a5aa90 ^
4741e8f9a ^
3a5cf3d63 ^
5e15dec17 ^
4741e8f9a ^

3a5cf3d63 ^

5e15dec17 ^
4741e8f9a ^


049de0ef6 ^
4741e8f9a ^

5e15dec17 ^
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026


                               
                                         



                                                   
 
                                                             
                       
 





                                                                       


                                                       
                                         


                                                         



                          




                                         
                                

                                                 
                                                             
                               
                         
                                                               



                                                    



                                                







                                                                               




                             

                                                           
                        

                                                                      
                                   







                                            



                                                            
                                   
                                                                            


                                                         

                                        
                                             
                                  

                                                       






                                                      


                                                                           

                                       
                                             
                                  
        

                                                        
 










                                                                     


                                                                             
                                             
                                  

                                   

                                                             
                      
                                          
                                             


                                                 
                                  

                                    

                                                              

                                               
                                                            

                                         

                                                              

                    

                                          
                                                       
                                       

                               







                                                                

                     
                                 
 
                                                          
              
                     
                                                         

                                                  
                                              

                                                        
                                            
 




                                                           
                                                      
                                               
                                  


                                                       


                                                                     
                                         
                                  
        
                                                    
                                            

                                                             

                                            
                                             

                                    
                                                          
                                  

                                                          
                                            
  
                                                

                      
       


                                                                     
                                                                  


                                                                       




                                            

                               






                                                                   
             

                                                                        

                                           
                            
                  

                      
                        
         
                                               
                             

                                                           

                                                     

                                          
                          
                 
                                       
                     

                                               


                                                   


                                         
                                           
                                                                
                                     
                                                


                              
                                               



                                                                      
 

                                                        
                              
                          
                                                      


                                                                      
                             


                                                       
                                                              
         
                     
       
                                








                                                                      

                                                          
                                                        

                                                          
       


                                                                    
                      

                                                 
                                                  
                                                  
  
                                                                                  
                       







                                        

                                                                 
 


                                                          
                                                              




                                                            
                                                                

                         
                                                                




                                                                    
                                              
                                            
                          


                         
                                                           
         















                                                                       
                                                      
     



                                                                               
                     


                                                        
                                                             
          
                                           

                                                 





                                                                      
                        
                                       
                               











                                                                   
                                             



                                                                               
                     
             



                                                  
                                   
                 
                  
                      
                           


                                                                          
                                                                   


                                                                   

                                             
               
                           












                                                                          




                                                                            
                                                                 


                                                            
                 
                         





                                                                                
                  
                                         




                                                 
                                                                     
                              






                                                                                
                                           

                                                                  
                                    

                                           
















                                                                                
                              








                                                                       






                                                         

                                                               
                          


                                                                      
                    
                                

                                                                      


                                                                           


                                                                         

                                                                 
                         

                                                                  




                                                                       

                                                      
  
                                                                 
                                                      

                                                           
                                   




                                                    
 



                                                                       


                                            









                                                       

                                                

                                          
                
                                                           


                                                      



                                         
                                          

                                                           
           

                                                         
 
                                                                         

                                                       











                                                                        


                                          
           

                                                          



                                                                          
                                                                


                                              
                                                                





                                           
                                                           

                                                           
              
               



                                                
                                                          
                     
                                      



                                                                           
                       
                          
                 
                                 

                                             
                         







                                                   

                                                 
                  
                                                 
                                                       
                    
                     

                                                        

                                                     

                                        


                                   
                                                                
                                   
                                              

                                                                    
                         

                            
                                                                    
                                             
                                                                    
                                       
                                  
                                    
 

                                          


                                                                          
                                                  
                                                                              
                              
                                    
                              
 
                                                                 
                       
                         
                                  
                                     
                


                                                     
       





                                                               
                                           






                                              



















                                                                           
                                                      

                       
                                                       
                                          



                                                
                                          
                                     
                                                 
                                          
                                 
                           



                                                                              

                                          
                

                                                         
                                              

                                                 
 



                                                
       
                                                     
 
                                                             
              
                                           
             
                 

                                                       
                      
                                                            

                                                                
         
                                   
                                         
                                              
                 


                                                       
                          


                                             
                      









                                                                     






                                                                      
           
                                  
         
                                


                                           

                                                     




                                                                      
                         
                                      






                                                                              
                                                





                                                          

                                            
                              
                     
                                                               
                                              
                     


                             



                                                                               
                   
           
                                                 
                       





                           
         
                                                                   
                                              

                                                   

                                                   

                                                   
                            

                                       
         















                                                                         



                                                         



                                            
       
                                       
                                            



                                                         
                   

                                              
              




                                          




                                            


                                                
                                               

                                      

                                      
                                        

                                       
                                        
                                                  

                             
                                          
                                                       



                                              
                                           
                                        

                                                

                                        

                                            
                      
                                           
  
                                                                   



                                                                      
                            


                                                                              
                                
                   
          








                                                

                                                              




                                                       
                                         



                                           
                                           

                                             
                                                     
                                               
                                                     
                                                   

                     

                                                       
                                           


                                         
                                                       

                                   
                                              
#
#
#           The Nimrod Compiler
#        (c) Copyright 2012 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# this module does the semantic checking of type declarations
# included from sem.nim

proc newOrPrevType(kind: TTypeKind, prev: PType, c: PContext): PType = 
  if prev == nil: 
    result = newTypeS(kind, c)
  else: 
    result = prev
    if result.kind == tyForward: result.kind = kind

proc newConstraint(c: PContext, k: TTypeKind): PType = 
  result = newTypeS(tyTypeClass, c)
  result.addSonSkipIntLit(newTypeS(k, c))

proc semEnum(c: PContext, n: PNode, prev: PType): PType =
  if n.sonsLen == 0: return newConstraint(c, tyEnum)
  var 
    counter, x: BiggestInt
    e: PSym
    base: PType
  counter = 0
  base = nil
  result = newOrPrevType(tyEnum, prev, c)
  result.n = newNodeI(nkEnumTy, n.info)
  checkMinSonsLen(n, 1)
  if n.sons[0].kind != nkEmpty: 
    base = semTypeNode(c, n.sons[0].sons[0], nil)
    if base.kind != tyEnum: 
      localError(n.sons[0].info, errInheritanceOnlyWithEnums)
    counter = lastOrd(base) + 1
  rawAddSon(result, base)
  let isPure = result.sym != nil and sfPure in result.sym.flags
  for i in countup(1, sonsLen(n) - 1): 
    case n.sons[i].kind
    of nkEnumFieldDef: 
      e = newSymS(skEnumField, n.sons[i].sons[0], c)
      var v = semConstExpr(c, n.sons[i].sons[1])
      var strVal: PNode = nil
      case skipTypes(v.typ, abstractInst).kind 
      of tyTuple: 
        if sonsLen(v) == 2:
          strVal = v.sons[1] # second tuple part is the string value
          if skipTypes(strVal.typ, abstractInst).kind in {tyString, tyCstring}:
            x = getOrdValue(v.sons[0]) # first tuple part is the ordinal
          else:
            LocalError(strVal.info, errStringLiteralExpected)
        else:
          LocalError(v.info, errWrongNumberOfVariables)
      of tyString, tyCstring:
        strVal = v
        x = counter
      else:
        x = getOrdValue(v)
      if i != 1:
        if x != counter: incl(result.flags, tfEnumHasHoles)
        if x < counter: 
          LocalError(n.sons[i].info, errInvalidOrderInEnumX, e.name.s)
          x = counter
      e.ast = strVal # might be nil
      counter = x
    of nkSym: 
      e = n.sons[i].sym
    of nkIdent: 
      e = newSymS(skEnumField, n.sons[i], c)
    else: illFormedAst(n)
    e.typ = result
    e.position = int(counter)
    if result.sym != nil and sfExported in result.sym.flags:
      incl(e.flags, sfUsed)
      incl(e.flags, sfExported)
      if not isPure: StrTableAdd(c.module.tab, e)
    addSon(result.n, newSymNode(e))
    if sfGenSym notin e.flags and not isPure: addDeclAt(c, e, c.tab.tos - 1)
    inc(counter)

proc semSet(c: PContext, n: PNode, prev: PType): PType = 
  result = newOrPrevType(tySet, prev, c)
  if sonsLen(n) == 2: 
    var base = semTypeNode(c, n.sons[1], nil)
    addSonSkipIntLit(result, base)
    if base.kind == tyGenericInst: base = lastSon(base)
    if base.kind != tyGenericParam: 
      if not isOrdinalType(base): 
        LocalError(n.info, errOrdinalTypeExpected)
      elif lengthOrd(base) > MaxSetElements: 
        LocalError(n.info, errSetTooBig)
  else:
    LocalError(n.info, errXExpectsOneTypeParam, "set")
    addSonSkipIntLit(result, errorType(c))
  
proc semContainer(c: PContext, n: PNode, kind: TTypeKind, kindStr: string, 
                  prev: PType): PType = 
  result = newOrPrevType(kind, prev, c)
  if sonsLen(n) == 2: 
    var base = semTypeNode(c, n.sons[1], nil)
    addSonSkipIntLit(result, base)
  else: 
    LocalError(n.info, errXExpectsOneTypeParam, kindStr)
    addSonSkipIntLit(result, errorType(c))

proc semVarargs(c: PContext, n: PNode, prev: PType): PType =
  result = newOrPrevType(tyVarargs, prev, c)
  if sonsLen(n) == 2 or sonsLen(n) == 3:
    var base = semTypeNode(c, n.sons[1], nil)
    addSonSkipIntLit(result, base)
    if sonsLen(n) == 3:
      result.n = newIdentNode(considerAcc(n.sons[2]), n.sons[2].info)
  else:
    LocalError(n.info, errXExpectsOneTypeParam, "varargs")
    addSonSkipIntLit(result, errorType(c))
  
proc semAnyRef(c: PContext, n: PNode, kind: TTypeKind, prev: PType): PType = 
  if sonsLen(n) == 1:
    result = newOrPrevType(kind, prev, c)
    var base = semTypeNode(c, n.sons[0], nil)
    addSonSkipIntLit(result, base)
  else:
    result = newConstraint(c, kind)
  
proc semVarType(c: PContext, n: PNode, prev: PType): PType = 
  if sonsLen(n) == 1: 
    result = newOrPrevType(tyVar, prev, c)
    var base = semTypeNode(c, n.sons[0], nil)
    if base.kind == tyVar: 
      LocalError(n.info, errVarVarTypeNotAllowed)
      base = base.sons[0]
    addSonSkipIntLit(result, base)
  else:
    result = newConstraint(c, tyVar)
  
proc semDistinct(c: PContext, n: PNode, prev: PType): PType = 
  if sonsLen(n) == 1:
    result = newOrPrevType(tyDistinct, prev, c)
    addSonSkipIntLit(result, semTypeNode(c, n.sons[0], nil))
  else:
    result = newConstraint(c, tyDistinct)
  
proc semRangeAux(c: PContext, n: PNode, prev: PType): PType = 
  assert IsRange(n)
  checkSonsLen(n, 3)
  result = newOrPrevType(tyRange, prev, c)
  result.n = newNodeI(nkRange, n.info)
  if (n[1].kind == nkEmpty) or (n[2].kind == nkEmpty): 
    LocalError(n.Info, errRangeIsEmpty)
  var a = semConstExpr(c, n[1])
  var b = semConstExpr(c, n[2])
  if not sameType(a.typ, b.typ): 
    LocalError(n.info, errPureTypeMismatch)
  elif a.typ.kind notin {tyInt..tyInt64,tyEnum,tyBool,tyChar,
                         tyFloat..tyFloat128,tyUInt8..tyUInt32}:
    LocalError(n.info, errOrdinalTypeExpected)
  elif enumHasHoles(a.typ): 
    LocalError(n.info, errEnumXHasHoles, a.typ.sym.name.s)
  elif not leValue(a, b): LocalError(n.Info, errRangeIsEmpty)
  addSon(result.n, a)
  addSon(result.n, b)
  addSonSkipIntLit(result, b.typ)

proc semRange(c: PContext, n: PNode, prev: PType): PType =
  result = nil
  if sonsLen(n) == 2:
    if isRange(n[1]): result = semRangeAux(c, n[1], prev)
    else:
      LocalError(n.sons[0].info, errRangeExpected)
      result = newOrPrevType(tyError, prev, c)
  else:
    LocalError(n.info, errXExpectsOneTypeParam, "range")
    result = newOrPrevType(tyError, prev, c)

proc semArray(c: PContext, n: PNode, prev: PType): PType = 
  var indx, base: PType
  result = newOrPrevType(tyArray, prev, c)
  if sonsLen(n) == 3: 
    # 3 = length(array indx base)
    if isRange(n[1]): indx = semRangeAux(c, n[1], nil)
    else: indx = semTypeNode(c, n.sons[1], nil)
    addSonSkipIntLit(result, indx)
    if indx.kind == tyGenericInst: indx = lastSon(indx)
    if indx.kind != tyGenericParam: 
      if not isOrdinalType(indx): 
        LocalError(n.sons[1].info, errOrdinalTypeExpected)
      elif enumHasHoles(indx): 
        LocalError(n.sons[1].info, errEnumXHasHoles, indx.sym.name.s)
    base = semTypeNode(c, n.sons[2], nil)
    addSonSkipIntLit(result, base)
  else: 
    LocalError(n.info, errArrayExpectsTwoTypeParams)
    result = newOrPrevType(tyError, prev, c)
  
proc semOrdinal(c: PContext, n: PNode, prev: PType): PType = 
  result = newOrPrevType(tyOrdinal, prev, c)
  if sonsLen(n) == 2: 
    var base = semTypeNode(c, n.sons[1], nil)
    if base.kind != tyGenericParam: 
      if not isOrdinalType(base): 
        LocalError(n.sons[1].info, errOrdinalTypeExpected)
    addSonSkipIntLit(result, base)
  else:
    LocalError(n.info, errXExpectsOneTypeParam, "ordinal")
    result = newOrPrevType(tyError, prev, c)
  
proc semTypeIdent(c: PContext, n: PNode): PSym =
  if n.kind == nkSym: 
    result = n.sym
  else:
    result = qualifiedLookup(c, n, {checkAmbiguity, checkUndeclared})
    if result != nil:
      markUsed(n, result)
      if result.kind == skParam and result.typ.kind == tyTypeDesc:
        # This is a typedesc param. is it already bound?
        # it's not bound when it's also used as return type for example
        if result.typ.sonsLen > 0:
          let bound = result.typ.sons[0].sym
          if bound != nil:
            return bound
          else:
            return result.typ.sym
        else:
          return result.typ.sym
      if result.kind != skType: 
        # this implements the wanted ``var v: V, x: V`` feature ...
        var ov: TOverloadIter
        var amb = InitOverloadIter(ov, c, n)
        while amb != nil and amb.kind != skType:
          amb = nextOverloadIter(ov, c, n)
        if amb != nil: result = amb
        else:
          if result.kind != skError: LocalError(n.info, errTypeExpected)
          return errorSym(c, n)
      if result.typ.kind != tyGenericParam:
        # XXX get rid of this hack!
        var oldInfo = n.info
        reset(n[])
        n.kind = nkSym
        n.sym = result
        n.info = oldInfo
    else:
      LocalError(n.info, errIdentifierExpected)
      result = errorSym(c, n)
  
proc semTuple(c: PContext, n: PNode, prev: PType): PType = 
  if n.sonsLen == 0: return newConstraint(c, tyTuple)
  var typ: PType
  result = newOrPrevType(tyTuple, prev, c)
  result.n = newNodeI(nkRecList, n.info)
  var check = initIntSet()
  var counter = 0
  for i in countup(0, sonsLen(n) - 1): 
    var a = n.sons[i]
    if (a.kind != nkIdentDefs): IllFormedAst(a)
    checkMinSonsLen(a, 3)
    var length = sonsLen(a)
    if a.sons[length - 2].kind != nkEmpty: 
      typ = semTypeNode(c, a.sons[length - 2], nil)
    else:
      LocalError(a.info, errTypeExpected)
      typ = errorType(c)
    if a.sons[length - 1].kind != nkEmpty: 
      LocalError(a.sons[length - 1].info, errInitHereNotAllowed)
    for j in countup(0, length - 3): 
      var field = newSymG(skField, a.sons[j], c)
      field.typ = typ
      field.position = counter
      inc(counter)
      if ContainsOrIncl(check, field.name.id): 
        LocalError(a.sons[j].info, errAttemptToRedefine, field.name.s)
      else:
        addSon(result.n, newSymNode(field))
        addSonSkipIntLit(result, typ)

proc semIdentVis(c: PContext, kind: TSymKind, n: PNode, 
                 allowed: TSymFlags): PSym = 
  # identifier with visibility
  if n.kind == nkPostfix: 
    if sonsLen(n) == 2 and n.sons[0].kind == nkIdent: 
      # for gensym'ed identifiers the identifier may already have been
      # transformed to a symbol and we need to use that here:
      result = newSymG(kind, n.sons[1], c)
      var v = n.sons[0].ident
      if sfExported in allowed and v.id == ord(wStar): 
        incl(result.flags, sfExported)
      else:
        LocalError(n.sons[0].info, errInvalidVisibilityX, v.s)
    else:
      illFormedAst(n)
  else:
    result = newSymG(kind, n, c)
  
proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode, 
                        allowed: TSymFlags): PSym = 
  if n.kind == nkPragmaExpr: 
    checkSonsLen(n, 2)
    result = semIdentVis(c, kind, n.sons[0], allowed)
    case kind
    of skType: 
      # process pragmas later, because result.typ has not been set yet
    of skField: pragma(c, result, n.sons[1], fieldPragmas)
    of skVar:   pragma(c, result, n.sons[1], varPragmas)
    of skLet:   pragma(c, result, n.sons[1], letPragmas)
    of skConst: pragma(c, result, n.sons[1], constPragmas)
    else: nil
  else:
    result = semIdentVis(c, kind, n, allowed)
  
proc checkForOverlap(c: PContext, t, ex: PNode, branchIndex: int) = 
  let ex = ex.skipConv
  for i in countup(1, branchIndex - 1): 
    for j in countup(0, sonsLen(t.sons[i]) - 2): 
      if overlap(t.sons[i].sons[j].skipConv, ex): 
        LocalError(ex.info, errDuplicateCaseLabel)
  
proc semBranchRange(c: PContext, t, a, b: PNode, covered: var biggestInt): PNode =
  checkMinSonsLen(t, 1)
  let ac = semConstExpr(c, a)
  let bc = semConstExpr(c, b)
  let at = fitNode(c, t.sons[0].typ, ac)
  let bt = fitNode(c, t.sons[0].typ, bc)
  
  result = newNodeI(nkRange, a.info)
  result.add(at)
  result.add(bt)
  if emptyRange(ac, bc): LocalError(b.info, errRangeIsEmpty)
  else: covered = covered + getOrdValue(bc) - getOrdValue(ac) + 1

proc SemCaseBranchRange(c: PContext, t, b: PNode, 
                        covered: var biggestInt): PNode = 
  checkSonsLen(b, 3)
  result = semBranchRange(c, t, b.sons[1], b.sons[2], covered)

proc semCaseBranchSetElem(c: PContext, t, b: PNode, 
                          covered: var biggestInt): PNode = 
  if isRange(b):
    checkSonsLen(b, 3)
    result = semBranchRange(c, t, b.sons[1], b.sons[2], covered)
  elif b.kind == nkRange:
    checkSonsLen(b, 2)
    result = semBranchRange(c, t, b.sons[0], b.sons[1], covered)
  else:
    result = fitNode(c, t.sons[0].typ, b)
    inc(covered)

proc semCaseBranch(c: PContext, t, branch: PNode, branchIndex: int, 
                   covered: var biggestInt) = 
  for i in countup(0, sonsLen(branch) - 2): 
    var b = branch.sons[i]
    if b.kind == nkRange:
      branch.sons[i] = b
    elif isRange(b):
      branch.sons[i] = semCaseBranchRange(c, t, b, covered)
    else:
      var r = semConstExpr(c, b)
      # for ``{}`` we want to trigger the type mismatch in ``fitNode``:
      if r.kind != nkCurly or len(r) == 0:
        checkMinSonsLen(t, 1)
        branch.sons[i] = fitNode(c, t.sons[0].typ, r)
        inc(covered)
      else:
        # constant sets have special rules
        # first element is special and will overwrite: branch.sons[i]:
        branch.sons[i] = semCaseBranchSetElem(c, t, r[0], covered)
        # other elements have to be added to ``branch``
        for j in 1 .. <r.len:
          branch.add(semCaseBranchSetElem(c, t, r[j], covered))
          # caution! last son of branch must be the actions to execute:
          var L = branch.len
          swap(branch.sons[L-2], branch.sons[L-1])
    checkForOverlap(c, t, branch.sons[i], branchIndex)
     
proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, 
                      father: PNode, rectype: PSym)
proc semRecordCase(c: PContext, n: PNode, check: var TIntSet, pos: var int, 
                   father: PNode, rectype: PSym) = 
  var a = copyNode(n)
  checkMinSonsLen(n, 2)
  semRecordNodeAux(c, n.sons[0], check, pos, a, rectype)
  if a.sons[0].kind != nkSym: 
    internalError("semRecordCase: discriminant is no symbol")
    return
  incl(a.sons[0].sym.flags, sfDiscriminant)
  var covered: biggestInt = 0
  var typ = skipTypes(a.sons[0].Typ, abstractVar)
  if not isOrdinalType(typ): 
    LocalError(n.info, errSelectorMustBeOrdinal)
  elif firstOrd(typ) < 0: 
    LocalError(n.info, errOrdXMustNotBeNegative, a.sons[0].sym.name.s)
  elif lengthOrd(typ) > 0x00007FFF: 
    LocalError(n.info, errLenXinvalid, a.sons[0].sym.name.s)
  var chckCovered = true
  for i in countup(1, sonsLen(n) - 1): 
    var b = copyTree(n.sons[i])
    case n.sons[i].kind
    of nkOfBranch: 
      checkMinSonsLen(b, 2)
      semCaseBranch(c, a, b, i, covered)
    of nkElse: 
      chckCovered = false
      checkSonsLen(b, 1)
    else: illFormedAst(n)
    delSon(b, sonsLen(b) - 1)
    semRecordNodeAux(c, lastSon(n.sons[i]), check, pos, b, rectype)
    addSon(a, b)
  if chckCovered and (covered != lengthOrd(a.sons[0].typ)): 
    localError(a.info, errNotAllCasesCovered)
  addSon(father, a)

proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, 
                      father: PNode, rectype: PSym) = 
  if n == nil: return
  case n.kind
  of nkRecWhen:
    var branch: PNode = nil   # the branch to take
    for i in countup(0, sonsLen(n) - 1):
      var it = n.sons[i]
      if it == nil: illFormedAst(n)
      var idx = 1
      case it.kind
      of nkElifBranch:
        checkSonsLen(it, 2)
        if c.InGenericContext == 0:
          var e = semConstBoolExpr(c, it.sons[0])
          if e.kind != nkIntLit: InternalError(e.info, "semRecordNodeAux")
          elif e.intVal != 0 and branch == nil: branch = it.sons[1]
        else:
          it.sons[0] = forceBool(c, semExprWithType(c, it.sons[0]))
      of nkElse:
        checkSonsLen(it, 1)
        if branch == nil: branch = it.sons[0]
        idx = 0
      else: illFormedAst(n)
      if c.InGenericContext > 0:
        # use a new check intset here for each branch:
        var newCheck: TIntSet
        assign(newCheck, check)
        var newPos = pos
        var newf = newNodeI(nkRecList, n.info)
        semRecordNodeAux(c, it.sons[idx], newcheck, newpos, newf, rectype)
        it.sons[idx] = if newf.len == 1: newf[0] else: newf
    if c.InGenericContext > 0:
      addSon(father, n)
    elif branch != nil:
      semRecordNodeAux(c, branch, check, pos, father, rectype)
  of nkRecCase:
    semRecordCase(c, n, check, pos, father, rectype)
  of nkNilLit: 
    if father.kind != nkRecList: addSon(father, newNodeI(nkRecList, n.info))
  of nkRecList: 
    # attempt to keep the nesting at a sane level:
    var a = if father.kind == nkRecList: father else: copyNode(n)
    for i in countup(0, sonsLen(n) - 1): 
      semRecordNodeAux(c, n.sons[i], check, pos, a, rectype)
    if a != father: addSon(father, a)
  of nkIdentDefs:
    checkMinSonsLen(n, 3)
    var length = sonsLen(n)
    var a: PNode
    if father.kind != nkRecList and length >= 4: a = newNodeI(nkRecList, n.info)
    else: a = ast.emptyNode
    if n.sons[length-1].kind != nkEmpty: 
      localError(n.sons[length-1].info, errInitHereNotAllowed)
    var typ: PType
    if n.sons[length-2].kind == nkEmpty: 
      LocalError(n.info, errTypeExpected)
      typ = errorType(c)
    else:
      typ = semTypeNode(c, n.sons[length-2], nil)
    for i in countup(0, sonsLen(n)-3):
      var f = semIdentWithPragma(c, skField, n.sons[i], {sfExported})
      suggestSym(n.sons[i], f)
      f.typ = typ
      f.position = pos
      if (rectype != nil) and ({sfImportc, sfExportc} * rectype.flags != {}) and
          (f.loc.r == nil): 
        f.loc.r = toRope(f.name.s)
        f.flags = f.flags + ({sfImportc, sfExportc} * rectype.flags)
      inc(pos)
      if ContainsOrIncl(check, f.name.id): 
        localError(n.sons[i].info, errAttemptToRedefine, f.name.s)
      if a.kind == nkEmpty: addSon(father, newSymNode(f))
      else: addSon(a, newSymNode(f))
    if a.kind != nkEmpty: addSon(father, a)
  of nkEmpty: nil
  else: illFormedAst(n)
  
proc addInheritedFieldsAux(c: PContext, check: var TIntSet, pos: var int, 
                           n: PNode) = 
  case n.kind
  of nkRecCase: 
    if (n.sons[0].kind != nkSym): InternalError(n.info, "addInheritedFieldsAux")
    addInheritedFieldsAux(c, check, pos, n.sons[0])
    for i in countup(1, sonsLen(n) - 1): 
      case n.sons[i].kind
      of nkOfBranch, nkElse: 
        addInheritedFieldsAux(c, check, pos, lastSon(n.sons[i]))
      else: internalError(n.info, "addInheritedFieldsAux(record case branch)")
  of nkRecList: 
    for i in countup(0, sonsLen(n) - 1): 
      addInheritedFieldsAux(c, check, pos, n.sons[i])
  of nkSym: 
    Incl(check, n.sym.name.id)
    inc(pos)
  else: InternalError(n.info, "addInheritedFieldsAux()")
  
proc addInheritedFields(c: PContext, check: var TIntSet, pos: var int, 
                        obj: PType) = 
  if (sonsLen(obj) > 0) and (obj.sons[0] != nil): 
    addInheritedFields(c, check, pos, obj.sons[0])
  addInheritedFieldsAux(c, check, pos, obj.n)

proc skipGenericInvokation(t: PType): PType {.inline.} = 
  result = t
  if result.kind == tyGenericInvokation:
    result = result.sons[0]
  if result.kind == tyGenericBody:
    result = lastSon(result)

proc semObjectNode(c: PContext, n: PNode, prev: PType): PType =
  if n.sonsLen == 0: return newConstraint(c, tyObject)
  var check = initIntSet()
  var pos = 0 
  var base: PType = nil
  # n.sons[0] contains the pragmas (if any). We process these later...
  checkSonsLen(n, 3)
  if n.sons[1].kind != nkEmpty: 
    base = skipTypes(semTypeNode(c, n.sons[1].sons[0], nil), skipPtrs)
    var concreteBase = skipGenericInvokation(base)
    if concreteBase.kind == tyObject and tfFinal notin concreteBase.flags: 
      addInheritedFields(c, check, pos, concreteBase)
    else:
      if concreteBase.kind != tyError:
        localError(n.sons[1].info, errInheritanceOnlyWithNonFinalObjects)
      base = nil
  if n.kind != nkObjectTy: InternalError(n.info, "semObjectNode")
  result = newOrPrevType(tyObject, prev, c)
  rawAddSon(result, base)
  result.n = newNodeI(nkRecList, n.info)
  semRecordNodeAux(c, n.sons[2], check, pos, result.n, result.sym)
  if n.sons[0].kind != nkEmpty:
    # dummy symbol for `pragma`:
    var s = newSymS(skType, newIdentNode(getIdent("dummy"), n.info), c)
    s.typ = result
    pragma(c, s, n.sons[0], typePragmas)
  if base == nil and tfInheritable notin result.flags:
    incl(result.flags, tfFinal)
  
proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind) =
  if kind == skMacro and param.typ.kind != tyTypeDesc:
    # within a macro, every param has the type PNimrodNode!
    # and param.typ.kind in {tyTypeDesc, tyExpr, tyStmt}:
    let nn = getSysSym"PNimrodNode"
    var a = copySym(param)
    a.typ = nn.typ
    if sfGenSym notin a.flags: addDecl(c, a)
  else:
    if sfGenSym notin param.flags: addDecl(c, param)

proc paramTypeClass(c: PContext, paramType: PType, procKind: TSymKind):
  tuple[typ: PType, id: PIdent] =
  # if typ is not-nil, the param should be turned into a generic param
  # if id is not nil, the generic param will bind just once (see below)
  case paramType.kind:
  of tyExpr:
    if procKind notin {skTemplate, skMacro}:
      if paramType.sonsLen == 0:
        # proc(a, b: expr)
        # no constraints, treat like generic param
        result.typ = newTypeS(tyGenericParam, c)
      else:
        # proc(a: expr{string}, b: expr{nkLambda})
        # overload on compile time values and AST trees
        result.typ = newTypeS(tyExpr, c)
        result.typ.sons = paramType.sons
  of tyTypeDesc:
    if procKind notin {skTemplate, skMacro} and 
       tfInstantiated notin paramType.flags:
      result.typ = newTypeS(tyTypeDesc, c)
      result.typ.sons = paramType.sons
  of tyDistinct:
    result = paramTypeClass(c, paramType.lastSon, procKind)
    # disable the bindOnce behavior for the type class
    result.id = nil
    return
  of tyGenericBody:
    # type Foo[T] = object
    # proc x(a: Foo, b: Foo) 
    result.typ = newTypeS(tyTypeClass, c)
    result.typ.addSonSkipIntLit(paramType)
  of tyTypeClass:
    result.typ = copyType(paramType, getCurrOwner(), false)
  else: nil
  # bindOnce by default
  if paramType.sym != nil: result.id = paramType.sym.name

proc liftParamType(c: PContext, procKind: TSymKind, genericParams: PNode,
                   paramType: PType, paramName: string,
                   info: TLineInfo): PType =
  ## Params having implicit generic types or pseudo types such as 'expr'
  ## need to be added to the generic params lists. 
  ## 'expr' is different from 'expr{string}' so we must first call 
  ## paramTypeClass to get the actual type we are going to use.
  result = paramType
  var (typeClass, paramTypId) = paramTypeClass(c, paramType, procKind)
  let isAnon = paramTypId == nil
  if typeClass != nil:
    if isAnon: paramTypId = getIdent(paramName & ":type")
    if genericParams == nil:
      # genericParams is nil when the proc is being instantiated
      # the resolved type will be in scope then
      let s = SymtabGet(c.tab, paramTypId)
      # tests/run/tinterf triggers this:
      if s != nil: result = s.typ
      else:
        LocalError(info, errCannotInstantiateX, paramName)
        result = errorType(c)
    else:
      block addImplicitGeneric:
        # is this a bindOnce type class already present in the param list?
        for i in countup(0, genericParams.len - 1):
          if genericParams.sons[i].sym.name.id == paramTypId.id:
            result = genericParams.sons[i].typ
            break addImplicitGeneric

        var s = newSym(skType, paramTypId, getCurrOwner(), info)
        if isAnon: s.flags.incl(sfAnon)
        s.linkTo(typeClass)
        s.position = genericParams.len
        genericParams.addSon(newSymNode(s))
        result = typeClass

proc semProcTypeNode(c: PContext, n, genericParams: PNode, 
                     prev: PType, kind: TSymKind): PType = 
  var
    res: PNode
    cl: TIntSet
  checkMinSonsLen(n, 1)
  result = newOrPrevType(tyProc, prev, c)
  result.callConv = lastOptionEntry(c).defaultCC
  result.n = newNodeI(nkFormalParams, n.info)
  if genericParams != nil and sonsLen(genericParams) == 0:
    cl = initIntSet()
  rawAddSon(result, nil) # return type
  # result.n[0] used to be `nkType`, but now it's `nkEffectList` because 
  # the effects are now stored in there too ... this is a bit hacky, but as
  # usual we desperately try to save memory:
  res = newNodeI(nkEffectList, n.info)
  addSon(result.n, res)
  var check = initIntSet()
  var counter = 0
  for i in countup(1, n.len - 1):
    var a = n.sons[i]
    if a.kind != nkIdentDefs: IllFormedAst(a)
    checkMinSonsLen(a, 3)
    var
      typ: PType = nil
      def: PNode = nil      
      length = sonsLen(a)
      hasType = a.sons[length-2].kind != nkEmpty
      hasDefault = a.sons[length-1].kind != nkEmpty

    if hasType:
      typ = semTypeNode(c, a.sons[length-2], nil)
      
    if hasDefault:
      def = semExprWithType(c, a.sons[length-1]) 
      # check type compability between def.typ and typ:
      if typ == nil:
        typ = def.typ
      elif def != nil:
        # and def.typ != nil and def.typ.kind != tyNone:
        # example code that triggers it:
        # proc sort[T](cmp: proc(a, b: T): int = cmp)
        if not containsGenericType(typ):
          def = fitNode(c, typ, def)
    if not (hasType or hasDefault):
      typ = newTypeS(tyExpr, c)
      
    if skipTypes(typ, {tyGenericInst}).kind == tyEmpty: continue
    for j in countup(0, length-3): 
      var arg = newSymG(skParam, a.sons[j], c)
      var finalType = liftParamType(c, kind, genericParams, typ,
                                    arg.name.s, arg.info).skipIntLit
      arg.typ = finalType
      arg.position = counter
      inc(counter)
      if def != nil and def.kind != nkEmpty: arg.ast = copyTree(def)
      if ContainsOrIncl(check, arg.name.id): 
        LocalError(a.sons[j].info, errAttemptToRedefine, arg.name.s)
      addSon(result.n, newSymNode(arg))
      rawAddSon(result, finalType)
      addParamOrResult(c, arg, kind)

  if n.sons[0].kind != nkEmpty:
    var r = semTypeNode(c, n.sons[0], nil)
    # turn explicit 'void' return type into 'nil' because the rest of the 
    # compiler only checks for 'nil':
    if skipTypes(r, {tyGenericInst}).kind != tyEmpty:
      if r.sym == nil or sfAnon notin r.sym.flags:
        r = liftParamType(c, kind, genericParams, r, "result", n.sons[0].info)
        r.flags.incl tfRetType
      result.sons[0] = skipIntLit(r)
      res.typ = result.sons[0]

proc semStmtListType(c: PContext, n: PNode, prev: PType): PType =
  checkMinSonsLen(n, 1)
  var length = sonsLen(n)
  for i in countup(0, length - 2):
    n.sons[i] = semStmt(c, n.sons[i])
  if length > 0:
    result = semTypeNode(c, n.sons[length - 1], prev)
    n.typ = result
    n.sons[length - 1].typ = result
  else:
    result = nil
  
proc semBlockType(c: PContext, n: PNode, prev: PType): PType = 
  Inc(c.p.nestedBlockCounter)
  checkSonsLen(n, 2)
  openScope(c.tab)
  if n.sons[0].kind notin {nkEmpty, nkSym}:
    addDecl(c, newSymS(skLabel, n.sons[0], c))
  result = semStmtListType(c, n.sons[1], prev)
  n.sons[1].typ = result
  n.typ = result
  closeScope(c.tab)
  Dec(c.p.nestedBlockCounter)

proc semGenericParamInInvokation(c: PContext, n: PNode): PType =
  # XXX hack 1022 for generics ... would have been nice if the compiler had
  # been designed with them in mind from start ...
  when false:
    if n.kind == nkSym:
      # for generics we need to lookup the type var again:
      var s = SymtabGet(c.Tab, n.sym.name)
      if s != nil:
        if s.kind == skType and s.typ != nil:
          var t = n.sym.typ
          echo "came here"
          return t
        else:
          echo "s is crap:"
          debug(s)
      else:
        echo "s is nil!!!!"
  result = semTypeNode(c, n, nil)

proc semGeneric(c: PContext, n: PNode, s: PSym, prev: PType): PType = 
  result = newOrPrevType(tyGenericInvokation, prev, c)
  var isConcrete = true
  if s.typ == nil:
    LocalError(n.info, errCannotInstantiateX, s.name.s)
    return newOrPrevType(tyError, prev, c)
  elif s.typ.kind != tyGenericBody:
    isConcrete = false
  elif s.typ.containerID == 0: 
    InternalError(n.info, "semtypes.semGeneric")
    return newOrPrevType(tyError, prev, c)
  elif sonsLen(n) != sonsLen(s.typ): 
    LocalError(n.info, errWrongNumberOfArguments)
    return newOrPrevType(tyError, prev, c)
  addSonSkipIntLit(result, s.typ)
  # iterate over arguments:
  for i in countup(1, sonsLen(n)-1):
    var elem = semGenericParamInInvokation(c, n.sons[i])
    if containsGenericType(elem): isConcrete = false
    #if elem.kind in {tyGenericParam, tyGenericInvokation}: isConcrete = false
    if elem.isNil: rawAddSon(result, elem)
    else: addSonSkipIntLit(result, elem)
  if isConcrete:
    if s.ast == nil: 
      LocalError(n.info, errCannotInstantiateX, s.name.s)
      result = newOrPrevType(tyError, prev, c)
    else:
      result = instGenericContainer(c, n, result)

proc semTypeExpr(c: PContext, n: PNode): PType =
  var n = semExprWithType(c, n)
  if n.kind == nkSym and n.sym.kind == skType:
    result = n.sym.typ
  else:
    LocalError(n.info, errTypeExpected, n.renderTree)

proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
  result = nil
  if gCmd == cmdIdeTools: suggestExpr(c, n)
  case n.kind
  of nkEmpty: nil
  of nkTypeOfExpr:
    # for ``type(countup(1,3))``, see ``tests/ttoseq``.
    checkSonsLen(n, 1)
    result = semExprWithType(c, n.sons[0], {efInTypeof}).typ
  of nkPar: 
    if sonsLen(n) == 1: result = semTypeNode(c, n.sons[0], prev)
    else:
      # XXX support anon tuple here
      LocalError(n.info, errTypeExpected)
      result = newOrPrevType(tyError, prev, c)
  of nkCallKinds:
    if n[0].kind == nkIdent:
      let op = n.sons[0].ident
      if op.id in {ord(wAnd), ord(wOr)} or op.s == "|":
        checkSonsLen(n, 3)
        var
          t1 = semTypeNode(c, n.sons[1], nil)
          t2 = semTypeNode(c, n.sons[2], nil)
        if t1 == nil: 
          LocalError(n.sons[1].info, errTypeExpected)
          result = newOrPrevType(tyError, prev, c)
        elif t2 == nil: 
          LocalError(n.sons[2].info, errTypeExpected)
          result = newOrPrevType(tyError, prev, c)
        else:
          result = newTypeS(tyTypeClass, c)
          result.addSonSkipIntLit(t1)
          result.addSonSkipIntLit(t2)
          result.flags.incl(if op.id == ord(wAnd): tfAll else: tfAny)
      elif op.id == ord(wNot):
        checkSonsLen(n, 3)
        result = semTypeNode(c, n.sons[1], prev)
        if result.kind in NilableTypes and n.sons[2].kind == nkNilLit:
          result.flags.incl(tfNotNil)
        else:
          LocalError(n.info, errGenerated, "invalid type")
      else:
        result = semTypeExpr(c, n)
    else:
      result = semTypeExpr(c, n)
  of nkCurlyExpr:
    result = semTypeNode(c, n.sons[0], nil)
    if result != nil:
      result = copyType(result, getCurrOwner(), true)
      result.constraint = semNodeKindConstraints(n)
  of nkWhenStmt:
    var whenResult = semWhen(c, n, false)
    if whenResult.kind == nkStmtList: whenResult.kind = nkStmtListType
    result = semTypeNode(c, whenResult, prev)
  of nkBracketExpr:
    checkMinSonsLen(n, 2)
    var s = semTypeIdent(c, n.sons[0])
    case s.magic
    of mArray: result = semArray(c, n, prev)
    of mOpenArray: result = semContainer(c, n, tyOpenArray, "openarray", prev)
    of mRange: result = semRange(c, n, prev)
    of mSet: result = semSet(c, n, prev)
    of mOrdinal: result = semOrdinal(c, n, prev)
    of mSeq: result = semContainer(c, n, tySequence, "seq", prev)
    of mVarargs: result = semVarargs(c, n, prev)
    of mExpr, mTypeDesc:
      result = semTypeNode(c, n.sons[0], nil)
      if result != nil:
        result = copyType(result, getCurrOwner(), false)
        for i in countup(1, n.len - 1):
          result.rawAddSon(semTypeNode(c, n.sons[i], nil))
    else: result = semGeneric(c, n, s, prev)
  of nkIdent, nkDotExpr, nkAccQuoted: 
    var s = semTypeIdent(c, n)
    if s.typ == nil: 
      if s.kind != skError: LocalError(n.info, errTypeExpected)
      result = newOrPrevType(tyError, prev, c)
    elif prev == nil:
      result = s.typ
    else: 
      assignType(prev, s.typ)
      # bugfix: keep the fresh id for aliases to integral types:
      if s.typ.kind notin {tyBool, tyChar, tyInt..tyInt64, tyFloat..tyFloat128,
                           tyUInt..tyUInt64}: 
        prev.id = s.typ.id
      result = prev
  of nkSym:
    if n.sym.kind == skType and n.sym.typ != nil:
      var t = n.sym.typ
      if prev == nil: 
        result = t
      else: 
        assignType(prev, t)
        result = prev
      markUsed(n, n.sym)
    else:
      if n.sym.kind != skError: LocalError(n.info, errTypeExpected)
      result = newOrPrevType(tyError, prev, c)
  of nkObjectTy: result = semObjectNode(c, n, prev)
  of nkTupleTy: result = semTuple(c, n, prev)
  of nkRefTy: result = semAnyRef(c, n, tyRef, prev)
  of nkPtrTy: result = semAnyRef(c, n, tyPtr, prev)
  of nkVarTy: result = semVarType(c, n, prev)
  of nkDistinctTy: result = semDistinct(c, n, prev)
  of nkProcTy, nkIteratorTy:
    if n.sonsLen == 0:
      result = newConstraint(c, tyProc)
    else:
      checkSonsLen(n, 2)
      openScope(c.tab)
      result = semProcTypeNode(c, n.sons[0], nil, prev, skProc)
      # dummy symbol for `pragma`:
      var s = newSymS(skProc, newIdentNode(getIdent("dummy"), n.info), c)
      s.typ = result
      if n.sons[1].kind == nkEmpty or n.sons[1].len == 0:
        if result.callConv == ccDefault:
          result.callConv = ccClosure
          #Message(n.info, warnImplicitClosure, renderTree(n))
      else:
        pragma(c, s, n.sons[1], procTypePragmas)
        when useEffectSystem: SetEffectsForProcType(result, n.sons[1])
      closeScope(c.tab)
    if n.kind == nkIteratorTy:
      result.flags.incl(tfIterator)
  of nkEnumTy: result = semEnum(c, n, prev)
  of nkType: result = n.typ
  of nkStmtListType: result = semStmtListType(c, n, prev)
  of nkBlockType: result = semBlockType(c, n, prev)
  of nkSharedTy:
    checkSonsLen(n, 1)
    result = semTypeNode(c, n.sons[0], prev)
    result.flags.incl(tfShared)
  else:
    LocalError(n.info, errTypeExpected)
    result = newOrPrevType(tyError, prev, c)
  
proc setMagicType(m: PSym, kind: TTypeKind, size: int) = 
  m.typ.kind = kind
  m.typ.align = size
  m.typ.size = size
  
proc processMagicType(c: PContext, m: PSym) = 
  case m.magic
  of mInt: setMagicType(m, tyInt, intSize)
  of mInt8: setMagicType(m, tyInt8, 1)
  of mInt16: setMagicType(m, tyInt16, 2)
  of mInt32: setMagicType(m, tyInt32, 4)
  of mInt64: setMagicType(m, tyInt64, 8)
  of mUInt: setMagicType(m, tyUInt, intSize)
  of mUInt8: setMagicType(m, tyUInt8, 1)
  of mUInt16: setMagicType(m, tyUInt16, 2)
  of mUInt32: setMagicType(m, tyUInt32, 4)
  of mUInt64: setMagicType(m, tyUInt64, 8)
  of mFloat: setMagicType(m, tyFloat, floatSize)
  of mFloat32: setMagicType(m, tyFloat32, 4)
  of mFloat64: setMagicType(m, tyFloat64, 8)
  of mFloat128: setMagicType(m, tyFloat128, 16)
  of mBool: setMagicType(m, tyBool, 1)
  of mChar: setMagicType(m, tyChar, 1)
  of mString: 
    setMagicType(m, tyString, ptrSize)
    rawAddSon(m.typ, getSysType(tyChar))
  of mCstring: 
    setMagicType(m, tyCString, ptrSize)
    rawAddSon(m.typ, getSysType(tyChar))
  of mPointer: setMagicType(m, tyPointer, ptrSize)
  of mEmptySet: 
    setMagicType(m, tySet, 1)
    rawAddSon(m.typ, newTypeS(tyEmpty, c))
  of mIntSetBaseType: setMagicType(m, tyRange, intSize)
  of mNil: setMagicType(m, tyNil, ptrSize)
  of mExpr: setMagicType(m, tyExpr, 0)
  of mStmt: setMagicType(m, tyStmt, 0)
  of mTypeDesc: setMagicType(m, tyTypeDesc, 0)
  of mVoidType: setMagicType(m, tyEmpty, 0)
  of mArray: setMagicType(m, tyArray, 0)
  of mOpenArray: setMagicType(m, tyOpenArray, 0)
  of mVarargs: setMagicType(m, tyVarargs, 0)
  of mRange: setMagicType(m, tyRange, 0)
  of mSet: setMagicType(m, tySet, 0) 
  of mSeq: setMagicType(m, tySequence, 0)
  of mOrdinal: setMagicType(m, tyOrdinal, 0)
  of mPNimrodNode: nil
  else: LocalError(m.info, errTypeExpected)
  
proc semGenericConstraints(c: PContext, n: PNode, result: PType) = 
  var x = semTypeNode(c, n, nil)
  if x.kind in StructuralEquivTypes and (
      sonsLen(x) == 0 or x.sons[0].kind in {tyGenericParam, tyEmpty}):
    x = newConstraint(c, x.kind)
  result.addSonSkipIntLit(x)

proc semGenericParamList(c: PContext, n: PNode, father: PType = nil): PNode = 
  result = copyNode(n)
  if n.kind != nkGenericParams: 
    illFormedAst(n)
    return
  for i in countup(0, sonsLen(n)-1): 
    var a = n.sons[i]
    if a.kind != nkIdentDefs: illFormedAst(n)
    var L = sonsLen(a)
    var def = a.sons[L-1]
    var typ: PType
    if a.sons[L-2].kind != nkEmpty: 
      typ = newTypeS(tyGenericParam, c)
      semGenericConstraints(c, a.sons[L-2], typ)
      if sonsLen(typ) == 1 and typ.sons[0].kind == tyTypeDesc:
        typ = typ.sons[0]
    elif def.kind != nkEmpty: typ = newTypeS(tyExpr, c)
    else: typ = nil
    for j in countup(0, L-3): 
      var s: PSym
      if typ == nil:
        s = newSymG(skType, a.sons[j], c)
        s.typ = newTypeS(tyGenericParam, c)
      else:
        case typ.kind
        of tyTypeDesc: 
          s = newSymG(skType, a.sons[j], c)
          s.typ = newTypeS(tyGenericParam, c)
        of tyExpr:
          #echo "GENERIC EXPR ", a.info.toFileLineCol
          # not a type param, but an expression
          # proc foo[x: expr](bar: int) what is this?
          s = newSymG(skGenericParam, a.sons[j], c)
          s.typ = typ
        else:
          # This handles cases like proc foo[t: tuple] 
          # XXX: we want to turn that into a type class
          s = newSymG(skType, a.sons[j], c)
          s.typ = typ
      if def.kind != nkEmpty: s.ast = def
      s.typ.sym = s
      if father != nil: addSonSkipIntLit(father, s.typ)
      s.position = i
      addSon(result, newSymNode(s))
      if sfGenSym notin s.flags: addDecl(c, s)