summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2009-05-10 22:35:58 +0200
committerAndreas Rumpf <rumpf_a@web.de>2009-05-10 22:35:58 +0200
commitc7e144f97810630d8ab4f396f299c6355fc93ba7 (patch)
treef013e592eb209b66d3b56401e8c96d58929d57b1
parentd54b333e7e3df82732b70cade2e4b8591e4c2572 (diff)
downloadNim-c7e144f97810630d8ab4f396f299c6355fc93ba7.tar.gz
added missing files;change config for bug #374441
-rw-r--r--doc/tut1.txt8
-rw-r--r--doc/tut2.txt4
-rw-r--r--examples/statcsv.nim2
-rw-r--r--lib/alloc.nim6
-rw-r--r--lib/ansi_c.nim1
-rw-r--r--lib/cellsets.nim196
-rw-r--r--lib/mm.nim1
-rw-r--r--nim/highlite.pas3
-rw-r--r--nim/strutils.pas8
-rw-r--r--pycompab.py103
-rw-r--r--rod/nimrod.cfg7
11 files changed, 324 insertions, 15 deletions
diff --git a/doc/tut1.txt b/doc/tut1.txt
index 58a56e8f1..237663cdc 100644
--- a/doc/tut1.txt
+++ b/doc/tut1.txt
@@ -522,7 +522,7 @@ Result variable
 ---------------
 A procedure that returns a value has an implicit ``result`` variable that
 represents the return value. A ``return`` statement with no expression is a
-shorthand for ``return result``. So all tree code snippets are equivalent:
+shorthand for ``return result``. So all three code snippets are equivalent:
 
 .. code-block:: nimrod
   return 42
@@ -556,7 +556,7 @@ caller, a ``var`` parameter can be used:
 
 In the example, ``res`` and ``remainder`` are `var parameters`.
 Var parameters can be modified by the procedure and the changes are
-visible to the caller. 
+visible to the caller.
 
 
 Discard statement
@@ -952,8 +952,8 @@ Operation             Comment
 ``dec(x, n)``         decrements `x` by `n`; `n` is an integer
 ``succ(x)``           returns the successor of `x`
 ``succ(x, n)``        returns the `n`'th successor of `x`
-``succ(x)``           returns the predecessor of `x`
-``succ(x, n)``        returns the `n`'th predecessor of `x`
+``prec(x)``           returns the predecessor of `x`
+``pred(x, n)``        returns the `n`'th predecessor of `x`
 -----------------     --------------------------------------------------------
 
 The ``inc dec succ pred`` operations can fail by raising an `EOutOfRange` or
diff --git a/doc/tut2.txt b/doc/tut2.txt
index 6d2fd3094..114039887 100644
--- a/doc/tut2.txt
+++ b/doc/tut2.txt
@@ -34,7 +34,7 @@ While Nimrod's support for object oriented programming (OOP) is minimalistic,
 powerful OOP technics can be used. OOP is seen as *one* way to design a 
 program, not *the only* way. Often a procedural approach leads to simpler
 and more efficient code. In particular, prefering aggregation over inheritance
-often yields to a better design.
+often results in a better design.
 
 
 Objects
@@ -422,7 +422,7 @@ containers:
     else:
       var it = root
       while it != nil:
-        # compare the data items; uses the generic ``cmd`` proc
+        # compare the data items; uses the generic ``cmp`` proc
         # that works for any type that has a ``==`` and ``<`` operator
         var c = cmp(it.data, n.data) 
         if c < 0:
diff --git a/examples/statcsv.nim b/examples/statcsv.nim
index 9c1ebd113..e2f272a21 100644
--- a/examples/statcsv.nim
+++ b/examples/statcsv.nim
@@ -6,7 +6,7 @@
 import os, streams, parsecsv, strutils, math
 
 if paramCount() < 1:
-  quit("Usage: sumcsv filename[.csv]")
+  quit("Usage: statcsv filename[.csv]")
 
 var filename = appendFileExt(ParamStr(1), "csv")
 var s = newFileStream(filename, fmRead)
diff --git a/lib/alloc.nim b/lib/alloc.nim
index e4d828449..95feff854 100644
--- a/lib/alloc.nim
+++ b/lib/alloc.nim
@@ -493,6 +493,10 @@ proc rawDealloc(a: var TAllocator, p: pointer) =
     f.zeroField = 0
     f.next = c.freeList
     c.freeList = f
+    when overwriteFree: 
+      # set to 0xff to check for usage after free bugs:
+      c_memset(cast[pointer](cast[int](p) +% sizeof(TFreeCell)), -1'i32, 
+               s -% sizeof(TFreeCell))
     # check if it is not in the freeSmallChunks[s] list:
     if c.free < s:
       assert c notin a.freeSmallChunks[s div memAlign]
@@ -506,6 +510,8 @@ proc rawDealloc(a: var TAllocator, p: pointer) =
         c.size = SmallChunkSize
         freeBigChunk(a, cast[PBigChunk](c))
   else:
+    # set to 0xff to check for usage after free bugs:
+    when overwriteFree: c_memset(p, -1'i32, c.size -% bigChunkOverhead())
     # free big chunk
     freeBigChunk(a, cast[PBigChunk](c))
 
diff --git a/lib/ansi_c.nim b/lib/ansi_c.nim
index 81abd2a3e..f307fb9ab 100644
--- a/lib/ansi_c.nim
+++ b/lib/ansi_c.nim
@@ -15,6 +15,7 @@ proc c_strcmp(a, b: CString): cint {.nodecl, importc: "strcmp".}
 proc c_memcmp(a, b: CString, size: cint): cint {.nodecl, importc: "memcmp".}
 proc c_memcpy(a, b: CString, size: cint) {.nodecl, importc: "memcpy".}
 proc c_strlen(a: CString): cint {.nodecl, importc: "strlen".}
+proc c_memset(p: pointer, value: cint, size: int) {.nodecl, importc: "memset".}
 
 type
   C_TextFile {.importc: "FILE", nodecl, final.} = object   # empty record for
diff --git a/lib/cellsets.nim b/lib/cellsets.nim
new file mode 100644
index 000000000..0ce83864c
--- /dev/null
+++ b/lib/cellsets.nim
@@ -0,0 +1,196 @@
+#
+#
+#            Nimrod's Runtime Library
+#        (c) Copyright 2009 Andreas Rumpf
+#
+#    See the file "copying.txt", included in this
+#    distribution, for details about the copyright.
+#
+
+# Efficient set of pointers for the GC (and repr)
+
+type
+  TCell {.pure.} = object
+    refcount: int  # the refcount and some flags
+    typ: PNimType
+    when debugGC:
+      filename: cstring
+      line: int
+
+  PCell = ptr TCell
+
+  PPageDesc = ptr TPageDesc
+  TBitIndex = range[0..UnitsPerPage-1]
+  TPageDesc {.final, pure.} = object
+    next: PPageDesc # all nodes are connected with this pointer
+    key: TAddress   # start address at bit 0
+    bits: array[TBitIndex, int] # a bit vector
+
+  PPageDescArray = ptr array[0..1000_000, PPageDesc]
+  TCellSet {.final, pure.} = object
+    counter, max: int
+    head: PPageDesc
+    data: PPageDescArray
+
+  PCellArray = ptr array[0..100_000_000, PCell]
+  TCellSeq {.final, pure.} = object
+    len, cap: int
+    d: PCellArray
+
+# ------------------- cell set handling ---------------------------------------
+
+proc contains(s: TCellSeq, c: PCell): bool {.inline.} =
+  for i in 0 .. s.len-1:
+    if s.d[i] == c: return True
+  return False
+
+proc add(s: var TCellSeq, c: PCell) {.inline.} =
+  if s.len >= s.cap:
+    s.cap = s.cap * 3 div 2
+    var d = cast[PCellArray](alloc(s.cap * sizeof(PCell)))
+    copyMem(d, s.d, s.len * sizeof(PCell))
+    dealloc(s.d)
+    s.d = d
+    # XXX: realloc?
+  s.d[s.len] = c
+  inc(s.len)
+
+proc init(s: var TCellSeq, cap: int = 1024) =
+  s.len = 0
+  s.cap = cap
+  s.d = cast[PCellArray](alloc0(cap * sizeof(PCell)))
+
+proc deinit(s: var TCellSeq) = 
+  dealloc(s.d)
+  s.d = nil
+  s.len = 0
+  s.cap = 0
+
+const
+  InitCellSetSize = 1024 # must be a power of two!
+
+proc Init(s: var TCellSet) =
+  s.data = cast[PPageDescArray](alloc0(InitCellSetSize * sizeof(PPageDesc)))
+  s.max = InitCellSetSize-1
+  s.counter = 0
+  s.head = nil
+
+proc Deinit(s: var TCellSet) =
+  var it = s.head
+  while it != nil:
+    var n = it.next
+    dealloc(it)
+    it = n
+  s.head = nil # play it safe here
+  dealloc(s.data)
+  s.data = nil
+  s.counter = 0
+
+proc nextTry(h, maxHash: int): int {.inline.} =
+  result = ((5*h) + 1) and maxHash
+  # For any initial h in range(maxHash), repeating that maxHash times
+  # generates each int in range(maxHash) exactly once (see any text on
+  # random-number generation for proof).
+  
+proc CellSetGet(t: TCellSet, key: TAddress): PPageDesc =
+  var h = cast[int](key) and t.max
+  while t.data[h] != nil:
+    if t.data[h].key == key: return t.data[h]
+    h = nextTry(h, t.max)
+  return nil
+
+proc CellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) =
+  var h = cast[int](desc.key) and t.max
+  while data[h] != nil:
+    assert(data[h] != desc)
+    h = nextTry(h, t.max)
+  assert(data[h] == nil)
+  data[h] = desc
+
+proc CellSetEnlarge(t: var TCellSet) =
+  var oldMax = t.max
+  t.max = ((t.max+1)*2)-1
+  var n = cast[PPageDescArray](alloc0((t.max + 1) * sizeof(PPageDesc)))
+  for i in 0 .. oldmax:
+    if t.data[i] != nil:
+      CellSetRawInsert(t, n, t.data[i])
+  dealloc(t.data)
+  t.data = n
+
+proc CellSetPut(t: var TCellSet, key: TAddress): PPageDesc =
+  var h = cast[int](key) and t.max
+  while true:
+    var x = t.data[h]
+    if x == nil: break
+    if x.key == key: return x
+    h = nextTry(h, t.max)
+
+  if ((t.max+1)*2 < t.counter*3) or ((t.max+1)-t.counter < 4):
+    CellSetEnlarge(t)
+  inc(t.counter)
+  h = cast[int](key) and t.max
+  while t.data[h] != nil: h = nextTry(h, t.max)
+  assert(t.data[h] == nil)
+  # the new page descriptor goes into result
+  result = cast[PPageDesc](alloc0(sizeof(TPageDesc)))
+  result.next = t.head
+  result.key = key
+  t.head = result
+  t.data[h] = result
+
+# ---------- slightly higher level procs --------------------------------------
+
+proc contains(s: TCellSet, cell: PCell): bool =
+  var u = cast[TAddress](cell)
+  var t = CellSetGet(s, u shr PageShift)
+  if t != nil:
+    u = (u %% PageSize) /% MemAlign
+    result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0
+  else:
+    result = false
+
+proc incl(s: var TCellSet, cell: PCell) {.noinline.} =
+  var u = cast[TAddress](cell)
+  var t = CellSetPut(s, u shr PageShift)
+  u = (u %% PageSize) /% MemAlign
+  t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask))
+
+proc excl(s: var TCellSet, cell: PCell) =
+  var u = cast[TAddress](cell)
+  var t = CellSetGet(s, u shr PageShift)
+  if t != nil:
+    u = (u %% PageSize) /% MemAlign
+    t.bits[u shr IntShift] = (t.bits[u shr IntShift] and
+                              not (1 shl (u and IntMask)))
+
+proc containsOrIncl(s: var TCellSet, cell: PCell): bool = 
+  var u = cast[TAddress](cell)
+  var t = CellSetGet(s, u shr PageShift)
+  if t != nil:
+    u = (u %% PageSize) /% MemAlign
+    result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0
+    if not result: 
+      t.bits[u shr IntShift] = t.bits[u shr IntShift] or
+          (1 shl (u and IntMask))
+  else: 
+    Incl(s, cell)
+    result = false
+
+iterator elements(t: TCellSet): PCell {.inline.} =
+  # while traversing it is forbidden to add pointers to the tree!
+  var r = t.head
+  while r != nil:
+    var i = 0
+    while i <= high(r.bits):
+      var w = r.bits[i] # taking a copy of r.bits[i] here is correct, because
+      # modifying operations are not allowed during traversation
+      var j = 0
+      while w != 0:         # test all remaining bits for zero
+        if (w and 1) != 0:  # the bit is set!
+          yield cast[PCell]((r.key shl PageShift) or
+                              (i shl IntShift +% j) *% MemAlign)
+        inc(j)
+        w = w shr 1
+      inc(i)
+    r = r.next
+
diff --git a/lib/mm.nim b/lib/mm.nim
index 5f16f7304..3bfb8a689 100644
--- a/lib/mm.nim
+++ b/lib/mm.nim
@@ -23,6 +23,7 @@ const
   reallyOsDealloc = true
   coalescRight = true
   coalescLeft = true
+  overwriteFree = false
 
 type
   PPointer = ptr pointer
diff --git a/nim/highlite.pas b/nim/highlite.pas
index ad7a6f724..1867268d3 100644
--- a/nim/highlite.pas
+++ b/nim/highlite.pas
@@ -358,7 +358,8 @@ begin
     end
   end;
   g.len := pos - g.pos;
-  if (g.kind <> gtEof) and (g.len <= 0) then InternalError('nimNextToken');
+  if (g.kind <> gtEof) and (g.len <= 0) then 
+    InternalError('nimNextToken: ' + toString(g.buf));
   g.pos := pos;
 end;
 
diff --git a/nim/strutils.pas b/nim/strutils.pas
index cd07105be..377d3abc6 100644
--- a/nim/strutils.pas
+++ b/nim/strutils.pas
@@ -1,7 +1,7 @@
 //
 //
 //           The Nimrod Compiler
-//        (c) Copyright 2008 Andreas Rumpf
+//        (c) Copyright 2009 Andreas Rumpf
 //
 //    See the file "copying.txt", included in this
 //    distribution, for details about the copyright.
@@ -45,6 +45,7 @@ function toString(i: BiggestInt): string; overload;
 //function toString(i: int): string; overload;
 function ToStringF(const r: Real): string; overload;
 function ToString(b: Boolean): string; overload;
+function ToString(b: PChar): string; overload;
 
 function IntToStr(i: BiggestInt; minChars: int): string;
 
@@ -415,6 +416,11 @@ begin
   result := sysUtils.intToStr(i);
 end;
 
+function ToString(b: PChar): string; overload;
+begin
+  result := string(b);
+end;
+
 function normalize(const s: string): string;
 var
   i: int;
diff --git a/pycompab.py b/pycompab.py
new file mode 100644
index 000000000..3121856ef
--- /dev/null
+++ b/pycompab.py
@@ -0,0 +1,103 @@
+""" Python compability library

+    

+    With careful and painful coding, compability from Python 1.5.2 up to 3.0

+    is achieved. Don't try this at home.

+

+    Copyright 2009, Andreas Rumpf

+"""

+

+import sys

+

+python3 = sys.version[0] >= "3"

+python26 = sys.version[:3] == "2.6"

+

+true, false = 0==0, 0==1

+

+if python3:

+  sys.exit("This script does not yet work with Python 3.0")

+

+try:

+  from cStringIO import StringIO

+except ImportError:

+  from io import StringIO

+

+if python3:

+  def replace(s, a, b): return s.replace(a, b)

+  def lower(s): return s.lower()

+  def join(a, s=""): return s.join(a)

+  def find(s, a): return s.find(a)

+  def split(s, a=None): return s.split(a)

+  def strip(s): return s.strip()

+

+  def has_key(dic, key): return key in dic

+else:

+  from string import replace, lower, join, find, split, strip

+

+  def has_key(dic, key): return dic.has_key(key)

+

+if not python3 and not python26:

+  import md5

+  def newMD5(): return md5.new()

+  def MD5update(obj, x):

+    return obj.update(x)

+else:

+  import hashlib

+  def newMD5(): return hashlib.md5()

+  def MD5update(obj, x):

+    if python26:

+      return obj.update(x)

+    else:

+      return obj.update(bytes(x, "utf-8"))

+

+def mydigest(hasher):

+  result = ""

+  for c in hasher.digest():

+    if python3:

+      x = hex(c)[2:]

+    else:

+      x = hex(ord(c))[2:]

+    if len(x) == 1: x = "0" + x

+    result = result + x

+  return result

+

+def Subs(frmt, *args, **substitution):

+  DIGITS = "0123456789"

+  LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

+  chars = DIGITS+LETTERS+"_"

+  d = substitution

+  a = args

+  result = []

+  i = 0

+  L = len(frmt)

+  while i < L:

+    if frmt[i] == '$':

+      i = i+1

+      if frmt[i] == '$':

+        result.append('$')

+        i = i+1

+      elif frmt[i] == '{':

+        i = i+1

+        j = i

+        while frmt[i] != '}': i = i+1

+        i = i+1 # skip }

+        x = frmt[j:i-1]

+        if x[0] in DIGITS:

+          result.append(str(a[int(x)-1]))

+        else:

+          result.append(str(d[x]))

+      elif frmt[i] in chars:

+        j = i

+        i = i+1

+        while i < len(frmt) and frmt[i] in chars: i = i + 1

+        x = frmt[j:i]

+        if x[0] in DIGITS:

+          result.append(str(a[int(x)-1]))

+        else:

+          result.append(str(d[x]))

+      else:

+        assert(false)

+    else:

+      result.append(frmt[i])

+      i = i+1

+  return join(result, "")

+

diff --git a/rod/nimrod.cfg b/rod/nimrod.cfg
index 65bb92bc5..d0293a5dd 100644
--- a/rod/nimrod.cfg
+++ b/rod/nimrod.cfg
@@ -5,12 +5,7 @@
 @if llvm_gcc or gcc:
   # GCC, LLVM and Visual C++ have a problem to optimize some modules.
   # This is really strange.
-  @if windows or macosX:
-    cgen.speed = "-O0"
-  @else:
-    cgen.speed = "-O1 -fno-strict-aliasing"
-  @end
+  cgen.speed = "-O0"
 @elif vcc:
   cgen.speed = ""
 @end
-
76a6a144b90b7'>e25474154 ^
a83036799 ^
e25474154 ^





a83036799 ^
e25474154 ^

















6c5693e63 ^



e25474154 ^

6c5693e63 ^
e25474154 ^




6c5693e63 ^



e25474154 ^






6c5693e63 ^
e25474154 ^






e25474154 ^




6c5693e63 ^
e25474154 ^
6c5693e63 ^






e25474154 ^

6c5693e63 ^
e25474154 ^








e25474154 ^
6c5693e63 ^
e25474154 ^



6c5693e63 ^
e25474154 ^




6c5693e63 ^


e25474154 ^
6c5693e63 ^
e25474154 ^









5c33646e8 ^



e25474154 ^

















6c5693e63 ^


e25474154 ^
6c5693e63 ^
e25474154 ^















e25474154 ^
6c5693e63 ^
e25474154 ^















6c5693e63 ^



e25474154 ^
6c5693e63 ^
e25474154 ^





6c5693e63 ^
e25474154 ^












6c5693e63 ^

e25474154 ^









6c5693e63 ^
e25474154 ^










e25474154 ^








6c5693e63 ^

e25474154 ^
6c5693e63 ^
e25474154 ^











































































6bc16904e ^

e25474154 ^












a83036799 ^
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


                               
                                         











































                                                                                

                                              

                                                                                

                                                                    

                                                                              

                                                                             


                                                                                 

                                                


                                                                            

                                                             








                                                                               



                                                                  

                                              

                                                                                

                                                                    

                                                                              

                                                                             



































                                                                                 
                                                             

                                         
 









                                                                          
  
                                                    






                                                               

                                           






                                      

                 
                                           
                                 



                                           
                            

                             
                                 









                                                 


                                                                    


























                                                                            
                        












                                                                           
                                                      

                                          
                                                                       
                                                                     


                                                                             

                                                              






                                


                                           




















                                                                         
                                                                           


                                                                       

                                                                    
























































                                                                           


                                                 












                                                             


                                                 














                                                             


                                                                  












                                                                  



                                                                    
                       



                                                                    











                                                                              


                                                                        





















                                                             





































                                                                         
              





                                          
              

















                                                                



                                                                            

                                                       
                           




                            



                                                        






                                       
                                






                                                                    




                                       
                      
                    






                                             

                                              
                                        








                                                    
                                      
                         



                                                                      
                    




                                                                 


                    
              
                    









                                                         



                                           

















                                                                


                    
              
                    















                                                                             
                     
                             















                                                                  



                                                                         
                         
                                





                                                         
                  












                                              

                    









                                                       
                    










                                                              








                                              

                                                          
                                      
                         











































































                                                                            

                             












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

# This scanner is handwritten for efficiency. I used an elegant buffering
# scheme which I have not seen anywhere else:
# We guarantee that a whole line is in the buffer. Thus only when scanning
# the \n or \r character we have to check wether we need to read in the next 
# chunk. (\n or \r already need special handling for incrementing the line
# counter; choosing both \n and \r allows the scanner to properly read Unix,
# DOS or Macintosh text files, even when it is not the native format.

import 
  nhashes, options, msgs, strutils, platform, idents, lexbase, llstream, 
  wordrecg

const 
  MaxLineLength* = 80         # lines longer than this lead to a warning
  numChars*: TCharSet = {'0'..'9', 'a'..'z', 'A'..'Z'}
  SymChars*: TCharSet = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF'}
  SymStartChars*: TCharSet = {'a'..'z', 'A'..'Z', '\x80'..'\xFF'}
  OpChars*: TCharSet = {'+', '-', '*', '/', '\\', '<', '>', '!', '?', '^', '.', 
    '|', '=', '%', '&', '$', '@', '~', '\x80'..'\xFF'}

type 
  TTokType* = enum 
    tkInvalid, tkEof,         # order is important here!
    tkSymbol, # keywords:
              #[[[cog
              #from string import split, capitalize
              #keywords = split(open("data/keywords.txt").read())
              #idents = ""
              #strings = ""
              #i = 1
              #for k in keywords:
              #  idents = idents + "tk" + capitalize(k) + ", "
              #  strings = strings + "'" + k + "', "
              #  if i % 4 == 0:
              #    idents = idents + "\n"
              #    strings = strings + "\n"
              #  i = i + 1
              #cog.out(idents)
              #]]]
    tkAddr, tkAnd, tkAs, tkAsm, tkAtomic, 
    tkBind, tkBlock, tkBreak, tkCase, tkCast, 
    tkConst, tkContinue, tkConverter, tkDiscard, tkDistinct, tkDiv, tkElif, 
    tkElse, tkEnd, tkEnum, tkExcept, tkFinally, tkFor, tkFrom, tkGeneric, tkIf, 
    tkImplies, tkImport, tkIn, tkInclude, tkIs, tkIsnot, tkIterator,
    tkLambda, tkLet,
    tkMacro, tkMethod, tkMod, tkNil, tkNot, tkNotin, tkObject, tkOf, tkOr, 
    tkOut, tkProc, tkPtr, tkRaise, tkRef, tkReturn, tkShl, tkShr, tkTemplate, 
    tkTry, tkTuple, tkType, tkVar, tkWhen, tkWhile, tkWith, tkWithout, tkXor,
    tkYield, #[[[end]]]
    tkIntLit, tkInt8Lit, tkInt16Lit, tkInt32Lit, tkInt64Lit, tkFloatLit, 
    tkFloat32Lit, tkFloat64Lit, tkStrLit, tkRStrLit, tkTripleStrLit, 
    tkCallRStrLit, tkCallTripleStrLit, tkCharLit, tkParLe, tkParRi, tkBracketLe, 
    tkBracketRi, tkCurlyLe, tkCurlyRi, 
    tkBracketDotLe, tkBracketDotRi, # [. and  .]
    tkCurlyDotLe, tkCurlyDotRi, # {.  and  .}
    tkParDotLe, tkParDotRi,   # (. and .)
    tkComma, tkSemiColon, tkColon, tkEquals, tkDot, tkDotDot, tkHat, tkOpr, 
    tkComment, tkAccent, tkInd, tkSad, 
    tkDed, # pseudo token types used by the source renderers:
    tkSpaces, tkInfixOpr, tkPrefixOpr, tkPostfixOpr
  TTokTypes* = set[TTokType]

const 
  tokKeywordLow* = succ(tkSymbol)
  tokKeywordHigh* = pred(tkIntLit)
  tokOperators*: TTokTypes = {tkOpr, tkSymbol, tkBracketLe, tkBracketRi, tkIn, 
    tkIs, tkIsNot, tkEquals, tkDot, tkHat, tkNot, tkAnd, tkOr, tkXor, tkShl, 
    tkShr, tkDiv, tkMod, tkNotIn}
  TokTypeToStr*: array[TTokType, string] = ["tkInvalid", "[EOF]", 
    "tkSymbol", #[[[cog
                #cog.out(strings)
                #]]]
    "addr", "and", "as", "asm", "atomic", 
    "bind", "block", "break", "case", "cast", 
    "const", "continue", "converter", "discard", "distinct", "div", "elif", 
    "else", "end", "enum", "except", "finally", "for", "from", "generic", "if", 
    "implies", "import", "in", "include", "is", "isnot", "iterator",
    "lambda", "let", 
    "macro", "method", "mod", "nil", "not", "notin", "object", "of", "or", 
    "out", "proc", "ptr", "raise", "ref", "return", "shl", "shr", "template", 
    "try", "tuple", "type", "var", "when", "while", "with", "without", "xor",
    "yield", #[[[end]]]
    "tkIntLit", "tkInt8Lit", "tkInt16Lit", "tkInt32Lit", "tkInt64Lit", 
    "tkFloatLit", "tkFloat32Lit", "tkFloat64Lit", "tkStrLit", "tkRStrLit", 
    "tkTripleStrLit", "tkCallRStrLit", "tkCallTripleStrLit", "tkCharLit", "(", 
    ")", "[", "]", "{", "}", "[.", ".]", "{.", ".}", "(.", ".)", ",", ";", ":", 
    "=", ".", "..", "^", "tkOpr", "tkComment", "`", "[new indentation]", 
    "[same indentation]", "[dedentation]", "tkSpaces", "tkInfixOpr", 
    "tkPrefixOpr", "tkPostfixOpr"]

type 
  TNumericalBase* = enum 
    base10,                   # base10 is listed as the first element,
                              # so that it is the correct default value
    base2, base8, base16
  PToken* = ref TToken
  TToken* = object            # a Nimrod token
    tokType*: TTokType        # the type of the token
    indent*: int              # the indentation; only valid if tokType = tkIndent
    ident*: PIdent            # the parsed identifier
    iNumber*: BiggestInt      # the parsed integer literal
    fNumber*: BiggestFloat    # the parsed floating point literal
    base*: TNumericalBase     # the numerical base; only valid for int
                              # or float literals
    literal*: string          # the parsed (string) literal; and
                              # documentation comments are here too
    next*: PToken             # next token; can be used for arbitrary look-ahead
  
  PLexer* = ref TLexer
  TLexer* = object of TBaseLexer
    filename*: string
    indentStack*: seq[int]    # the indentation stack
    dedent*: int              # counter for DED token generation
    indentAhead*: int         # if > 0 an indendation has already been read
                              # this is needed because scanning comments
                              # needs so much look-ahead
  

var gLinesCompiled*: int  # all lines that have been compiled

proc pushInd*(L: var TLexer, indent: int)

proc popInd*(L: var TLexer)
proc isKeyword*(kind: TTokType): bool
proc openLexer*(lex: var TLexer, filename: string, inputstream: PLLStream)
proc rawGetTok*(L: var TLexer, tok: var TToken)
  # reads in the next token into tok and skips it
proc getColumn*(L: TLexer): int
proc getLineInfo*(L: TLexer): TLineInfo
proc closeLexer*(lex: var TLexer)
proc PrintTok*(tok: PToken)
proc tokToStr*(tok: PToken): string
  
proc lexMessage*(L: TLexer, msg: TMsgKind, arg = "")
  # the Pascal scanner uses this too:
proc fillToken*(L: var TToken)
# implementation

proc isKeyword(kind: TTokType): bool = 
  result = (kind >= tokKeywordLow) and (kind <= tokKeywordHigh)

proc isNimrodIdentifier*(s: string): bool =
  if s[0] in SymStartChars:
    var i = 1
    while i < s.len:
      if s[i] == '_': 
        inc(i)
        if s[i] notin SymChars: return
      if s[i] notin SymChars: return
      inc(i)
    result = true

proc pushInd(L: var TLexer, indent: int) = 
  var length = len(L.indentStack)
  setlen(L.indentStack, length + 1)
  if (indent > L.indentStack[length - 1]): 
    L.indentstack[length] = indent
  else: 
    InternalError("pushInd")
  
proc popInd(L: var TLexer) = 
  var length = len(L.indentStack)
  setlen(L.indentStack, length - 1)

proc findIdent(L: TLexer, indent: int): bool = 
  for i in countdown(len(L.indentStack) - 1, 0): 
    if L.indentStack[i] == indent: 
      return true
  result = false

proc tokToStr(tok: PToken): string = 
  case tok.tokType
  of tkIntLit..tkInt64Lit: result = $tok.iNumber
  of tkFloatLit..tkFloat64Lit: result = $tok.fNumber
  of tkInvalid, tkStrLit..tkCharLit, tkComment: result = tok.literal
  of tkParLe..tkColon, tkEof, tkInd, tkSad, tkDed, tkAccent: 
    result = tokTypeToStr[tok.tokType]
  else: 
    if (tok.ident != nil): 
      result = tok.ident.s
    else: 
      InternalError("tokToStr")
      result = ""
  
proc PrintTok(tok: PToken) = 
  write(stdout, TokTypeToStr[tok.tokType])
  write(stdout, " ")
  writeln(stdout, tokToStr(tok))

var dummyIdent: PIdent

proc fillToken(L: var TToken) = 
  L.TokType = tkInvalid
  L.iNumber = 0
  L.Indent = 0
  L.literal = ""
  L.fNumber = 0.0
  L.base = base10
  L.ident = dummyIdent        # this prevents many bugs!
  
proc openLexer(lex: var TLexer, filename: string, inputstream: PLLStream) = 
  openBaseLexer(lex, inputstream)
  lex.indentStack = @[0]
  lex.filename = filename
  lex.indentAhead = - 1

proc closeLexer(lex: var TLexer) = 
  inc(gLinesCompiled, lex.LineNumber)
  closeBaseLexer(lex)

proc getColumn(L: TLexer): int = 
  result = getColNumber(L, L.bufPos)

proc getLineInfo(L: TLexer): TLineInfo = 
  result = newLineInfo(L.filename, L.linenumber, getColNumber(L, L.bufpos))

proc lexMessage(L: TLexer, msg: TMsgKind, arg = "") = 
  msgs.liMessage(getLineInfo(L), msg, arg)

proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") = 
  var info = newLineInfo(L.filename, L.linenumber, pos - L.lineStart)
  msgs.liMessage(info, msg, arg)

proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: TCharSet) = 
  var pos = L.bufpos              # use registers for pos, buf
  var buf = L.buf
  while true: 
    if buf[pos] in chars: 
      add(tok.literal, buf[pos])
      Inc(pos)
    else: 
      break 
    if buf[pos] == '_': 
      if buf[pos+1] notin chars: 
        lexMessage(L, errInvalidToken, "_")
        break
      add(tok.literal, '_')
      Inc(pos)
  L.bufPos = pos

proc matchTwoChars(L: TLexer, first: Char, second: TCharSet): bool = 
  result = (L.buf[L.bufpos] == first) and (L.buf[L.bufpos + 1] in Second)

proc isFloatLiteral(s: string): bool = 
  for i in countup(0, len(s) + 0 - 1): 
    if s[i] in {'.', 'e', 'E'}: 
      return true
  result = false

proc GetNumber(L: var TLexer): TToken = 
  var 
    pos, endpos: int
    xi: biggestInt
  # get the base:
  result.tokType = tkIntLit   # int literal until we know better
  result.literal = ""
  result.base = base10        # BUGFIX
  pos = L.bufpos     # make sure the literal is correct for error messages:
  matchUnderscoreChars(L, result, {'A'..'Z', 'a'..'z', '0'..'9'})
  if (L.buf[L.bufpos] == '.') and (L.buf[L.bufpos + 1] in {'0'..'9'}): 
    add(result.literal, '.')
    inc(L.bufpos) 
    #matchUnderscoreChars(L, result, ['A'..'Z', 'a'..'z', '0'..'9'])
    matchUnderscoreChars(L, result, {'0'..'9'})
    if L.buf[L.bufpos] in {'e', 'E'}: 
      add(result.literal, 'e')
      inc(L.bufpos)
      if L.buf[L.bufpos] in {'+', '-'}: 
        add(result.literal, L.buf[L.bufpos])
        inc(L.bufpos)
      matchUnderscoreChars(L, result, {'0'..'9'})
  endpos = L.bufpos
  if L.buf[endpos] == '\'': 
    #matchUnderscoreChars(L, result, ['''', 'f', 'F', 'i', 'I', '0'..'9']);
    inc(endpos)
    L.bufpos = pos            # restore position
    case L.buf[endpos]
    of 'f', 'F': 
      inc(endpos)
      if (L.buf[endpos] == '6') and (L.buf[endpos + 1] == '4'): 
        result.tokType = tkFloat64Lit
        inc(endpos, 2)
      elif (L.buf[endpos] == '3') and (L.buf[endpos + 1] == '2'): 
        result.tokType = tkFloat32Lit
        inc(endpos, 2)
      else: 
        lexMessage(L, errInvalidNumber, result.literal)
    of 'i', 'I': 
      inc(endpos)
      if (L.buf[endpos] == '6') and (L.buf[endpos + 1] == '4'): 
        result.tokType = tkInt64Lit
        inc(endpos, 2)
      elif (L.buf[endpos] == '3') and (L.buf[endpos + 1] == '2'): 
        result.tokType = tkInt32Lit
        inc(endpos, 2)
      elif (L.buf[endpos] == '1') and (L.buf[endpos + 1] == '6'): 
        result.tokType = tkInt16Lit
        inc(endpos, 2)
      elif (L.buf[endpos] == '8'): 
        result.tokType = tkInt8Lit
        inc(endpos)
      else: 
        lexMessage(L, errInvalidNumber, result.literal)
    else: lexMessage(L, errInvalidNumber, result.literal)
  else: 
    L.bufpos = pos            # restore position
  try: 
    if (L.buf[pos] == '0') and
        (L.buf[pos + 1] in {'x', 'X', 'b', 'B', 'o', 'O', 'c', 'C'}): 
      inc(pos, 2)
      xi = 0                  # it may be a base prefix
      case L.buf[pos - 1]     # now look at the optional type suffix:
      of 'b', 'B': 
        result.base = base2
        while true: 
          case L.buf[pos]
          of 'A'..'Z', 'a'..'z', '2'..'9', '.': 
            lexMessage(L, errInvalidNumber, result.literal)
            inc(pos)
          of '_': 
            if L.buf[pos+1] notin {'0'..'1'}: 
              lexMessage(L, errInvalidToken, "_")
              break
            inc(pos)
          of '0', '1': 
            xi = `shl`(xi, 1) or (ord(L.buf[pos]) - ord('0'))
            inc(pos)
          else: break 
      of 'o', 'c', 'C': 
        result.base = base8
        while true: 
          case L.buf[pos]
          of 'A'..'Z', 'a'..'z', '8'..'9', '.': 
            lexMessage(L, errInvalidNumber, result.literal)
            inc(pos)
          of '_': 
            if L.buf[pos+1] notin {'0'..'7'}:
              lexMessage(L, errInvalidToken, "_")
              break
            inc(pos)
          of '0'..'7': 
            xi = `shl`(xi, 3) or (ord(L.buf[pos]) - ord('0'))
            inc(pos)
          else: break 
      of 'O': 
        lexMessage(L, errInvalidNumber, result.literal)
      of 'x', 'X': 
        result.base = base16
        while true: 
          case L.buf[pos]
          of 'G'..'Z', 'g'..'z', '.': 
            lexMessage(L, errInvalidNumber, result.literal)
            inc(pos)
          of '_': 
            if L.buf[pos+1] notin {'0'..'9', 'a'..'f', 'A'..'F'}: 
              lexMessage(L, errInvalidToken, "_")
              break
            inc(pos)
          of '0'..'9': 
            xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('0'))
            inc(pos)
          of 'a'..'f': 
            xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('a') + 10)
            inc(pos)
          of 'A'..'F': 
            xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('A') + 10)
            inc(pos)
          else: break 
      else: InternalError(getLineInfo(L), "getNumber")
      case result.tokType
      of tkIntLit, tkInt64Lit: result.iNumber = xi
      of tkInt8Lit: result.iNumber = biggestInt(int8(toU8(int(xi))))
      of tkInt16Lit: result.iNumber = biggestInt(toU16(int(xi)))
      of tkInt32Lit: result.iNumber = biggestInt(toU32(xi))
      of tkFloat32Lit: 
        result.fNumber = (cast[PFloat32](addr(xi)))^ 
        # note: this code is endian neutral!
        # XXX: Test this on big endian machine!
      of tkFloat64Lit: result.fNumber = (cast[PFloat64](addr(xi)))^ 
      else: InternalError(getLineInfo(L), "getNumber")
    elif isFloatLiteral(result.literal) or (result.tokType == tkFloat32Lit) or
        (result.tokType == tkFloat64Lit): 
      result.fnumber = parseFloat(result.literal)
      if result.tokType == tkIntLit: result.tokType = tkFloatLit
    else: 
      result.iNumber = ParseBiggestInt(result.literal)
      if (result.iNumber < low(int32)) or (result.iNumber > high(int32)): 
        if result.tokType == tkIntLit: 
          result.tokType = tkInt64Lit
        elif result.tokType != tkInt64Lit: 
          lexMessage(L, errInvalidNumber, result.literal)
  except EInvalidValue: lexMessage(L, errInvalidNumber, result.literal)
  except EOverflow: lexMessage(L, errNumberOutOfRange, result.literal)
  except EOutOfRange: lexMessage(L, errNumberOutOfRange, result.literal)
  L.bufpos = endpos

proc handleHexChar(L: var TLexer, xi: var int) = 
  case L.buf[L.bufpos]
  of '0'..'9': 
    xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('0'))
    inc(L.bufpos)
  of 'a'..'f': 
    xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('a') + 10)
    inc(L.bufpos)
  of 'A'..'F': 
    xi = (xi shl 4) or (ord(L.buf[L.bufpos]) - ord('A') + 10)
    inc(L.bufpos)
  else: 
    nil

proc handleDecChars(L: var TLexer, xi: var int) = 
  while L.buf[L.bufpos] in {'0'..'9'}: 
    xi = (xi * 10) + (ord(L.buf[L.bufpos]) - ord('0'))
    inc(L.bufpos)

proc getEscapedChar(L: var TLexer, tok: var TToken) = 
  inc(L.bufpos)               # skip '\'
  case L.buf[L.bufpos]
  of 'n', 'N': 
    if tok.toktype == tkCharLit: lexMessage(L, errNnotAllowedInCharacter)
    tok.literal = tok.literal & tnl
    Inc(L.bufpos)
  of 'r', 'R', 'c', 'C': 
    add(tok.literal, CR)
    Inc(L.bufpos)
  of 'l', 'L': 
    add(tok.literal, LF)
    Inc(L.bufpos)
  of 'f', 'F': 
    add(tok.literal, FF)
    inc(L.bufpos)
  of 'e', 'E': 
    add(tok.literal, ESC)
    Inc(L.bufpos)
  of 'a', 'A': 
    add(tok.literal, BEL)
    Inc(L.bufpos)
  of 'b', 'B': 
    add(tok.literal, BACKSPACE)
    Inc(L.bufpos)
  of 'v', 'V': 
    add(tok.literal, VT)
    Inc(L.bufpos)
  of 't', 'T': 
    add(tok.literal, Tabulator)
    Inc(L.bufpos)
  of '\'', '\"': 
    add(tok.literal, L.buf[L.bufpos])
    Inc(L.bufpos)
  of '\\': 
    add(tok.literal, '\\')
    Inc(L.bufpos)
  of 'x', 'X': 
    inc(L.bufpos)
    var xi = 0
    handleHexChar(L, xi)
    handleHexChar(L, xi)
    add(tok.literal, Chr(xi))
  of '0'..'9': 
    if matchTwoChars(L, '0', {'0'..'9'}): 
      lexMessage(L, warnOctalEscape)
    var xi = 0
    handleDecChars(L, xi)
    if (xi <= 255): add(tok.literal, Chr(xi))
    else: lexMessage(L, errInvalidCharacterConstant)
  else: lexMessage(L, errInvalidCharacterConstant)
  
proc HandleCRLF(L: var TLexer, pos: int): int = 
  case L.buf[pos]
  of CR: 
    if getColNumber(L, pos) > MaxLineLength: 
      lexMessagePos(L, hintLineTooLong, pos)
    result = lexbase.HandleCR(L, pos)
  of LF: 
    if getColNumber(L, pos) > MaxLineLength: 
      lexMessagePos(L, hintLineTooLong, pos)
    result = lexbase.HandleLF(L, pos)
  else: result = pos
  
proc getString(L: var TLexer, tok: var TToken, rawMode: bool) = 
  var pos = L.bufPos + 1          # skip "
  var buf = L.buf                 # put `buf` in a register
  var line = L.linenumber         # save linenumber for better error message
  if buf[pos] == '\"' and buf[pos+1] == '\"': 
    tok.tokType = tkTripleStrLit # long string literal:
    inc(pos, 2)               # skip ""
    # skip leading newline:
    pos = HandleCRLF(L, pos)
    buf = L.buf
    while true: 
      case buf[pos]
      of '\"': 
        if buf[pos+1] == '\"' and buf[pos+2] == '\"' and
            buf[pos+3] != '\"': 
          L.bufpos = pos + 3 # skip the three """
          break 
        add(tok.literal, '\"')
        Inc(pos)
      of CR, LF: 
        pos = HandleCRLF(L, pos)
        buf = L.buf
        tok.literal = tok.literal & tnl
      of lexbase.EndOfFile: 
        var line2 = L.linenumber
        L.LineNumber = line
        lexMessagePos(L, errClosingTripleQuoteExpected, L.lineStart)
        L.LineNumber = line2
        break 
      else: 
        add(tok.literal, buf[pos])
        Inc(pos)
  else: 
    # ordinary string literal
    if rawMode: tok.tokType = tkRStrLit
    else: tok.tokType = tkStrLit
    while true: 
      var c = buf[pos]
      if c == '\"': 
        if rawMode and buf[pos+1] == '\"':
          inc(pos, 2)
          add(tok.literal, '"')
        else:
          inc(pos) # skip '"'
          break
      elif c in {CR, LF, lexbase.EndOfFile}: 
        lexMessage(L, errClosingQuoteExpected)
        break 
      elif (c == '\\') and not rawMode: 
        L.bufPos = pos
        getEscapedChar(L, tok)
        pos = L.bufPos
      else: 
        add(tok.literal, c)
        Inc(pos)
    L.bufpos = pos

proc getCharacter(L: var TLexer, tok: var TToken) = 
  Inc(L.bufpos)               # skip '
  var c = L.buf[L.bufpos]
  case c
  of '\0'..Pred(' '), '\'': lexMessage(L, errInvalidCharacterConstant)
  of '\\': getEscapedChar(L, tok)
  else: 
    tok.literal = $c
    Inc(L.bufpos)
  if L.buf[L.bufpos] != '\'': lexMessage(L, errMissingFinalQuote)
  inc(L.bufpos)               # skip '
  
proc getSymbol(L: var TLexer, tok: var TToken) = 
  var h: THash = 0
  var pos = L.bufpos
  var buf = L.buf
  while true: 
    var c = buf[pos]
    case c
    of 'a'..'z', '0'..'9', '\x80'..'\xFF': 
      h = h +% Ord(c)
      h = h +% h shl 10
      h = h xor (h shr 6)
    of 'A'..'Z': 
      c = chr(ord(c) + (ord('a') - ord('A'))) # toLower()
      h = h +% Ord(c)
      h = h +% h shl 10
      h = h xor (h shr 6)
    of '_': 
      if buf[pos+1] notin SymChars: 
        lexMessage(L, errInvalidToken, "_")
        return
    else: break 
    Inc(pos)
  h = h +% h shl 3
  h = h xor (h shr 11)
  h = h +% h shl 15
  tok.ident = getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  L.bufpos = pos
  if (tok.ident.id < ord(tokKeywordLow) - ord(tkSymbol)) or
      (tok.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)): 
    tok.tokType = tkSymbol
  else: 
    tok.tokType = TTokType(tok.ident.id + ord(tkSymbol))
  if buf[pos] == '\"': 
    getString(L, tok, true)
    if tok.tokType == tkRStrLit: tok.tokType = tkCallRStrLit
    else: tok.tokType = tkCallTripleStrLit
  
proc getOperator(L: var TLexer, tok: var TToken) = 
  var pos = L.bufpos
  var buf = L.buf
  var h: THash = 0
  while true: 
    var c = buf[pos]
    if c in OpChars: 
      h = h +% Ord(c)
      h = h +% h shl 10
      h = h xor (h shr 6)
    else: 
      break 
    Inc(pos)
  h = h +% h shl 3
  h = h xor (h shr 11)
  h = h +% h shl 15
  tok.ident = getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
  if (tok.ident.id < oprLow) or (tok.ident.id > oprHigh): tok.tokType = tkOpr
  else: tok.tokType = TTokType(tok.ident.id - oprLow + ord(tkColon))
  L.bufpos = pos

proc handleIndentation(L: var TLexer, tok: var TToken, indent: int) = 
  tok.indent = indent
  var i = high(L.indentStack)
  if indent > L.indentStack[i]: 
    tok.tokType = tkInd
  elif indent == L.indentStack[i]: 
    tok.tokType = tkSad
  else: 
    # check we have the indentation somewhere in the stack:
    while (i >= 0) and (indent != L.indentStack[i]): 
      dec(i)
      inc(L.dedent)
    dec(L.dedent)
    tok.tokType = tkDed
    if i < 0: 
      tok.tokType = tkSad     # for the parser it is better as SAD
      lexMessage(L, errInvalidIndentation)

proc scanComment(L: var TLexer, tok: var TToken) = 
  var pos = L.bufpos
  var buf = L.buf 
  # a comment ends if the next line does not start with the # on the same
  # column after only whitespace
  tok.tokType = tkComment
  var col = getColNumber(L, pos)
  while true: 
    while not (buf[pos] in {CR, LF, lexbase.EndOfFile}): 
      add(tok.literal, buf[pos])
      inc(pos)
    pos = handleCRLF(L, pos)
    buf = L.buf
    var indent = 0
    while buf[pos] == ' ': 
      inc(pos)
      inc(indent)
    if (buf[pos] == '#') and (col == indent): 
      tok.literal = tok.literal & "\n"
    else: 
      if buf[pos] > ' ': 
        L.indentAhead = indent
        inc(L.dedent)
      break 
  L.bufpos = pos

proc skip(L: var TLexer, tok: var TToken) = 
  var pos = L.bufpos
  var buf = L.buf
  while true: 
    case buf[pos]
    of ' ': 
      Inc(pos)
    of Tabulator: 
      lexMessagePos(L, errTabulatorsAreNotAllowed, pos)
      inc(pos)                # BUGFIX
    of CR, LF: 
      pos = HandleCRLF(L, pos)
      buf = L.buf
      var indent = 0
      while buf[pos] == ' ': 
        Inc(pos)
        Inc(indent)
      if (buf[pos] > ' '): 
        handleIndentation(L, tok, indent)
        break 
    else: 
      break                   # EndOfFile also leaves the loop
  L.bufpos = pos

proc rawGetTok(L: var TLexer, tok: var TToken) = 
  fillToken(tok)
  if L.dedent > 0: 
    dec(L.dedent)
    if L.indentAhead >= 0: 
      handleIndentation(L, tok, L.indentAhead)
      L.indentAhead = - 1
    else: 
      tok.tokType = tkDed
    return 
  skip(L, tok)
  # got an documentation comment or tkIndent, return that:
  if tok.toktype != tkInvalid: return 
  var c = L.buf[L.bufpos]
  if c in SymStartChars - {'r', 'R', 'l'}: 
    getSymbol(L, tok)
  elif c in {'0'..'9'}: 
    tok = getNumber(L)
  else: 
    case c
    of '#': 
      scanComment(L, tok)
    of ':': 
      tok.tokType = tkColon
      inc(L.bufpos)
    of ',': 
      tok.toktype = tkComma
      Inc(L.bufpos)
    of 'l': 
      # if we parsed exactly one character and its a small L (l), this
      # is treated as a warning because it may be confused with the number 1
      if not (L.buf[L.bufpos + 1] in (SymChars + {'_'})): 
        lexMessage(L, warnSmallLshouldNotBeUsed)
      getSymbol(L, tok)
    of 'r', 'R': 
      if L.buf[L.bufPos + 1] == '\"': 
        Inc(L.bufPos)
        getString(L, tok, true)
      else: 
        getSymbol(L, tok)
    of '(': 
      Inc(L.bufpos)
      if (L.buf[L.bufPos] == '.') and (L.buf[L.bufPos + 1] != '.'): 
        tok.toktype = tkParDotLe
        Inc(L.bufpos)
      else: 
        tok.toktype = tkParLe
    of ')': 
      tok.toktype = tkParRi
      Inc(L.bufpos)
    of '[': 
      Inc(L.bufpos)
      if (L.buf[L.bufPos] == '.') and (L.buf[L.bufPos + 1] != '.'): 
        tok.toktype = tkBracketDotLe
        Inc(L.bufpos)
      else: 
        tok.toktype = tkBracketLe
    of ']': 
      tok.toktype = tkBracketRi
      Inc(L.bufpos)
    of '.': 
      if L.buf[L.bufPos + 1] == ']': 
        tok.tokType = tkBracketDotRi
        Inc(L.bufpos, 2)
      elif L.buf[L.bufPos + 1] == '}': 
        tok.tokType = tkCurlyDotRi
        Inc(L.bufpos, 2)
      elif L.buf[L.bufPos + 1] == ')': 
        tok.tokType = tkParDotRi
        Inc(L.bufpos, 2)
      else: 
        getOperator(L, tok)
    of '{': 
      Inc(L.bufpos)
      if (L.buf[L.bufPos] == '.') and (L.buf[L.bufPos + 1] != '.'): 
        tok.toktype = tkCurlyDotLe
        Inc(L.bufpos)
      else: 
        tok.toktype = tkCurlyLe
    of '}': 
      tok.toktype = tkCurlyRi
      Inc(L.bufpos)
    of ';': 
      tok.toktype = tkSemiColon
      Inc(L.bufpos)
    of '`': 
      tok.tokType = tkAccent
      Inc(L.bufpos)
    of '\"': 
      getString(L, tok, false)
    of '\'':
      tok.tokType = tkCharLit
      getCharacter(L, tok)
      tok.tokType = tkCharLit
    of lexbase.EndOfFile: 
      tok.toktype = tkEof
    else: 
      if c in OpChars: 
        getOperator(L, tok)
      else: 
        tok.literal = c & ""
        tok.tokType = tkInvalid
        lexMessage(L, errInvalidToken, c & " (\\" & $(ord(c)) & ')')
        Inc(L.bufpos)
  
dummyIdent = getIdent("")