summary refs log tree commit diff stats
path: root/lib/pure/ftpclient.nim
blob: 53f6688b9b5545b21dde535619ee9e779f0f9ef7 (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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
#
#
#            Nimrod's Runtime Library
#        (c) Copyright 2012 Dominik Picheta
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

include "system/inclrtl"

import sockets, strutils, parseutils, times, os, asyncio

## This module **partially** implements an FTP client as specified
## by `RFC 959 <http://tools.ietf.org/html/rfc959>`_. 
## 
## This module provides both a synchronous and asynchronous implementation.
## The asynchronous implementation requires you to use the ``AsyncFTPClient``
## function. You are then required to register the ``PAsyncFTPClient`` with a
## asyncio dispatcher using the ``register`` function. Take a look at the
## asyncio module documentation for more information.
##
## **Note**: The asynchronous implementation is only asynchronous for long
## file transfers, calls to functions which use the command socket will block.
##
## Here is some example usage of this module:
## 
## .. code-block:: Nimrod
##    var ftp = FTPClient("example.org", user = "user", pass = "pass")
##    ftp.connect()
##    ftp.retrFile("file.ext", "file.ext")
##
## **Warning:** The API of this module is unstable, and therefore is subject
## to change.


type
  TFTPClient* = object of TObject
    case isAsync: bool
    of false:
      csock: TSocket # Command connection socket
      dsock: TSocket # Data connection socket
    else:
      dummyA, dummyB: pointer # workaround a Nimrod API issue
      asyncCSock: PAsyncSocket
      asyncDSock: PAsyncSocket
      handleEvent*: proc (ftp: PAsyncFTPClient, ev: TFTPEvent){.closure,gcsafe.}
      disp: PDispatcher
      asyncDSockID: PDelegate
    user, pass: string
    address: string
    port: TPort
    
    jobInProgress: bool
    job: ref TFTPJob

    dsockConnected: bool

  PFTPClient* = ref TFTPClient

  FTPJobType* = enum
    JRetrText, JRetr, JStore

  TFTPJob = object
    prc: proc (ftp: PFTPClient, async: bool): bool {.nimcall, gcsafe.}
    case typ*: FTPJobType
    of JRetrText:
      lines: string
    of JRetr, JStore:
      file: TFile
      filename: string
      total: biggestInt # In bytes.
      progress: biggestInt # In bytes.
      oneSecond: biggestInt # Bytes transferred in one second.
      lastProgressReport: float # Time
      toStore: string # Data left to upload (Only used with async)
    else: nil

  PAsyncFTPClient* = ref TAsyncFTPClient ## Async alternative to TFTPClient.
  TAsyncFTPClient* = object of TFTPClient

  FTPEventType* = enum
    EvTransferProgress, EvLines, EvRetr, EvStore

  TFTPEvent* = object ## Event
    filename*: string
    case typ*: FTPEventType
    of EvLines:
      lines*: string ## Lines that have been transferred.
    of EvRetr, EvStore: ## Retr/Store operation finished.
      nil 
    of EvTransferProgress:
      bytesTotal*: biggestInt     ## Bytes total.
      bytesFinished*: biggestInt  ## Bytes transferred.
      speed*: biggestInt          ## Speed in bytes/s
      currentJob*: FTPJobType     ## The current job being performed.

  EInvalidReply* = object of ESynch
  EFTP* = object of ESynch

proc ftpClient*(address: string, port = TPort(21),
                user, pass = ""): PFTPClient =
  ## Create a ``PFTPClient`` object.
  new(result)
  result.user = user
  result.pass = pass
  result.address = address
  result.port = port

  result.isAsync = false
  result.dsockConnected = false
  result.csock = socket()
  if result.csock == InvalidSocket: osError(osLastError())

proc getDSock(ftp: PFTPClient): TSocket =
  if ftp.isAsync: return ftp.asyncDSock else: return ftp.dsock

proc getCSock(ftp: PFTPClient): TSocket =
  if ftp.isAsync: return ftp.asyncCSock else: return ftp.csock

template blockingOperation(sock: TSocket, body: stmt) {.immediate.} =
  if ftp.isAsync:
    sock.setBlocking(true)
  body
  if ftp.isAsync:
    sock.setBlocking(false)

proc expectReply(ftp: PFTPClient): TaintedString =
  result = TaintedString""
  blockingOperation(ftp.getCSock()):
    ftp.getCSock().readLine(result)

proc send*(ftp: PFTPClient, m: string): TaintedString =
  ## Send a message to the server, and wait for a primary reply.
  ## ``\c\L`` is added for you.
  blockingOperation(ftp.getCSock()):
    ftp.getCSock().send(m & "\c\L")
  return ftp.expectReply()

proc assertReply(received: TaintedString, expected: string) =
  if not received.string.startsWith(expected):
    raise newException(EInvalidReply,
                       "Expected reply '$1' got: $2" % [
                       expected, received.string])

proc assertReply(received: TaintedString, expected: varargs[string]) =
  for i in items(expected):
    if received.string.startsWith(i): return
  raise newException(EInvalidReply,
                     "Expected reply '$1' got: $2" %
                     [expected.join("' or '"), received.string])

proc createJob(ftp: PFTPClient,
               prc: proc (ftp: PFTPClient, async: bool): bool {.
                          nimcall,gcsafe.},
               cmd: FTPJobType) =
  if ftp.jobInProgress:
    raise newException(EFTP, "Unable to do two jobs at once.")
  ftp.jobInProgress = true
  new(ftp.job)
  ftp.job.prc = prc
  ftp.job.typ = cmd
  case cmd
  of JRetrText:
    ftp.job.lines = ""
  of JRetr, JStore:
    ftp.job.toStore = ""

proc deleteJob(ftp: PFTPClient) =
  assert ftp.jobInProgress
  ftp.jobInProgress = false
  case ftp.job.typ
  of JRetrText:
    ftp.job.lines = ""
  of JRetr, JStore:
    ftp.job.file.close()
  if ftp.isAsync:
    ftp.asyncDSock.close()
  else:
    ftp.dsock.close()

proc handleTask(s: PAsyncSocket, ftp: PFTPClient) =
  if ftp.jobInProgress:
    if ftp.job.typ in {JRetr, JStore}:
      if epochTime() - ftp.job.lastProgressReport >= 1.0:
        var r: TFTPEvent
        ftp.job.lastProgressReport = epochTime()
        r.typ = EvTransferProgress
        r.bytesTotal = ftp.job.total
        r.bytesFinished = ftp.job.progress
        r.speed = ftp.job.oneSecond
        r.filename = ftp.job.filename
        r.currentJob = ftp.job.typ
        ftp.job.oneSecond = 0
        ftp.handleEvent(PAsyncFTPClient(ftp), r)

proc handleWrite(s: PAsyncSocket, ftp: PFTPClient) =
  if ftp.jobInProgress:
    if ftp.job.typ == JStore:
      assert (not ftp.job.prc(ftp, true))

proc handleConnect(s: PAsyncSocket, ftp: PFTPClient) =
  ftp.dsockConnected = true
  assert(ftp.jobInProgress)
  if ftp.job.typ == JStore:
    s.setHandleWrite(proc (s: PAsyncSocket) = handleWrite(s, ftp))
  else:
    s.delHandleWrite()

proc handleRead(s: PAsyncSocket, ftp: PFTPClient) =
  assert ftp.jobInProgress
  assert ftp.job.typ != JStore
  # This can never return true, because it shouldn't check for code 
  # 226 from csock.
  assert(not ftp.job.prc(ftp, true))

proc pasv(ftp: PFTPClient) =
  ## Negotiate a data connection.
  if not ftp.isAsync:
    ftp.dsock = socket()
    if ftp.dsock == InvalidSocket: osError(osLastError())
  else:
    ftp.asyncDSock = AsyncSocket()
    ftp.asyncDSock.handleRead =
      proc (s: PAsyncSocket) =
        handleRead(s, ftp)
    ftp.asyncDSock.handleConnect =
      proc (s: PAsyncSocket) =
        handleConnect(s, ftp)
    ftp.asyncDSock.handleTask =
      proc (s: PAsyncSocket) =
        handleTask(s, ftp)
    ftp.disp.register(ftp.asyncDSock)
  
  var pasvMsg = ftp.send("PASV").string.strip.TaintedString
  assertReply(pasvMsg, "227")
  var betweenParens = captureBetween(pasvMsg.string, '(', ')')
  var nums = betweenParens.split(',')
  var ip = nums[0.. -3]
  var port = nums[-2.. -1]
  var properPort = port[0].parseInt()*256+port[1].parseInt()
  if ftp.isAsync:
    ftp.asyncDSock.connect(ip.join("."), TPort(properPort.toU16))
    ftp.dsockConnected = False
  else:
    ftp.dsock.connect(ip.join("."), TPort(properPort.toU16))
    ftp.dsockConnected = True

proc normalizePathSep(path: string): string =
  return replace(path, '\\', '/')

proc connect*(ftp: PFTPClient) =
  ## Connect to the FTP server specified by ``ftp``.
  if ftp.isAsync:
    blockingOperation(ftp.asyncCSock):
      ftp.asyncCSock.connect(ftp.address, ftp.port)
  else:
    ftp.csock.connect(ftp.address, ftp.port)

  # TODO: Handle 120? or let user handle it.
  assertReply ftp.expectReply(), "220"

  if ftp.user != "":
    assertReply(ftp.send("USER " & ftp.user), "230", "331")

  if ftp.pass != "":
    assertReply ftp.send("PASS " & ftp.pass), "230"

proc pwd*(ftp: PFTPClient): string =
  ## Returns the current working directory.
  var wd = ftp.send("PWD")
  assertReply wd, "257"
  return wd.string.captureBetween('"') # "

proc cd*(ftp: PFTPClient, dir: string) =
  ## Changes the current directory on the remote FTP server to ``dir``.
  assertReply ftp.send("CWD " & dir.normalizePathSep), "250"

proc cdup*(ftp: PFTPClient) =
  ## Changes the current directory to the parent of the current directory.
  assertReply ftp.send("CDUP"), "200"

proc getLines(ftp: PFTPClient, async: bool = false): bool =
  ## Downloads text data in ASCII mode
  ## Returns true if the download is complete.
  ## It doesn't if `async` is true, because it doesn't check for 226 then.
  if ftp.dsockConnected:
    var r = TaintedString""
    if ftp.isAsync:
      if ftp.asyncDSock.readLine(r):
        if r.string == "":
          ftp.dsockConnected = false
        else:
          ftp.job.lines.add(r.string & "\n")
    else:
      assert(not async)
      ftp.dsock.readLine(r)
      if r.string == "":
        ftp.dsockConnected = false
      else:
        ftp.job.lines.add(r.string & "\n")
  
  if not async:
    var readSocks: seq[TSocket] = @[ftp.getCSock()]
    # This is only needed here. Asyncio gets this socket...
    blockingOperation(ftp.getCSock()):
      if readSocks.select(1) != 0 and ftp.getCSock() in readSocks:
        assertReply ftp.expectReply(), "226"
        return true

proc listDirs*(ftp: PFTPClient, dir: string = "",
               async = false): seq[string] =
  ## Returns a list of filenames in the given directory. If ``dir`` is "",
  ## the current directory is used. If ``async`` is true, this
  ## function will return immediately and it will be your job to
  ## use asyncio's ``poll`` to progress this operation.

  ftp.createJob(getLines, JRetrText)
  ftp.pasv()

  assertReply ftp.send("NLST " & dir.normalizePathSep), ["125", "150"]

  if not async:
    while not ftp.job.prc(ftp, false): discard
    result = splitLines(ftp.job.lines)
    ftp.deleteJob()
  else: return @[]

proc fileExists*(ftp: PFTPClient, file: string): bool {.deprecated.} =
  ## **Deprecated since version 0.9.0:** Please use ``existsFile``.
  ##
  ## Determines whether ``file`` exists.
  ##
  ## Warning: This function may block. Especially on directories with many
  ## files, because a full list of file names must be retrieved.
  var files = ftp.listDirs()
  for f in items(files):
    if f.normalizePathSep == file.normalizePathSep: return true

proc existsFile*(ftp: PFTPClient, file: string): bool =
  ## Determines whether ``file`` exists.
  ##
  ## Warning: This function may block. Especially on directories with many
  ## files, because a full list of file names must be retrieved.
  var files = ftp.listDirs()
  for f in items(files):
    if f.normalizePathSep == file.normalizePathSep: return true

proc createDir*(ftp: PFTPClient, dir: string, recursive: bool = false) =
  ## Creates a directory ``dir``. If ``recursive`` is true, the topmost
  ## subdirectory of ``dir`` will be created first, following the secondmost...
  ## etc. this allows you to give a full path as the ``dir`` without worrying
  ## about subdirectories not existing.
  if not recursive:
    assertReply ftp.send("MKD " & dir.normalizePathSep), "257"
  else:
    var reply = TaintedString""
    var previousDirs = ""
    for p in split(dir, {os.dirSep, os.altSep}):
      if p != "":
        previousDirs.add(p)
        reply = ftp.send("MKD " & previousDirs)
        previousDirs.add('/')
    assertReply reply, "257"

proc chmod*(ftp: PFTPClient, path: string,
            permissions: set[TFilePermission]) =
  ## Changes permission of ``path`` to ``permissions``.
  var userOctal = 0
  var groupOctal = 0
  var otherOctal = 0
  for i in items(permissions):
    case i
    of fpUserExec: userOctal.inc(1)
    of fpUserWrite: userOctal.inc(2)
    of fpUserRead: userOctal.inc(4)
    of fpGroupExec: groupOctal.inc(1)
    of fpGroupWrite: groupOctal.inc(2)
    of fpGroupRead: groupOctal.inc(4)
    of fpOthersExec: otherOctal.inc(1)
    of fpOthersWrite: otherOctal.inc(2)
    of fpOthersRead: otherOctal.inc(4)

  var perm = $userOctal & $groupOctal & $otherOctal
  assertReply ftp.send("SITE CHMOD " & perm &
                       " " & path.normalizePathSep), "200"

proc list*(ftp: PFTPClient, dir: string = "", async = false): string =
  ## Lists all files in ``dir``. If ``dir`` is ``""``, uses the current
  ## working directory. If ``async`` is true, this function will return
  ## immediately and it will be your job to call asyncio's 
  ## ``poll`` to progress this operation.
  ftp.createJob(getLines, JRetrText)
  ftp.pasv()

  assertReply(ftp.send("LIST" & " " & dir.normalizePathSep), ["125", "150"])

  if not async:
    while not ftp.job.prc(ftp, false): discard
    result = ftp.job.lines
    ftp.deleteJob()
  else:
    return ""

proc retrText*(ftp: PFTPClient, file: string, async = false): string =
  ## Retrieves ``file``. File must be ASCII text.
  ## If ``async`` is true, this function will return immediately and
  ## it will be your job to call asyncio's ``poll`` to progress this operation.
  ftp.createJob(getLines, JRetrText)
  ftp.pasv()
  assertReply ftp.send("RETR " & file.normalizePathSep), ["125", "150"]
  
  if not async:
    while not ftp.job.prc(ftp, false): discard
    result = ftp.job.lines
    ftp.deleteJob()
  else:
    return ""

proc getFile(ftp: PFTPClient, async = false): bool =
  if ftp.dsockConnected:
    var r = "".TaintedString
    var bytesRead = 0
    var returned = false
    if async:
      if not ftp.isAsync: raise newException(EFTP, "FTPClient must be async.")
      bytesRead = ftp.AsyncDSock.recvAsync(r, BufferSize)
      returned = bytesRead != -1
    else: 
      bytesRead = getDSock(ftp).recv(r, BufferSize)
      returned = true
    let r2 = r.string
    if r2 != "":
      ftp.job.progress.inc(r2.len)
      ftp.job.oneSecond.inc(r2.len)
      ftp.job.file.write(r2)
    elif returned and r2 == "":
      ftp.dsockConnected = False
  
  if not async:
    var readSocks: seq[TSocket] = @[ftp.getCSock()]
    blockingOperation(ftp.getCSock()):
      if readSocks.select(1) != 0 and ftp.getCSock() in readSocks:
        assertReply ftp.expectReply(), "226"
        return true

proc retrFile*(ftp: PFTPClient, file, dest: string, async = false) =
  ## Downloads ``file`` and saves it to ``dest``. Usage of this function
  ## asynchronously is recommended to view the progress of the download.
  ## The ``EvRetr`` event is passed to the specified ``handleEvent`` function 
  ## when the download is finished, and the ``filename`` field will be equal
  ## to ``file``.
  ftp.createJob(getFile, JRetr)
  ftp.job.file = open(dest, mode = fmWrite)
  ftp.pasv()
  var reply = ftp.send("RETR " & file.normalizePathSep)
  assertReply reply, ["125", "150"]
  if {'(', ')'} notin reply.string:
    raise newException(EInvalidReply, "Reply has no file size.")
  var fileSize: biggestInt
  if reply.string.captureBetween('(', ')').parseBiggestInt(fileSize) == 0:
    raise newException(EInvalidReply, "Reply has no file size.")
    
  ftp.job.total = fileSize
  ftp.job.lastProgressReport = epochTime()
  ftp.job.filename = file.normalizePathSep

  if not async:
    while not ftp.job.prc(ftp, false): discard
    ftp.deleteJob()

proc doUpload(ftp: PFTPClient, async = false): bool =
  if ftp.dsockConnected:
    if ftp.job.toStore.len() > 0:
      assert(async)
      let bytesSent = ftp.asyncDSock.sendAsync(ftp.job.toStore)
      if bytesSent == ftp.job.toStore.len:
        ftp.job.toStore = ""
      elif bytesSent != ftp.job.toStore.len and bytesSent != 0:
        ftp.job.toStore = ftp.job.toStore[bytesSent .. -1]
      ftp.job.progress.inc(bytesSent)
      ftp.job.oneSecond.inc(bytesSent)
    else:
      var s = newStringOfCap(4000)
      var len = ftp.job.file.readBuffer(addr(s[0]), 4000)
      setLen(s, len)
      if len == 0:
        # File finished uploading.
        if ftp.isAsync: ftp.asyncDSock.close() else: ftp.dsock.close()
        ftp.dsockConnected = false
  
        if not async:
          assertReply ftp.expectReply(), "226"
          return true
        return false
    
      if not async:
        getDSock(ftp).send(s)
      else:
        let bytesSent = ftp.asyncDSock.sendAsync(s)
        if bytesSent == 0:
          ftp.job.toStore.add(s)
        elif bytesSent != s.len:
          ftp.job.toStore.add(s[bytesSent .. -1])
        len = bytesSent
      
      ftp.job.progress.inc(len)
      ftp.job.oneSecond.inc(len)

proc store*(ftp: PFTPClient, file, dest: string, async = false) =
  ## Uploads ``file`` to ``dest`` on the remote FTP server. Usage of this
  ## function asynchronously is recommended to view the progress of
  ## the download.
  ## The ``EvStore`` event is passed to the specified ``handleEvent`` function 
  ## when the upload is finished, and the ``filename`` field will be 
  ## equal to ``file``.
  ftp.createJob(doUpload, JStore)
  ftp.job.file = open(file)
  ftp.job.total = ftp.job.file.getFileSize()
  ftp.job.lastProgressReport = epochTime()
  ftp.job.filename = file
  ftp.pasv()
  
  assertReply ftp.send("STOR " & dest.normalizePathSep), ["125", "150"]

  if not async:
    while not ftp.job.prc(ftp, false): discard
    ftp.deleteJob()

proc close*(ftp: PFTPClient) =
  ## Terminates the connection to the server.
  assertReply ftp.send("QUIT"), "221"
  if ftp.jobInProgress: ftp.deleteJob()
  if ftp.isAsync:
    ftp.asyncCSock.close()
    ftp.asyncDSock.close()
  else:
    ftp.csock.close()
    ftp.dsock.close()

proc csockHandleRead(s: PAsyncSocket, ftp: PAsyncFTPClient) =
  if ftp.jobInProgress:
    assertReply ftp.expectReply(), "226" # Make sure the transfer completed.
    var r: TFTPEvent
    case ftp.job.typ
    of JRetrText:
      r.typ = EvLines
      r.lines = ftp.job.lines
    of JRetr:
      r.typ = EvRetr
      r.filename = ftp.job.filename
      if ftp.job.progress != ftp.job.total:
        raise newException(EFTP, "Didn't download full file.")
    of JStore:
      r.typ = EvStore
      r.filename = ftp.job.filename
      if ftp.job.progress != ftp.job.total:
        raise newException(EFTP, "Didn't upload full file.")
    ftp.deleteJob()
    
    ftp.handleEvent(ftp, r)

proc asyncFTPClient*(address: string, port = TPort(21),
                     user, pass = "",
    handleEvent: proc (ftp: PAsyncFTPClient, ev: TFTPEvent) {.closure,gcsafe.} = 
      (proc (ftp: PAsyncFTPClient, ev: TFTPEvent) = discard)): PAsyncFTPClient =
  ## Create a ``PAsyncFTPClient`` object.
  ##
  ## Use this if you want to use asyncio's dispatcher.
  var dres: PAsyncFTPClient
  new(dres)
  dres.user = user
  dres.pass = pass
  dres.address = address
  dres.port = port
  dres.isAsync = true
  dres.dsockConnected = false
  dres.handleEvent = handleEvent
  dres.asyncCSock = AsyncSocket()
  dres.asyncCSock.handleRead =
    proc (s: PAsyncSocket) =
      csockHandleRead(s, dres)
  result = dres

proc register*(d: PDispatcher, ftp: PAsyncFTPClient): PDelegate {.discardable.} =
  ## Registers ``ftp`` with dispatcher ``d``.
  assert ftp.isAsync
  ftp.disp = d
  return ftp.disp.register(ftp.asyncCSock)

when isMainModule:
  var d = newDispatcher()
  let hev =
    proc (ftp: PAsyncFTPClient, event: TFTPEvent) =
      case event.typ
      of EvStore:
        echo("Upload finished!")
        ftp.retrFile("payload.JPG", "payload2.JPG", async = true)
      of EvTransferProgress:
        var time: int64 = -1
        if event.speed != 0:
          time = (event.bytesTotal - event.bytesFinished) div event.speed
        echo(event.currentJob)
        echo(event.speed div 1000, " kb/s. - ",
             event.bytesFinished, "/", event.bytesTotal,
             " - ", time, " seconds")
        echo(d.len)
      of EvRetr:
        echo("Download finished!")
        ftp.close()
        echo d.len
      else: assert(false)
  var ftp = asyncFTPClient("picheta.me", user = "test", pass = "asf", handleEvent = hev)
  
  d.register(ftp)
  d.len.echo()
  ftp.connect()
  echo "connected"
  ftp.store("payload.JPG", "payload.JPG", async = true)
  d.len.echo()
  echo "uploading..."
  while true:
    if not d.poll(): break


when isMainModule and false:
  var ftp = ftpClient("picheta.me", user = "asdasd", pass = "asfwq")
  ftp.connect()
  echo ftp.pwd()
  echo ftp.list()
  echo("uploading")
  ftp.store("payload.JPG", "payload.JPG", async = false)

  echo("Upload complete")
  ftp.retrFile("payload.JPG", "payload2.JPG", async = false)

  echo("Download complete")
  sleep(5000)
  ftp.close()
  sleep(200)
semiStmtList(p, result) else: a = colonOrEquals(p, a) result.add(a) if p.tok.tokType == tkComma: getTok(p) skipComment(p, a) while p.tok.tokType != tkParRi and p.tok.tokType != tkEof: var a = exprColonEqExpr(p) addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) skipComment(p, a) optPar(p) eat(p, tkParRi) proc identOrLiteral(p: var TParser, mode: TPrimaryMode): PNode = #| literal = | INT_LIT | INT8_LIT | INT16_LIT | INT32_LIT | INT64_LIT #| | UINT_LIT | UINT8_LIT | UINT16_LIT | UINT32_LIT | UINT64_LIT #| | FLOAT_LIT | FLOAT32_LIT | FLOAT64_LIT #| | STR_LIT | RSTR_LIT | TRIPLESTR_LIT #| | CHAR_LIT #| | NIL #| generalizedLit = GENERALIZED_STR_LIT | GENERALIZED_TRIPLESTR_LIT #| identOrLiteral = generalizedLit | symbol | literal #| | par | arrayConstr | setOrTableConstr #| | castExpr #| tupleConstr = '(' optInd (exprColonEqExpr comma?)* optPar ')' #| arrayConstr = '[' optInd (exprColonEqExpr comma?)* optPar ']' case p.tok.tokType of tkSymbol, tkType, tkAddr: result = newIdentNodeP(p.tok.ident, p) getTok(p) result = parseGStrLit(p, result) of tkAccent: result = parseSymbol(p) # literals of tkIntLit: result = newIntNodeP(nkIntLit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkInt8Lit: result = newIntNodeP(nkInt8Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkInt16Lit: result = newIntNodeP(nkInt16Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkInt32Lit: result = newIntNodeP(nkInt32Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkInt64Lit: result = newIntNodeP(nkInt64Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkUIntLit: result = newIntNodeP(nkUIntLit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkUInt8Lit: result = newIntNodeP(nkUInt8Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkUInt16Lit: result = newIntNodeP(nkUInt16Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkUInt32Lit: result = newIntNodeP(nkUInt32Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkUInt64Lit: result = newIntNodeP(nkUInt64Lit, p.tok.iNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkFloatLit: result = newFloatNodeP(nkFloatLit, p.tok.fNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkFloat32Lit: result = newFloatNodeP(nkFloat32Lit, p.tok.fNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkFloat64Lit: result = newFloatNodeP(nkFloat64Lit, p.tok.fNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkFloat128Lit: result = newFloatNodeP(nkFloat128Lit, p.tok.fNumber, p) setBaseFlags(result, p.tok.base) getTok(p) of tkStrLit: result = newStrNodeP(nkStrLit, p.tok.literal, p) getTok(p) of tkRStrLit: result = newStrNodeP(nkRStrLit, p.tok.literal, p) getTok(p) of tkTripleStrLit: result = newStrNodeP(nkTripleStrLit, p.tok.literal, p) getTok(p) of tkCharLit: result = newIntNodeP(nkCharLit, ord(p.tok.literal[0]), p) getTok(p) of tkNil: result = newNodeP(nkNilLit, p) getTok(p) of tkParLe: # () constructor if mode in {pmTypeDesc, pmTypeDef}: result = exprColonEqExprList(p, nkPar, tkParRi) else: result = parsePar(p) of tkBracketDotLe: # {} constructor result = setOrTableConstr(p) of tkBracketLe: # [] constructor result = exprColonEqExprList(p, nkBracket, tkBracketRi) of tkCast: result = parseCast(p) else: parMessage(p, errExprExpected, p.tok) getTok(p) # we must consume a token here to prevend endless loops! result = ast.emptyNode proc namedParams(p: var TParser, callee: PNode, kind: TNodeKind, endTok: TTokType): PNode = let a = callee result = newNodeP(kind, p) addSon(result, a) exprColonEqExprListAux(p, endTok, result) proc parseMacroColon(p: var TParser, x: PNode): PNode proc primarySuffix(p: var TParser, r: PNode): PNode = #| primarySuffix = '(' (exprColonEqExpr comma?)* ')' doBlocks? #| | doBlocks #| | '.' optInd symbol generalizedLit? #| | '[' optInd indexExprList optPar ']' #| | '{' optInd indexExprList optPar '}' #| | &( '`'|IDENT|literal|'cast'|'addr'|'type') expr # command syntax result = r template somePar() = discard while p.tok.indent < 0: case p.tok.tokType of tkParLe: somePar() result = namedParams(p, result, nkCall, tkParRi) if result.len > 1 and result.sons[1].kind == nkExprColonExpr: result.kind = nkObjConstr else: parseDoBlocks(p, result) of tkDo: var a = result result = newNodeP(nkCall, p) addSon(result, a) parseDoBlocks(p, result) of tkDot: result = dotExpr(p, result) result = parseGStrLit(p, result) of tkBracketLe: somePar() result = namedParams(p, result, nkBracketExpr, tkBracketRi) of tkBracketDotLe: somePar() result = namedParams(p, result, nkCurlyExpr, tkBracketDotRi) of tkSymbol, tkAccent, tkIntLit..tkCharLit, tkNil, tkCast, tkAddr, tkType: if p.inPragma == 0: # actually parsing {.push hints:off.} as {.push(hints:off).} is a sweet # solution, but pragmas.nim can't handle that let a = result result = newNodeP(nkCommand, p) addSon(result, a) when true: addSon result, parseExpr(p) else: while p.tok.tokType != tkEof: let x = parseExpr(p) addSon(result, x) if p.tok.tokType != tkComma: break getTok(p) optInd(p, x) if p.tok.tokType == tkDo: parseDoBlocks(p, result) else: result = parseMacroColon(p, result) break else: break proc primary(p: var TParser, mode: TPrimaryMode): PNode proc simpleExprAux(p: var TParser, limit: int, mode: TPrimaryMode): PNode proc parseOperators(p: var TParser, headNode: PNode, limit: int, mode: TPrimaryMode): PNode = result = headNode # expand while operators have priorities higher than 'limit' var opPrec = getPrecedence(p.tok) let modeB = if mode == pmTypeDef: pmTypeDesc else: mode # the operator itself must not start on a new line: while opPrec >= limit and p.tok.indent < 0 and not isAt(p.tok): checkBinary(p) var leftAssoc = 1-ord(isRightAssociative(p.tok)) var a = newNodeP(nkInfix, p) var opNode = newIdentNodeP(p.tok.ident, p) # skip operator: getTok(p) optInd(p, a) # read sub-expression with higher priority: var b = simpleExprAux(p, opPrec + leftAssoc, modeB) addSon(a, opNode) addSon(a, result) addSon(a, b) result = a opPrec = getPrecedence(p.tok) proc simpleExprAux(p: var TParser, limit: int, mode: TPrimaryMode): PNode = result = primary(p, mode) result = parseOperators(p, result, limit, mode) proc simpleExpr(p: var TParser, mode = pmNormal): PNode = result = simpleExprAux(p, -1, mode) proc parseIfExpr(p: var TParser, kind: TNodeKind): PNode = #| condExpr = expr colcom expr optInd #| ('elif' expr colcom expr optInd)* #| 'else' colcom expr #| ifExpr = 'if' condExpr #| whenExpr = 'when' condExpr result = newNodeP(kind, p) while true: getTok(p) # skip `if`, `elif` var branch = newNodeP(nkElifExpr, p) addSon(branch, parseExpr(p)) colcom(p, branch) addSon(branch, parseExpr(p)) optInd(p, branch) addSon(result, branch) if p.tok.tokType != tkElif: break var branch = newNodeP(nkElseExpr, p) eat(p, tkElse) colcom(p, branch) addSon(branch, parseExpr(p)) addSon(result, branch) proc parsePragma(p: var TParser): PNode = result = newNodeP(nkPragma, p) inc p.inPragma if isAt(p.tok): while isAt(p.tok): getTok(p) var a = parseExpr(p) optInd(p, a) if a.kind in nkCallKinds and a.len == 2: let repaired = newNodeI(nkExprColonExpr, a.info) repaired.add a[0] repaired.add a[1] a = repaired addSon(result, a) skipComment(p, a) else: getTok(p) optInd(p, result) while p.tok.tokType notin {tkCurlyDotRi, tkCurlyRi, tkEof}: var a = exprColonEqExpr(p) addSon(result, a) if p.tok.tokType == tkComma: getTok(p) skipComment(p, a) optPar(p) if p.tok.tokType in {tkCurlyDotRi, tkCurlyRi}: getTok(p) else: parMessage(p, errTokenExpected, ".}") dec p.inPragma proc identVis(p: var TParser; allowDot=false): PNode = #| identVis = symbol opr? # postfix position #| identVisDot = symbol '.' optInd symbol opr? var a = parseSymbol(p) if p.tok.tokType == tkOpr: result = newNodeP(nkPostfix, p) addSon(result, newIdentNodeP(p.tok.ident, p)) addSon(result, a) getTok(p) elif p.tok.tokType == tkDot and allowDot: result = dotExpr(p, a) else: result = a proc identWithPragma(p: var TParser; allowDot=false): PNode = #| identWithPragma = identVis pragma? #| identWithPragmaDot = identVisDot pragma? var a = identVis(p, allowDot) if p.tok.tokType == tkCurlyDotLe or isAt(p.tok): result = newNodeP(nkPragmaExpr, p) addSon(result, a) addSon(result, parsePragma(p)) else: result = a type TDeclaredIdentFlag = enum withPragma, # identifier may have pragma withBothOptional # both ':' and '=' parts are optional TDeclaredIdentFlags = set[TDeclaredIdentFlag] proc parseIdentColonEquals(p: var TParser, flags: TDeclaredIdentFlags): PNode = #| declColonEquals = identWithPragma (comma identWithPragma)* comma? #| (':' optInd typeDesc)? ('=' optInd expr)? #| identColonEquals = ident (comma ident)* comma? #| (':' optInd typeDesc)? ('=' optInd expr)?) var a: PNode result = newNodeP(nkIdentDefs, p) while true: case p.tok.tokType of tkSymbol, tkAccent: if withPragma in flags: a = identWithPragma(p) else: a = parseSymbol(p) if a.kind == nkEmpty: return else: break addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) optInd(p, a) if p.tok.tokType == tkColon: getTok(p) optInd(p, result) addSon(result, parseTypeDesc(p)) else: addSon(result, ast.emptyNode) if p.tok.tokType != tkEquals and withBothOptional notin flags: parMessage(p, errColonOrEqualsExpected, p.tok) if p.tok.tokType == tkEquals: getTok(p) optInd(p, result) addSon(result, parseExpr(p)) else: addSon(result, ast.emptyNode) proc parseTuple(p: var TParser): PNode = result = newNodeP(nkTupleTy, p) getTok(p) if p.tok.tokType in {tkBracketLe, tkCurlyLe}: let usedCurly = p.tok.tokType == tkCurlyLe getTok(p) optInd(p, result) while p.tok.tokType in {tkSymbol, tkAccent}: var a = parseIdentColonEquals(p, {}) addSon(result, a) if p.tok.tokType notin {tkComma, tkSemiColon}: break getTok(p) skipComment(p, a) optPar(p) if usedCurly: eat(p, tkCurlyRi) else: eat(p, tkBracketRi) else: result = newNodeP(nkTupleClassTy, p) proc parseParamList(p: var TParser, retColon = true): PNode = #| paramList = '(' declColonEquals ^* (comma/semicolon) ')' #| paramListArrow = paramList? ('->' optInd typeDesc)? #| paramListColon = paramList? (':' optInd typeDesc)? var a: PNode result = newNodeP(nkFormalParams, p) addSon(result, ast.emptyNode) # return type let hasParLe = p.tok.tokType == tkParLe and p.tok.indent < 0 if hasParLe: getTok(p) optInd(p, result) while true: case p.tok.tokType of tkSymbol, tkAccent: a = parseIdentColonEquals(p, {withBothOptional, withPragma}) of tkParRi: break else: parMessage(p, errTokenExpected, ")") break addSon(result, a) if p.tok.tokType notin {tkComma, tkSemiColon}: break getTok(p) skipComment(p, a) optPar(p) eat(p, tkParRi) let hasRet = if retColon: p.tok.tokType == tkColon else: p.tok.tokType == tkOpr and p.tok.ident.s == "->" if hasRet and p.tok.indent < 0: getTok(p) optInd(p, result) result.sons[0] = parseTypeDesc(p) elif not retColon and not hasParle: # Mark as "not there" in order to mark for deprecation in the semantic pass: result = ast.emptyNode proc optPragmas(p: var TParser): PNode = if p.tok.tokType == tkCurlyDotLe or isAt(p.tok): result = parsePragma(p) else: result = ast.emptyNode proc parseDoBlock(p: var TParser): PNode = #| doBlock = 'do' paramListArrow pragmas? colcom stmt let info = parLineInfo(p) getTok(p) let params = parseParamList(p, retColon=false) let pragmas = optPragmas(p) colcom(p, result) result = newProcNode(nkDo, info, parseStmt(p), params = params, pragmas = pragmas) proc parseDoBlocks(p: var TParser, call: PNode) = #| doBlocks = doBlock ^* IND{=} while p.tok.tokType == tkDo: addSon(call, parseDoBlock(p)) proc parseCurlyStmt(p: var TParser): PNode = result = newNodeP(nkStmtList, p) eat(p, tkCurlyLe) result.add parseStmt(p) while p.tok.tokType notin {tkEof, tkCurlyRi}: if p.tok.tokType == tkSemicolon: getTok(p) elif p.tok.indent < 0: break result.add parseStmt(p) eat(p, tkCurlyRi) proc parseProcExpr(p: var TParser, isExpr: bool): PNode = #| procExpr = 'proc' paramListColon pragmas? ('=' COMMENT? stmt)? # either a proc type or a anonymous proc let info = parLineInfo(p) getTok(p) let hasSignature = p.tok.tokType in {tkParLe, tkColon} and p.tok.indent < 0 let params = parseParamList(p) let pragmas = optPragmas(p) if p.tok.tokType == tkCurlyLe and isExpr: result = newProcNode(nkLambda, info, parseCurlyStmt(p), params = params, pragmas = pragmas) else: result = newNodeI(nkProcTy, info) if hasSignature: addSon(result, params) addSon(result, pragmas) proc isExprStart(p: TParser): bool = case p.tok.tokType of tkSymbol, tkAccent, tkOpr, tkNot, tkNil, tkCast, tkIf, tkProc, tkIterator, tkBind, tkAddr, tkParLe, tkBracketLe, tkCurlyLe, tkIntLit..tkCharLit, tkVar, tkRef, tkPtr, tkTuple, tkObject, tkType, tkWhen, tkCase, tkOut: result = true else: result = false proc parseSymbolList(p: var TParser, result: PNode, allowNil = false) = while true: var s = parseSymbol(p, allowNil) if s.kind == nkEmpty: break addSon(result, s) if p.tok.tokType != tkComma: break getTok(p) optInd(p, s) proc parseTypeDescKAux(p: var TParser, kind: TNodeKind, mode: TPrimaryMode): PNode = #| distinct = 'distinct' optInd typeDesc result = newNodeP(kind, p) getTok(p) optInd(p, result) if not isOperator(p.tok) and isExprStart(p): addSon(result, primary(p, mode)) if kind == nkDistinctTy and p.tok.tokType == tkSymbol: var nodeKind: TNodeKind if p.tok.ident.s == "with": nodeKind = nkWith elif p.tok.ident.s == "without": nodeKind = nkWithout else: return result getTok(p) let list = newNodeP(nodeKind, p) result.addSon list parseSymbolList(p, list, allowNil = true) proc parseExpr(p: var TParser): PNode = #| expr = (ifExpr #| | whenExpr #| | caseExpr #| | tryExpr) #| / simpleExpr case p.tok.tokType: of tkIf: result = parseIfExpr(p, nkIfExpr) of tkWhen: result = parseIfExpr(p, nkWhenExpr) of tkCase: result = parseCase(p) of tkTry: result = parseTry(p) else: result = simpleExpr(p) proc parseEnum(p: var TParser): PNode proc parseObject(p: var TParser): PNode proc parseTypeClass(p: var TParser): PNode proc primary(p: var TParser, mode: TPrimaryMode): PNode = #| typeKeyw = 'var' | 'out' | 'ref' | 'ptr' | 'shared' | 'tuple' #| | 'proc' | 'iterator' | 'distinct' | 'object' | 'enum' #| primary = typeKeyw typeDescK #| / prefixOperator* identOrLiteral primarySuffix* #| / 'static' primary #| / 'bind' primary if isOperator(p.tok): let isSigil = isSigilLike(p.tok) result = newNodeP(nkPrefix, p) var a = newIdentNodeP(p.tok.ident, p) addSon(result, a) getTok(p) optInd(p, a) if isSigil: #XXX prefix operators addSon(result, primary(p, pmSkipSuffix)) result = primarySuffix(p, result) else: addSon(result, primary(p, pmNormal)) return case p.tok.tokType: of tkTuple: result = parseTuple(p) of tkProc: result = parseProcExpr(p, mode notin {pmTypeDesc, pmTypeDef}) of tkIterator: result = parseProcExpr(p, mode notin {pmTypeDesc, pmTypeDef}) if result.kind == nkLambda: result.kind = nkIteratorDef else: result.kind = nkIteratorTy of tkEnum: if mode == pmTypeDef: result = parseEnum(p) else: result = newNodeP(nkEnumTy, p) getTok(p) of tkObject: if mode == pmTypeDef: result = parseObject(p) else: result = newNodeP(nkObjectTy, p) getTok(p) of tkConcept: if mode == pmTypeDef: result = parseTypeClass(p) else: parMessage(p, errInvalidToken, p.tok) of tkStatic: let info = parLineInfo(p) getTokNoInd(p) let next = primary(p, pmNormal) if next.kind == nkBracket and next.sonsLen == 1: result = newNode(nkStaticTy, info, @[next.sons[0]]) else: result = newNode(nkStaticExpr, info, @[next]) of tkBind: result = newNodeP(nkBind, p) getTok(p) optInd(p, result) addSon(result, primary(p, pmNormal)) of tkVar: result = parseTypeDescKAux(p, nkVarTy, mode) of tkOut: result = parseTypeDescKAux(p, nkVarTy, mode) of tkRef: result = parseTypeDescKAux(p, nkRefTy, mode) of tkPtr: result = parseTypeDescKAux(p, nkPtrTy, mode) of tkDistinct: result = parseTypeDescKAux(p, nkDistinctTy, mode) else: result = identOrLiteral(p, mode) if mode != pmSkipSuffix: result = primarySuffix(p, result) proc parseTypeDesc(p: var TParser): PNode = #| typeDesc = simpleExpr result = simpleExpr(p, pmTypeDesc) proc parseTypeDefAux(p: var TParser): PNode = #| typeDefAux = simpleExpr #| | 'concept' typeClass result = simpleExpr(p, pmTypeDef) proc makeCall(n: PNode): PNode = ## Creates a call if the given node isn't already a call. if n.kind in nkCallKinds: result = n else: result = newNodeI(nkCall, n.info) result.add n proc parseMacroColon(p: var TParser, x: PNode): PNode = #| macroColon = ':' stmt? ( IND{=} 'of' exprList ':' stmt #| | IND{=} 'elif' expr ':' stmt #| | IND{=} 'except' exprList ':' stmt #| | IND{=} 'else' ':' stmt )* result = x if p.tok.tokType == tkColon and p.tok.indent < 0: result = makeCall(result) getTok(p) skipComment(p, result) let stmtList = newNodeP(nkStmtList, p) if p.tok.tokType notin {tkOf, tkElif, tkElse, tkExcept}: let body = parseStmt(p) stmtList.add body #addSon(result, makeStmtList(body)) while true: var b: PNode case p.tok.tokType of tkOf: b = newNodeP(nkOfBranch, p) exprList(p, tkCurlyLe, b) of tkElif: b = newNodeP(nkElifBranch, p) getTok(p) optInd(p, b) addSon(b, parseExpr(p)) of tkExcept: b = newNodeP(nkExceptBranch, p) exprList(p, tkCurlyLe, b) of tkElse: b = newNodeP(nkElse, p) getTok(p) else: break addSon(b, parseCurlyStmt(p)) addSon(stmtList, b) if b.kind == nkElse: break if stmtList.len == 1 and stmtList[0].kind == nkStmtList: # to keep backwards compatibility (see tests/vm/tstringnil) result.add stmtList[0] else: result.add stmtList proc parseExprStmt(p: var TParser): PNode = #| exprStmt = simpleExpr #| (( '=' optInd expr ) #| / ( expr ^+ comma #| doBlocks #| / macroColon #| ))? var a = simpleExpr(p) if p.tok.tokType == tkEquals: getTok(p) optInd(p, result) var b = parseExpr(p) result = newNodeI(nkAsgn, a.info) addSon(result, a) addSon(result, b) else: # simpleExpr parsed 'p a' from 'p a, b'? if p.tok.indent < 0 and p.tok.tokType == tkComma and a.kind == nkCommand: result = a while true: getTok(p) optInd(p, result) var e = parseExpr(p) addSon(result, e) if p.tok.tokType != tkComma: break elif p.tok.indent < 0 and isExprStart(p): if a.kind == nkCommand: result = a else: result = newNode(nkCommand, a.info, @[a]) while true: var e = parseExpr(p) addSon(result, e) if p.tok.tokType != tkComma: break getTok(p) optInd(p, result) else: result = a if p.tok.tokType == tkDo and p.tok.indent < 0: result = makeCall(result) parseDoBlocks(p, result) return result result = parseMacroColon(p, result) proc parseModuleName(p: var TParser, kind: TNodeKind): PNode = result = parseExpr(p) proc parseImport(p: var TParser, kind: TNodeKind): PNode = #| importStmt = 'import' optInd expr #| ((comma expr)* #| / 'except' optInd (expr ^+ comma)) result = newNodeP(kind, p) getTok(p) # skip `import` or `export` optInd(p, result) var a = parseModuleName(p, kind) addSon(result, a) if p.tok.tokType in {tkComma, tkExcept}: if p.tok.tokType == tkExcept: result.kind = succ(kind) getTok(p) optInd(p, result) while true: # was: while p.tok.tokType notin {tkEof, tkSad, tkDed}: a = parseModuleName(p, kind) if a.kind == nkEmpty: break addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) optInd(p, a) #expectNl(p) proc parseIncludeStmt(p: var TParser): PNode = #| includeStmt = 'include' optInd expr ^+ comma result = newNodeP(nkIncludeStmt, p) getTok(p) # skip `import` or `include` optInd(p, result) while true: # was: while p.tok.tokType notin {tkEof, tkSad, tkDed}: var a = parseExpr(p) if a.kind == nkEmpty: break addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) optInd(p, a) #expectNl(p) proc parseFromStmt(p: var TParser): PNode = #| fromStmt = 'from' moduleName 'import' optInd expr (comma expr)* result = newNodeP(nkFromStmt, p) getTok(p) # skip `from` optInd(p, result) var a = parseModuleName(p, nkImportStmt) addSon(result, a) #optInd(p, a); eat(p, tkImport) optInd(p, result) while true: # p.tok.tokType notin {tkEof, tkSad, tkDed}: a = parseExpr(p) if a.kind == nkEmpty: break addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) optInd(p, a) #expectNl(p) proc parseReturnOrRaise(p: var TParser, kind: TNodeKind): PNode = #| returnStmt = 'return' optInd expr? #| raiseStmt = 'raise' optInd expr? #| yieldStmt = 'yield' optInd expr? #| discardStmt = 'discard' optInd expr? #| breakStmt = 'break' optInd expr? #| continueStmt = 'break' optInd expr? result = newNodeP(kind, p) getTok(p) if p.tok.tokType == tkComment: skipComment(p, result) addSon(result, ast.emptyNode) elif p.tok.indent >= 0 or not isExprStart(p): # NL terminates: addSon(result, ast.emptyNode) else: addSon(result, parseExpr(p)) proc parseIfOrWhen(p: var TParser, kind: TNodeKind): PNode = #| condStmt = expr colcom stmt COMMENT? #| (IND{=} 'elif' expr colcom stmt)* #| (IND{=} 'else' colcom stmt)? #| ifStmt = 'if' condStmt #| whenStmt = 'when' condStmt result = newNodeP(kind, p) while true: getTok(p) # skip `if`, `when`, `elif` var branch = newNodeP(nkElifBranch, p) optInd(p, branch) addSon(branch, parseExpr(p)) colcom(p, branch) addSon(branch, parseCurlyStmt(p)) skipComment(p, branch) addSon(result, branch) if p.tok.tokType != tkElif: break if p.tok.tokType == tkElse: var branch = newNodeP(nkElse, p) eat(p, tkElse) addSon(branch, parseCurlyStmt(p)) addSon(result, branch) proc parseWhile(p: var TParser): PNode = #| whileStmt = 'while' expr colcom stmt result = newNodeP(nkWhileStmt, p) getTok(p) optInd(p, result) addSon(result, parseExpr(p)) colcom(p, result) addSon(result, parseCurlyStmt(p)) proc parseCase(p: var TParser): PNode = #| ofBranch = 'of' exprList colcom stmt #| ofBranches = ofBranch (IND{=} ofBranch)* #| (IND{=} 'elif' expr colcom stmt)* #| (IND{=} 'else' colcom stmt)? #| caseStmt = 'case' expr ':'? COMMENT? #| (IND{>} ofBranches DED #| | IND{=} ofBranches) var b: PNode inElif= false result = newNodeP(nkCaseStmt, p) getTok(p) addSon(result, parseExpr(p)) eat(p, tkCurlyLe) skipComment(p, result) while true: case p.tok.tokType of tkOf: if inElif: break b = newNodeP(nkOfBranch, p) exprList(p, tkCurlyLe, b) of tkElif: inElif = true b = newNodeP(nkElifBranch, p) getTok(p) optInd(p, b) addSon(b, parseExpr(p)) of tkElse: b = newNodeP(nkElse, p) getTok(p) else: break skipComment(p, b) addSon(b, parseCurlyStmt(p)) addSon(result, b) if b.kind == nkElse: break eat(p, tkCurlyRi) proc parseTry(p: var TParser): PNode = #| tryStmt = 'try' colcom stmt &(IND{=}? 'except'|'finally') #| (IND{=}? 'except' exprList colcom stmt)* #| (IND{=}? 'finally' colcom stmt)? #| tryExpr = 'try' colcom stmt &(optInd 'except'|'finally') #| (optInd 'except' exprList colcom stmt)* #| (optInd 'finally' colcom stmt)? result = newNodeP(nkTryStmt, p) getTok(p) colcom(p, result) addSon(result, parseCurlyStmt(p)) var b: PNode = nil while true: case p.tok.tokType of tkExcept: b = newNodeP(nkExceptBranch, p) exprList(p, tkCurlyLe, b) of tkFinally: b = newNodeP(nkFinally, p) getTok(p) else: break skipComment(p, b) addSon(b, parseCurlyStmt(p)) addSon(result, b) if b.kind == nkFinally: break if b == nil: parMessage(p, errTokenExpected, "except") proc parseFor(p: var TParser): PNode = #| forStmt = 'for' (identWithPragma ^+ comma) 'in' expr colcom stmt result = newNodeP(nkForStmt, p) getTokNoInd(p) var a = identWithPragma(p) addSon(result, a) while p.tok.tokType == tkComma: getTok(p) optInd(p, a) a = identWithPragma(p) addSon(result, a) eat(p, tkIn) addSon(result, parseExpr(p)) colcom(p, result) addSon(result, parseCurlyStmt(p)) proc parseBlock(p: var TParser): PNode = #| blockStmt = 'block' symbol? colcom stmt result = newNodeP(nkBlockStmt, p) getTokNoInd(p) if p.tok.tokType == tkCurlyLe: addSon(result, ast.emptyNode) else: addSon(result, parseSymbol(p)) colcom(p, result) addSon(result, parseCurlyStmt(p)) proc parseStaticOrDefer(p: var TParser; k: TNodeKind): PNode = #| staticStmt = 'static' colcom stmt #| deferStmt = 'defer' colcom stmt result = newNodeP(k, p) getTok(p) colcom(p, result) addSon(result, parseCurlyStmt(p)) proc parseAsm(p: var TParser): PNode = #| asmStmt = 'asm' pragma? (STR_LIT | RSTR_LIT | TRIPLE_STR_LIT) result = newNodeP(nkAsmStmt, p) getTokNoInd(p) if p.tok.tokType == tkCurlyDotLe or isAt(p.tok): addSon(result, parsePragma(p)) else: addSon(result, ast.emptyNode) case p.tok.tokType of tkStrLit: addSon(result, newStrNodeP(nkStrLit, p.tok.literal, p)) of tkRStrLit: addSon(result, newStrNodeP(nkRStrLit, p.tok.literal, p)) of tkTripleStrLit: addSon(result, newStrNodeP(nkTripleStrLit, p.tok.literal, p)) else: parMessage(p, errStringLiteralExpected) addSon(result, ast.emptyNode) return getTok(p) proc parseGenericParam(p: var TParser): PNode = #| genericParam = symbol (comma symbol)* (colon expr)? ('=' optInd expr)? var a: PNode result = newNodeP(nkIdentDefs, p) while true: case p.tok.tokType of tkIn, tkOut: let t = p.tok.tokType getTok(p) expectIdent(p) a = parseSymbol(p) of tkSymbol, tkAccent: a = parseSymbol(p) if a.kind == nkEmpty: return else: break addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) optInd(p, a) if p.tok.tokType == tkColon: getTok(p) optInd(p, result) addSon(result, parseExpr(p)) else: addSon(result, ast.emptyNode) if p.tok.tokType == tkEquals: getTok(p) optInd(p, result) addSon(result, parseExpr(p)) else: addSon(result, ast.emptyNode) proc parseGenericParamList(p: var TParser): PNode = #| genericParamList = '[' optInd #| genericParam ^* (comma/semicolon) optPar ']' result = newNodeP(nkGenericParams, p) getTok(p) optInd(p, result) while p.tok.tokType in {tkSymbol, tkAccent}: var a = parseGenericParam(p) addSon(result, a) if p.tok.tokType notin {tkComma, tkSemiColon}: break getTok(p) skipComment(p, a) optPar(p) eat(p, tkBracketRi) proc parsePattern(p: var TParser): PNode = eat(p, tkBracketDotLe) result = parseStmt(p) eat(p, tkBracketDotRi) proc validInd(p: TParser): bool = p.tok.indent < 0 proc parseRoutine(p: var TParser, kind: TNodeKind): PNode = #| indAndComment = (IND{>} COMMENT)? | COMMENT? #| routine = optInd identVis pattern? genericParamList? #| paramListColon pragma? ('=' COMMENT? stmt)? indAndComment result = newNodeP(kind, p) getTok(p) optInd(p, result) addSon(result, identVis(p)) if p.tok.tokType == tkBracketDotLe and p.validInd: addSon(result, p.parsePattern) else: addSon(result, ast.emptyNode) if p.tok.tokType == tkBracketLe and p.validInd: result.add(p.parseGenericParamList) else: addSon(result, ast.emptyNode) addSon(result, p.parseParamList) if (p.tok.tokType == tkCurlyDotLe or isAt(p.tok)) and p.validInd: addSon(result, p.parsePragma) else: addSon(result, ast.emptyNode) # empty exception tracking: addSon(result, ast.emptyNode) if p.tok.tokType == tkCurlyLe: addSon(result, parseCurlyStmt(p)) else: addSon(result, ast.emptyNode) indAndComment(p, result) proc newCommentStmt(p: var TParser): PNode = #| commentStmt = COMMENT result = newNodeP(nkCommentStmt, p) result.comment = p.tok.literal getTok(p) type TDefParser = proc (p: var TParser): PNode {.nimcall.} proc parseSection(p: var TParser, kind: TNodeKind, defparser: TDefParser): PNode = #| section(p) = COMMENT? p / (IND{>} (p / COMMENT)^+IND{=} DED) result = newNodeP(kind, p) if kind != nkTypeSection: getTok(p) skipComment(p, result) if p.tok.tokType == tkParLe: getTok(p) skipComment(p, result) while true: case p.tok.tokType of tkSymbol, tkAccent, tkParLe: var a = defparser(p) skipComment(p, a) addSon(result, a) of tkComment: var a = newCommentStmt(p) addSon(result, a) of tkParRi: break else: parMessage(p, errIdentifierExpected, p.tok) break eat(p, tkParRi) if result.len == 0: parMessage(p, errIdentifierExpected, p.tok) elif p.tok.tokType in {tkSymbol, tkAccent, tkBracketLe}: # tkBracketLe is allowed for ``var [x, y] = ...`` tuple parsing addSon(result, defparser(p)) else: parMessage(p, errIdentifierExpected, p.tok) proc parseConstant(p: var TParser): PNode = #| constant = identWithPragma (colon typedesc)? '=' optInd expr indAndComment result = newNodeP(nkConstDef, p) addSon(result, identWithPragma(p)) if p.tok.tokType == tkColon: getTok(p) optInd(p, result) addSon(result, parseTypeDesc(p)) else: addSon(result, ast.emptyNode) eat(p, tkEquals) optInd(p, result) addSon(result, parseExpr(p)) indAndComment(p, result) proc parseEnum(p: var TParser): PNode = #| enum = 'enum' optInd (symbol optInd ('=' optInd expr COMMENT?)? comma?)+ result = newNodeP(nkEnumTy, p) getTok(p) addSon(result, ast.emptyNode) optInd(p, result) flexComment(p, result) eat(p, tkCurlyLe) optInd(p, result) while p.tok.tokType notin {tkEof, tkCurlyRi}: var a = parseSymbol(p) if a.kind == nkEmpty: return if p.tok.tokType == tkEquals: getTok(p) optInd(p, a) var b = a a = newNodeP(nkEnumFieldDef, p) addSon(a, b) addSon(a, parseExpr(p)) if p.tok.indent < 0: rawSkipComment(p, a) if p.tok.tokType == tkComma: getTok(p) rawSkipComment(p, a) addSon(result, a) eat(p, tkCurlyRi) if result.len <= 1: lexMessageTok(p.lex, errIdentifierExpected, p.tok, prettyTok(p.tok)) proc parseObjectPart(p: var TParser; needsCurly: bool): PNode proc parseObjectWhen(p: var TParser): PNode = result = newNodeP(nkRecWhen, p) while true: getTok(p) # skip `when`, `elif` var branch = newNodeP(nkElifBranch, p) optInd(p, branch) addSon(branch, parseExpr(p)) colcom(p, branch) addSon(branch, parseObjectPart(p, true)) flexComment(p, branch) addSon(result, branch) if p.tok.tokType != tkElif: break if p.tok.tokType == tkElse: var branch = newNodeP(nkElse, p) eat(p, tkElse) colcom(p, branch) addSon(branch, parseObjectPart(p, true)) flexComment(p, branch) addSon(result, branch) proc parseObjectCase(p: var TParser): PNode = result = newNodeP(nkRecCase, p) getTokNoInd(p) var a = newNodeP(nkIdentDefs, p) addSon(a, identWithPragma(p)) eat(p, tkColon) addSon(a, parseTypeDesc(p)) addSon(a, ast.emptyNode) addSon(result, a) eat(p, tkCurlyLe) flexComment(p, result) while true: var b: PNode case p.tok.tokType of tkOf: b = newNodeP(nkOfBranch, p) exprList(p, tkColon, b) of tkElse: b = newNodeP(nkElse, p) getTok(p) else: break colcom(p, b) var fields = parseObjectPart(p, true) if fields.kind == nkEmpty: parMessage(p, errIdentifierExpected, p.tok) fields = newNodeP(nkNilLit, p) # don't break further semantic checking addSon(b, fields) addSon(result, b) if b.kind == nkElse: break eat(p, tkCurlyRi) proc parseObjectPart(p: var TParser; needsCurly: bool): PNode = if p.tok.tokType == tkCurlyLe: result = newNodeP(nkRecList, p) getTok(p) rawSkipComment(p, result) while true: case p.tok.tokType of tkCase, tkWhen, tkSymbol, tkAccent, tkNil, tkDiscard: addSon(result, parseObjectPart(p, false)) of tkCurlyRi: break else: parMessage(p, errIdentifierExpected, p.tok) break eat(p, tkCurlyRi) else: if needsCurly: parMessage(p, errTokenExpected, "{") case p.tok.tokType of tkWhen: result = parseObjectWhen(p) of tkCase: result = parseObjectCase(p) of tkSymbol, tkAccent: result = parseIdentColonEquals(p, {withPragma}) if p.tok.indent < 0: rawSkipComment(p, result) of tkNil, tkDiscard: result = newNodeP(nkNilLit, p) getTok(p) else: result = ast.emptyNode proc parseObject(p: var TParser): PNode = result = newNodeP(nkObjectTy, p) getTok(p) if (p.tok.tokType == tkCurlyDotLe or isAt(p.tok)) and p.validInd: addSon(result, parsePragma(p)) else: addSon(result, ast.emptyNode) if p.tok.tokType == tkOf and p.tok.indent < 0: var a = newNodeP(nkOfInherit, p) getTok(p) addSon(a, parseTypeDesc(p)) addSon(result, a) else: addSon(result, ast.emptyNode) skipComment(p, result) # an initial IND{>} HAS to follow: addSon(result, parseObjectPart(p, true)) proc parseTypeClassParam(p: var TParser): PNode = if p.tok.tokType in {tkOut, tkVar}: result = newNodeP(nkVarTy, p) getTok(p) result.addSon(p.parseSymbol) else: result = p.parseSymbol proc parseTypeClass(p: var TParser): PNode = #| typeClassParam = ('var' | 'out')? symbol #| typeClass = typeClassParam ^* ',' (pragma)? ('of' typeDesc ^* ',')? #| &IND{>} stmt result = newNodeP(nkTypeClassTy, p) getTok(p) var args = newNodeP(nkArgList, p) addSon(result, args) addSon(args, p.parseTypeClassParam) while p.tok.tokType == tkComma: getTok(p) addSon(args, p.parseTypeClassParam) if (p.tok.tokType == tkCurlyDotLe or isAt(p.tok)) and p.validInd: addSon(result, parsePragma(p)) else: addSon(result, ast.emptyNode) if p.tok.tokType == tkOf and p.tok.indent < 0: var a = newNodeP(nkOfInherit, p) getTok(p) while true: addSon(a, parseTypeDesc(p)) if p.tok.tokType != tkComma: break getTok(p) addSon(result, a) else: addSon(result, ast.emptyNode) if p.tok.tokType == tkComment: skipComment(p, result) addSon(result, parseCurlyStmt(p)) proc parseTypeDef(p: var TParser): PNode = #| #| typeDef = identWithPragmaDot genericParamList? '=' optInd typeDefAux #| indAndComment? result = newNodeP(nkTypeDef, p) addSon(result, identWithPragma(p, allowDot=true)) if p.tok.tokType == tkBracketLe and p.validInd: addSon(result, parseGenericParamList(p)) else: addSon(result, ast.emptyNode) if p.tok.tokType == tkEquals: getTok(p) optInd(p, result) addSon(result, parseTypeDefAux(p)) else: addSon(result, ast.emptyNode) indAndComment(p, result) # special extension! proc parseVarTuple(p: var TParser): PNode = #| varTuple = '(' optInd identWithPragma ^+ comma optPar ')' '=' optInd expr result = newNodeP(nkVarTuple, p) getTok(p) # skip '(' optInd(p, result) while p.tok.tokType in {tkSymbol, tkAccent}: var a = identWithPragma(p) addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) skipComment(p, a) addSon(result, ast.emptyNode) # no type desc optPar(p) eat(p, tkBracketRi) eat(p, tkEquals) optInd(p, result) addSon(result, parseExpr(p)) proc parseVariable(p: var TParser): PNode = #| variable = (varTuple / identColonEquals) indAndComment if p.tok.tokType == tkBracketLe: result = parseVarTuple(p) else: result = parseIdentColonEquals(p, {withPragma}) indAndComment(p, result) proc parseBind(p: var TParser, k: TNodeKind): PNode = #| bindStmt = 'bind' optInd qualifiedIdent ^+ comma #| mixinStmt = 'mixin' optInd qualifiedIdent ^+ comma result = newNodeP(k, p) getTok(p) optInd(p, result) while true: var a = qualifiedIdent(p) addSon(result, a) if p.tok.tokType != tkComma: break getTok(p) optInd(p, a) proc parseStmtPragma(p: var TParser): PNode = result = parsePragma(p) if p.tok.tokType == tkCurlyLe: let a = result result = newNodeI(nkPragmaBlock, a.info) getTok(p) skipComment(p, result) result.add a result.add parseStmt(p) eat(p, tkCurlyRi) proc simpleStmt(p: var TParser): PNode = case p.tok.tokType of tkReturn: result = parseReturnOrRaise(p, nkReturnStmt) of tkRaise: result = parseReturnOrRaise(p, nkRaiseStmt) of tkYield: result = parseReturnOrRaise(p, nkYieldStmt) of tkDiscard: result = parseReturnOrRaise(p, nkDiscardStmt) of tkBreak: result = parseReturnOrRaise(p, nkBreakStmt) of tkContinue: result = parseReturnOrRaise(p, nkContinueStmt) of tkCurlyDotLe: result = parseStmtPragma(p) of tkImport: result = parseImport(p, nkImportStmt) of tkExport: result = parseImport(p, nkExportStmt) of tkFrom: result = parseFromStmt(p) of tkInclude: result = parseIncludeStmt(p) of tkComment: result = newCommentStmt(p) else: if isExprStart(p): result = parseExprStmt(p) else: result = ast.emptyNode if result.kind notin {nkEmpty, nkCommentStmt}: skipComment(p, result) proc complexOrSimpleStmt(p: var TParser): PNode = case p.tok.tokType of tkIf: result = parseIfOrWhen(p, nkIfStmt) of tkWhile: result = parseWhile(p) of tkCase: result = parseCase(p) of tkTry: result = parseTry(p) of tkFor: result = parseFor(p) of tkBlock: result = parseBlock(p) of tkStatic: result = parseStaticOrDefer(p, nkStaticStmt) of tkDefer: result = parseStaticOrDefer(p, nkDefer) of tkAsm: result = parseAsm(p) of tkProc: result = parseRoutine(p, nkProcDef) of tkMethod: result = parseRoutine(p, nkMethodDef) of tkIterator: result = parseRoutine(p, nkIteratorDef) of tkMacro: result = parseRoutine(p, nkMacroDef) of tkTemplate: result = parseRoutine(p, nkTemplateDef) of tkConverter: result = parseRoutine(p, nkConverterDef) of tkType: getTok(p) if p.tok.tokType == tkBracketLe: getTok(p) result = newNodeP(nkTypeOfExpr, p) result.addSon(primary(p, pmTypeDesc)) eat(p, tkBracketRi) result = parseOperators(p, result, -1, pmNormal) else: result = parseSection(p, nkTypeSection, parseTypeDef) of tkConst: result = parseSection(p, nkConstSection, parseConstant) of tkLet: result = parseSection(p, nkLetSection, parseVariable) of tkWhen: result = parseIfOrWhen(p, nkWhenStmt) of tkVar: result = parseSection(p, nkVarSection, parseVariable) of tkBind: result = parseBind(p, nkBindStmt) of tkMixin: result = parseBind(p, nkMixinStmt) of tkUsing: result = parseSection(p, nkUsingStmt, parseVariable) else: result = simpleStmt(p) proc parseStmt(p: var TParser): PNode = result = complexOrSimpleStmt(p) proc parseAll*(p: var TParser): PNode = ## Parses the rest of the input stream held by the parser into a PNode. result = newNodeP(nkStmtList, p) while p.tok.tokType != tkEof: var a = complexOrSimpleStmt(p) if a.kind != nkEmpty: addSon(result, a) else: parMessage(p, errExprExpected, p.tok) # bugfix: consume a token here to prevent an endless loop: getTok(p) proc parseTopLevelStmt*(p: var TParser): PNode = ## Implements an iterator which, when called repeatedly, returns the next ## top-level statement or emptyNode if end of stream. result = ast.emptyNode while true: case p.tok.tokType of tkSemiColon: getTok(p) of tkEof: break else: result = complexOrSimpleStmt(p) if result.kind == nkEmpty: parMessage(p, errExprExpected, p.tok) break