Repository navigation
Expand file tree
/
Copy pathLexer.fs
More file actions
74 lines (65 loc) · 2.84 KB
/
Copy pathLexer.fs
File metadata and controls
74 lines (65 loc) · 2.84 KB
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
namespace ParseExample
[<RequireQualifiedAccess>]
module Lexer =
let private (|Digit|_|) (c : char) : byte option =
if '0' <= c && c <= '9' then
Some (byte c - byte '0')
else
None
let private isAlphaNumeric (c : char) : bool =
('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')
let lex (s : string) : Token seq =
seq {
let mutable i = 0
while i < s.Length do
match i, s.[i] with
| Token.SingleChar token ->
i <- i + 1
yield token
| startI, Digit _ ->
i <- i + 1
let mutable shouldBreak = false
while i < s.Length && not shouldBreak do
match s.[i] with
| Digit _ -> i <- i + 1
| _ -> shouldBreak <- true
yield Token.standalone TokenType.ConstInt startI (i - startI)
| _, ' ' -> i <- i + 1
| _, '.' when i < s.Length - 1 && s.[i + 1] = '[' ->
yield Token.standalone TokenType.ArrayIndex i 2
i <- i + 2
| _, 'i' when
i < s.Length - 1
&& s.[i + 1] = 'f'
&& (i + 2 >= s.Length || not (isAlphaNumeric s.[i + 2]))
->
yield Token.standalone TokenType.If i 2
i <- i + 2
| _, 't' when
i < s.Length - 3
&& s.[i + 1 .. i + 3] = "hen"
&& (i + 4 >= s.Length || not (isAlphaNumeric s.[i + 4]))
->
yield Token.standalone TokenType.Then i 4
i <- i + 4
| _, 'e' when
i < s.Length - 3
&& s.[i + 1 .. i + 3] = "lse"
&& (i + 4 >= s.Length || not (isAlphaNumeric s.[i + 4]))
->
yield Token.standalone TokenType.Else i 4
i <- i + 4
| startI, c ->
if ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') then
i <- i + 1
let mutable shouldBreak = false
while i < s.Length && not shouldBreak do
let c = s.[i]
if ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') then
i <- i + 1
else
shouldBreak <- true
yield Token.standalone TokenType.Var startI (i - startI)
else
failwithf "Could not tokenize, char %c, at position %i" c startI
}