ce/lex.ml

62 lines
1.4 KiB
OCaml
Raw Normal View History

2022-01-10 01:31:47 +09:00
type tokens = Token.t Seq.t
2022-01-17 15:17:18 +09:00
exception Token_not_found
2022-01-10 01:31:47 +09:00
let either f g c =
f c || g c
let is_digit c =
'0' <= c && c <= '9'
let is_num = function
| 'x' -> true
| c -> is_digit c
let is_whitespace = function
| ' ' | '\t' | '\n' -> true
| _ -> false
let is_alpha c =
2022-01-10 23:11:13 +09:00
('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')
2022-01-10 01:31:47 +09:00
let is_ident_start =
either is_alpha ((=) '_')
let is_ident =
either is_ident_start is_digit
(* same as take_while f seq, drop_while f seq *)
let rec partition_while f seq : 'a Seq.t * 'a Seq.t =
match seq () with
| Seq.Nil -> Seq.empty, seq
| Seq.Cons (x, seq) ->
if f x then
let n, s = partition_while f seq in
Seq.cons x n, s
else
Seq.(empty, cons x seq)
let tokenize (str : string) : tokens =
let seq = String.to_seq str in
2022-01-17 15:21:27 +09:00
let rec aux seq () =
2022-01-10 01:31:47 +09:00
let open Token in
match seq () with
2022-01-17 15:21:27 +09:00
| Seq.Nil -> Seq.Nil
2022-01-10 01:31:47 +09:00
| Seq.Cons (x, s) ->
if is_whitespace x then
2022-01-17 15:21:27 +09:00
aux s () (* skip whitespace *)
2022-01-10 01:31:47 +09:00
else if is_digit x then
2022-01-17 15:17:18 +09:00
let n, s = partition_while is_num seq in
let n = int_of_string @@ String.of_seq n in
2022-01-17 15:21:27 +09:00
Seq.Cons (Int n, aux s)
2022-01-10 01:31:47 +09:00
else if is_ident_start x then
2022-01-17 15:17:18 +09:00
let id, s = partition_while is_ident seq in
let id = String.of_seq id in
2022-01-17 15:21:27 +09:00
Seq.Cons (Ident id, aux s)
2022-01-10 01:31:47 +09:00
else
2022-01-17 15:17:18 +09:00
match find_token seq with
| None -> raise Token_not_found
2022-01-17 15:21:27 +09:00
| Some (t, s) -> Seq.Cons (t, aux s)
2022-01-10 01:31:47 +09:00
in
aux seq