-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathlexer.rkt
executable file
·75 lines (63 loc) · 2.12 KB
/
lexer.rkt
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
#lang racket
(module+ test (require rackunit rackunit/text-ui))
(define (eat-ws inp)
(regexp-try-match #px"^[[:space:]]+" inp))
(define (parse-prefix inp)
(regexp-match #px"[[:graph:]]+" inp))
(define (parse-command inp)
(regexp-match #px"[0-9]{3}|[[:alpha:]]+" inp))
(define (parse-params inp)
(let loop ([result '()])
(eat-ws inp)
(cond
[(eof-object? (peek-char inp))
(reverse result)]
[(char=? #\: (peek-char inp))
(begin
(read-char inp)
(if (eof-object? (peek-char inp))
result
(loop (cons `(param . ,(regexp-match #px"[^\u0000\r\n]+" inp)) result))))]
[else
(loop (cons `(param . ,(regexp-match #px"[^\u0000\r\n ]+" inp)) result))])))
(define (parse-crlf inp )
(regexp-match #px"\r\n" inp))
(provide parse-message)
(define/contract parse-message
((or/c string? input-port?) . -> . list?)
(match-lambda
[(? string? message)
(parse-message (open-input-string message))]
[(? input-port? message)
(begin0
(cons
(if (char=? #\: (peek-char message))
(begin
(read-char message)
(cons 'prefix (parse-prefix message)))
'(prefix))
(begin
(eat-ws message)
(begin0
`([command . ,(parse-command message)]
[params . ,(parse-params message)])
(parse-crlf message)))))]))
(module+ test
(define-test-suite all-tests
(check-equal? (parse-params (open-input-string ":"))
'())
(check-equal?
(parse-message
":offby1!n=user@pdpc/supporter/monthlybyte/offby1 PRIVMSG ##cinema :rudybot: uptime")
'((prefix #"offby1!n=user@pdpc/supporter/monthlybyte/offby1")
(command #"PRIVMSG")
;; Ahh! It honors multiple consecutive spaces! The old way didn't.
(params (param #"##cinema") (param #"rudybot: uptime"))))
(check-equal?
(parse-message
":nick!knack@frotz 123 #channel :some stuff")
'((prefix #"nick!knack@frotz")
(command #"123")
(params (param #"#channel")
(param #"some stuff")))))
(run-tests all-tests 'verbose))