From 66a2cc6959459a63968b097cdba543103d30c051 Mon Sep 17 00:00:00 2001 From: coolguy Date: Sun, 30 Aug 2026 02:14:37 +0900 Subject: [PATCH] =?UTF-8?q?lexer:=20=EC=96=B4=ED=9C=98=20=EB=B6=84?= =?UTF-8?q?=EC=84=9D=20=EA=B5=AC=ED=98=84=EA=B3=BC=20ASI=20=ED=95=A8?= =?UTF-8?q?=EC=A0=95=20=ED=95=98=EB=82=98=20=EC=A0=95=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grammar.ebnf의 어휘 절을 구현한다. 렉서는 선읽기를 요구하지 않고, 문법과 얽히는 유일한 부분인 NEWLINE 삽입은 can_end_statement 하나로 판정한다. 모든 토큰이 위치를 들고 다닌다 — 진단 품질이 헌법급이므로 나중에 붙이지 않는다. 샘플을 실제로 렉싱해 함정을 하나 잡았다. effects 절이 줄 끝에 오면 "}"가 값 종료 토큰이라 NEWLINE이 삽입되어 다음 줄의 "->"와 끊긴다(Go ASI와 같은 형태). 렉서에 문맥을 주는 대신 — 렉서 피드백은 철학 2가 배제한다 — 시그니처 머리의 흡수 위치를 프로덕션에 명시적으로 적어 닫았다. 파서가 임의로 건너뛰는 것이 아니라 문법에 적힌 자리에서만 흡수한다. 다중 줄 목록의 후행 콤마 필수도 함께 명시(콤마로 끝난 줄은 NEWLINE을 만들지 않으므로 목록이 자연히 이어진다). cool check는 어휘 분석을 돌리되 통과했다고 말하지 않는다. 파이프라인의 나머지가 없는 이상 그 파일은 검사된 것이 아니다. 디버깅용 cool tokens 추가. 테스트 30건: 키워드, 두 글자 연산자 우선, NEWLINE 삽입 6가지 경우, 리터럴과 이스케이프, 오류 7종과 오류 위치, 그리고 samples/*.cool 전체가 어휘 분석을 통과하는지. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_019ZVDeU6KLuUVL3gs18Hm3E --- bin/main.ml | 21 ++-- docs/grammar.ebnf | 25 ++++- lib/driver.ml | 56 +++++++++-- lib/lexer.ml | 192 ++++++++++++++++++++++++++++++++++++ lib/token.ml | 162 ++++++++++++++++++++++++++++++ test/dune | 4 +- test/test_coollang.ml | 222 +++++++++++++++++++++++++++++++++++++++++- 7 files changed, 657 insertions(+), 25 deletions(-) create mode 100644 lib/lexer.ml create mode 100644 lib/token.ml diff --git a/bin/main.ml b/bin/main.ml index 3f78185..7f47fd5 100644 --- a/bin/main.ml +++ b/bin/main.ml @@ -4,16 +4,22 @@ let usage = 사용법: cool check ... 타입/effect/capability 검사 (fast path) cool run typed IR 인터프리터로 실행 + cool tokens 토큰 덤프 (렉서 디버깅) cool version 버전 출력 |} -let report = function - | Ok () -> 0 - | Error errors -> - List.iter - (fun e -> prerr_endline (Coollang.Driver.string_of_error e)) - errors; - 1 +let report_errors errors = + List.iter (fun e -> prerr_endline (Coollang.Driver.string_of_error e)) errors; + 1 + +let report = function Ok () -> 0 | Error errors -> report_errors errors + +let dump_tokens file = + match Coollang.Driver.tokens file with + | Error errors -> report_errors errors + | Ok tokens -> + List.iter (fun t -> print_endline (Coollang.Token.show t)) tokens; + 0 let () = let argv = Array.to_list Sys.argv in @@ -21,6 +27,7 @@ let () = match List.tl argv with | "check" :: files -> report (Coollang.Driver.check files) | [ "run"; file ] -> report (Coollang.Driver.run file) + | [ "tokens"; file ] -> dump_tokens file | [ "version" ] -> print_endline Coollang.Version.string; 0 diff --git a/docs/grammar.ebnf b/docs/grammar.ebnf index f3c3591..3bb3fa8 100644 --- a/docs/grammar.ebnf +++ b/docs/grammar.ebnf @@ -24,6 +24,15 @@ * 그 줄 끝에 NEWLINE 토큰을 넣는다. 그 외에는 넣지 않는다. * 따라서 연산자나 여는 괄호로 끝나는 줄은 다음 줄로 이어진다. * 빈 줄과 주석만 있는 줄은 NEWLINE을 만들지 않는다. + * + * 다중 줄 목록(파라미터, 인자, 필드, variant, 리스트 리터럴)은 후행 콤마가 + * 필수다. 콤마로 끝난 줄은 NEWLINE을 만들지 않으므로 목록이 자연히 이어진다. + * 공식 formatter가 이를 강제한다. + * + * 시그니처 머리에서는 NEWLINE이 문법적으로 허용되고 무시된다. effects 절이 + * 줄 끝에 오면 "}"가 값 종료 토큰이라 NEWLINE이 삽입되는데, 이 자리는 문이 + * 끝날 수 있는 자리가 아니므로 아래 프로덕션이 { NEWLINE }으로 흡수한다. + * 흡수 위치를 프로덕션에 명시적으로 적는다 — 파서가 임의로 건너뛰지 않는다. *) ident = letter , { letter | digit | "_" } ; @@ -37,7 +46,9 @@ literal = int_lit | string_lit | bool_lit ; (* ------------------------------------------------------------------ *) module = { NEWLINE } , { item } ; -item = ( import | reexport | decl ) , NEWLINE ; +item = ( import | reexport | decl ) , { NEWLINE } ; +(* decl이 이미 NEWLINE을 흡수했을 수 있으므로 항목 구분자는 0개 이상이다. + * 문 수준에서는 그렇지 않다 — stmt는 NEWLINE 하나를 반드시 요구한다 *) import = "import" , string_lit , "as" , ident ; reexport = "reexport" , ident ; @@ -50,7 +61,10 @@ decl = [ "pub" ] , ( fn_decl | struct_decl | enum_decl (* ------------------------------------------------------------------ *) fn_decl = "fn" , ident , [ gen_params ] , "(" , [ params ] , ")" , - [ eff_result ] , [ "->" , type ] , [ block ] ; + { NEWLINE } , + [ eff_result , { NEWLINE } ] , + [ "->" , type , { NEWLINE } ] , + [ block ] ; (* block이 없으면 시그니처 선언. interface 파일과 capability 본문에서 쓴다 *) struct_decl = [ "copyable" ] , "struct" , ident , [ gen_params ] , @@ -61,8 +75,8 @@ enum_decl = "enum" , ident , [ gen_params ] , "{" , { variant } , "}" ; variant = ident , [ "(" , type_list , ")" ] , "," , { NEWLINE } ; capability_decl = "capability" , ident , "{" , { cap_method } , "}" ; -cap_method = "fn" , ident , "(" , [ params ] , ")" , - [ eff_result ] , [ "->" , type ] , NEWLINE ; +cap_method = "fn" , ident , "(" , [ params ] , ")" , { NEWLINE } , + [ eff_result , { NEWLINE } ] , [ "->" , type ] , NEWLINE ; const_decl = "const" , ident , ":" , type , "=" , expr ; @@ -110,7 +124,8 @@ type_list = type , { "," , type } , [ "," ] ; (* ------------------------------------------------------------------ *) block = "{" , { NEWLINE } , { stmt } , "}" ; -stmt = ( let_stmt | return_stmt | assign_stmt | expr ) , NEWLINE ; +stmt = ( let_stmt | return_stmt | assign_stmt | expr ) , + NEWLINE , { NEWLINE } ; let_stmt = "let" , [ "mut" ] , pattern , [ ":" , type ] , "=" , expr ; return_stmt = "return" , [ expr ] ; diff --git a/lib/driver.ml b/lib/driver.ml index 1c73c79..5de862e 100644 --- a/lib/driver.ml +++ b/lib/driver.ml @@ -1,17 +1,59 @@ -(* v0 파이프라인의 자리표시자. +(* v0 파이프라인. parse -> name resolution -> type check -> effect/capability check -> interface artifact + hash -> (cool run 시) 얇은 typed IR -> interpreter - 각 단계는 별도 모듈로 분리해 들어온다. 지금은 CLI 형태만 고정한다. *) + 현재 구현된 단계: 어휘 분석. *) -type error = { file : string; message : string } +type error = { file : string; line : int; col : int; message : string } -let string_of_error { file; message } = Printf.sprintf "%s: %s" file message +let string_of_error { file; line; col; message } = + Printf.sprintf "%s:%d:%d: %s" file line col message + +let read_file file = + try + let ic = open_in_bin file in + let n = in_channel_length ic in + let s = really_input_string ic n in + close_in ic; + Ok s + with Sys_error msg -> Error { file; line = 0; col = 0; message = msg } + +let lex_file file = + match read_file file with + | Error e -> Error e + | Ok src -> ( + match Lexer.lex_result src with + | Ok tokens -> Ok tokens + | Error { pos; msg } -> + Error { file; line = pos.line; col = pos.col; message = msg }) + +let tokens (file : string) : (Token.t list, error list) result = + match lex_file file with Ok ts -> Ok ts | Error e -> Error [ e ] let check (files : string list) : (unit, error list) result = match files with - | [] -> Error [ { file = ""; message = "검사할 파일이 없습니다" } ] - | file :: _ -> Error [ { file; message = "check 파이프라인이 아직 구현되지 않았습니다" } ] + | [] -> + Error [ { file = ""; line = 0; col = 0; message = "검사할 파일이 없습니다" } ] + | _ -> + let errors = + List.filter_map + (fun f -> match lex_file f with Ok _ -> None | Error e -> Some e) + files + in + if errors <> [] then Error errors + else + (* 어휘 분석은 통과했다. 통과했다고 말하지 않는다 — 파이프라인의 + 나머지가 아직 없으므로 검사되지 않은 것이다. *) + Error + (List.map + (fun f -> + { + file = f; + line = 0; + col = 0; + message = "어휘 분석까지 통과. 파서가 아직 구현되지 않았습니다"; + }) + files) let run (file : string) : (unit, error list) result = - Error [ { file; message = "interpreter가 아직 구현되지 않았습니다" } ] + Error [ { file; line = 0; col = 0; message = "interpreter가 아직 구현되지 않았습니다" } ] diff --git a/lib/lexer.ml b/lib/lexer.ml new file mode 100644 index 0000000..8208ada --- /dev/null +++ b/lib/lexer.ml @@ -0,0 +1,192 @@ +(* 렉서. grammar.ebnf의 어휘 절을 그대로 구현한다. + 유일하게 문법과 얽히는 부분은 NEWLINE 삽입인데, 그 판정은 + Token.can_end_statement 하나로 끝나며 선읽기를 요구하지 않는다. *) + +type error = { pos : Token.pos; msg : string } + +exception Error of error + +type state = { + src : string; + len : int; + mutable i : int; + mutable line : int; + mutable bol : int; (* 현재 줄의 시작 offset *) + mutable out : Token.t list; (* 역순 누적 *) +} + +let pos st : Token.pos = { line = st.line; col = st.i - st.bol + 1 } +let fail st msg = raise (Error { pos = pos st; msg }) +let fail_at p msg = raise (Error { pos = p; msg }) +let peek st = if st.i < st.len then Some st.src.[st.i] else None +let peek2 st = if st.i + 1 < st.len then Some st.src.[st.i + 1] else None +let emit st p kind = st.out <- { Token.kind; pos = p } :: st.out +let last_kind st = match st.out with [] -> None | t :: _ -> Some t.Token.kind + +(* 줄 끝에 도달했을 때만 호출된다. 직전 토큰이 값으로 끝날 수 있으면 삽입. + 이미 Newline을 넣었거나 아무것도 없으면 넣지 않으므로, + 빈 줄과 주석만 있는 줄은 구분자를 만들지 않는다. *) +let maybe_newline st = + match last_kind st with + | Some k when Token.can_end_statement k -> emit st (pos st) Token.Newline + | _ -> () + +let is_letter c = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +let is_digit c = c >= '0' && c <= '9' +let is_ident_rest c = is_letter c || is_digit c || c = '_' + +let lex_ident st = + let p = pos st in + let start = st.i in + while st.i < st.len && is_ident_rest st.src.[st.i] do + st.i <- st.i + 1 + done; + let s = String.sub st.src start (st.i - start) in + match Token.keyword s with + | Some k -> emit st p k + | None -> emit st p (Token.Ident s) + +let lex_int st = + let p = pos st in + let start = st.i in + while st.i < st.len && (is_digit st.src.[st.i] || st.src.[st.i] = '_') do + st.i <- st.i + 1 + done; + (* 숫자 바로 뒤에 글자가 붙으면 오타일 가능성이 높다. 조용히 넘기지 않는다. *) + if st.i < st.len && is_letter st.src.[st.i] then + fail st "정수 리터럴 뒤에 글자가 올 수 없습니다"; + emit st p (Token.Int (String.sub st.src start (st.i - start))) + +let lex_string st = + let p = pos st in + st.i <- st.i + 1; + let buf = Buffer.create 16 in + let rec go () = + if st.i >= st.len then fail_at p "문자열이 닫히지 않았습니다" + else + match st.src.[st.i] with + | '"' -> st.i <- st.i + 1 + | '\n' -> fail_at p "문자열이 닫히지 않았습니다 (줄바꿈 전에 닫아야 합니다)" + | '\\' -> + st.i <- st.i + 1; + if st.i >= st.len then fail_at p "문자열이 닫히지 않았습니다"; + let c = st.src.[st.i] in + let decoded = + match c with + | 'n' -> '\n' + | 't' -> '\t' + | '\\' -> '\\' + | '"' -> '"' + | _ -> fail st (Printf.sprintf "알 수 없는 이스케이프 \\%c" c) + in + Buffer.add_char buf decoded; + st.i <- st.i + 1; + go () + | c -> + Buffer.add_char buf c; + st.i <- st.i + 1; + go () + in + go (); + emit st p (Token.Str (Buffer.contents buf)) + +let skip_line_comment st = + while st.i < st.len && st.src.[st.i] <> '\n' do + st.i <- st.i + 1 + done + +(* 한 글자 또는 두 글자 연산자. 두 글자를 항상 먼저 본다. *) +let lex_punct st = + let p = pos st in + let one k = + st.i <- st.i + 1; + emit st p k + in + let two k = + st.i <- st.i + 2; + emit st p k + in + match (st.src.[st.i], peek2 st) with + | '-', Some '>' -> two Token.Arrow + | '=', Some '>' -> two Token.FatArrow + | '=', Some '=' -> two Token.EqEq + | '!', Some '=' -> two Token.BangEq + | '<', Some '=' -> two Token.Le + | '>', Some '=' -> two Token.Ge + | '&', Some '&' -> two Token.AmpAmp + | '|', Some '|' -> two Token.PipePipe + | '(', _ -> one Token.LParen + | ')', _ -> one Token.RParen + | '{', _ -> one Token.LBrace + | '}', _ -> one Token.RBrace + | '[', _ -> one Token.LBracket + | ']', _ -> one Token.RBracket + | ',', _ -> one Token.Comma + | ':', _ -> one Token.Colon + | '.', _ -> one Token.Dot + | '?', _ -> one Token.Question + | '=', _ -> one Token.Eq + | '!', _ -> one Token.Bang + | '<', _ -> one Token.Lt + | '>', _ -> one Token.Gt + | '+', _ -> one Token.Plus + | '-', _ -> one Token.Minus + | '*', _ -> one Token.Star + | '/', _ -> one Token.Slash + | '%', _ -> one Token.Percent + | '|', _ -> one Token.Pipe + | '&', _ -> fail st "& 연산자는 없습니다 (&&를 의도했습니까?)" + | c, _ -> fail st (Printf.sprintf "예상치 못한 문자 %C" c) + +let lex (src : string) : Token.t list = + let st = + { src; len = String.length src; i = 0; line = 1; bol = 0; out = [] } + in + let rec go () = + if st.i >= st.len then ( + maybe_newline st; + emit st (pos st) Token.Eof) + else + let c = st.src.[st.i] in + match c with + | ' ' | '\t' | '\r' -> + st.i <- st.i + 1; + go () + | '\n' -> + maybe_newline st; + st.i <- st.i + 1; + st.line <- st.line + 1; + st.bol <- st.i; + go () + | '/' when peek2 st = Some '/' -> + skip_line_comment st; + go () + | '_' -> + let p = pos st in + if st.i + 1 < st.len && is_ident_rest st.src.[st.i + 1] then + fail st "이름은 문자로 시작해야 합니다" + else ( + st.i <- st.i + 1; + emit st p Token.Underscore; + go ()) + | c when is_letter c -> + lex_ident st; + go () + | c when is_digit c -> + lex_int st; + go () + | '"' -> + lex_string st; + go () + | _ -> + lex_punct st; + go () + in + go (); + List.rev st.out + +let lex_result src = + match lex src with tokens -> Ok tokens | exception Error e -> Error e + +(* peek는 lex_punct 안에서만 쓰이지 않으므로 경고를 피한다 *) +let _ = peek diff --git a/lib/token.ml b/lib/token.ml new file mode 100644 index 0000000..28350b8 --- /dev/null +++ b/lib/token.ml @@ -0,0 +1,162 @@ +(* 토큰 정의. 위치는 진단 품질이 헌법급이므로 모든 토큰이 들고 다닌다. *) + +type pos = { line : int; col : int } + +type kind = + (* 리터럴과 이름 *) + | Ident of string + | Int of string + | Str of string + (* 키워드 *) + | Kw_pub + | Kw_fn + | Kw_struct + | Kw_enum + | Kw_capability + | Kw_const + | Kw_import + | Kw_as + | Kw_reexport + | Kw_let + | Kw_mut + | Kw_own + | Kw_affine + | Kw_copyable + | Kw_effects + | Kw_return + | Kw_if + | Kw_else + | Kw_match + | Kw_scope + | Kw_true + | Kw_false + (* 구두점 *) + | LParen + | RParen + | LBrace + | RBrace + | LBracket + | RBracket + | Comma + | Colon + | Dot + | Arrow + | FatArrow + | Question + | Underscore + | Eq + | EqEq + | Bang + | BangEq + | Lt + | Le + | Gt + | Ge + | Plus + | Minus + | Star + | Slash + | Percent + | AmpAmp + | PipePipe + | Pipe + (* 렉서가 삽입하는 문 구분자 *) + | Newline + | Eof + +type t = { kind : kind; pos : pos } + +let keyword = function + | "pub" -> Some Kw_pub + | "fn" -> Some Kw_fn + | "struct" -> Some Kw_struct + | "enum" -> Some Kw_enum + | "capability" -> Some Kw_capability + | "const" -> Some Kw_const + | "import" -> Some Kw_import + | "as" -> Some Kw_as + | "reexport" -> Some Kw_reexport + | "let" -> Some Kw_let + | "mut" -> Some Kw_mut + | "own" -> Some Kw_own + | "affine" -> Some Kw_affine + | "copyable" -> Some Kw_copyable + | "effects" -> Some Kw_effects + | "return" -> Some Kw_return + | "if" -> Some Kw_if + | "else" -> Some Kw_else + | "match" -> Some Kw_match + | "scope" -> Some Kw_scope + | "true" -> Some Kw_true + | "false" -> Some Kw_false + | _ -> None + +let show_kind = function + | Ident s -> Printf.sprintf "이름 %s" s + | Int s -> Printf.sprintf "정수 %s" s + | Str _ -> "문자열" + | Kw_pub -> "pub" + | Kw_fn -> "fn" + | Kw_struct -> "struct" + | Kw_enum -> "enum" + | Kw_capability -> "capability" + | Kw_const -> "const" + | Kw_import -> "import" + | Kw_as -> "as" + | Kw_reexport -> "reexport" + | Kw_let -> "let" + | Kw_mut -> "mut" + | Kw_own -> "own" + | Kw_affine -> "affine" + | Kw_copyable -> "copyable" + | Kw_effects -> "effects" + | Kw_return -> "return" + | Kw_if -> "if" + | Kw_else -> "else" + | Kw_match -> "match" + | Kw_scope -> "scope" + | Kw_true -> "true" + | Kw_false -> "false" + | LParen -> "(" + | RParen -> ")" + | LBrace -> "{" + | RBrace -> "}" + | LBracket -> "[" + | RBracket -> "]" + | Comma -> "," + | Colon -> ":" + | Dot -> "." + | Arrow -> "->" + | FatArrow -> "=>" + | Question -> "?" + | Underscore -> "_" + | Eq -> "=" + | EqEq -> "==" + | Bang -> "!" + | BangEq -> "!=" + | Lt -> "<" + | Le -> "<=" + | Gt -> ">" + | Ge -> ">=" + | Plus -> "+" + | Minus -> "-" + | Star -> "*" + | Slash -> "/" + | Percent -> "%" + | AmpAmp -> "&&" + | PipePipe -> "||" + | Pipe -> "|" + | Newline -> "줄바꿈" + | Eof -> "파일 끝" + +let show { kind; pos } = + Printf.sprintf "%d:%d %s" pos.line pos.col (show_kind kind) + +(* 줄 끝에서 문 구분자를 삽입할지 결정한다 (grammar.ebnf 어휘 절). + 값으로 끝날 수 있는 토큰 뒤에서만 삽입하므로, 연산자나 여는 괄호로 + 끝나는 줄은 다음 줄로 이어진다. *) +let can_end_statement = function + | Ident _ | Int _ | Str _ | RParen | RBracket | RBrace | Question | Kw_return + | Kw_true | Kw_false -> + true + | _ -> false diff --git a/test/dune b/test/dune index edfcadf..38438f3 100644 --- a/test/dune +++ b/test/dune @@ -1,3 +1,5 @@ (test (name test_coollang) - (libraries coollang)) + (libraries coollang) + (deps + (glob_files %{workspace_root}/samples/*.cool))) diff --git a/test/test_coollang.ml b/test/test_coollang.ml index c10ef2e..840f45a 100644 --- a/test/test_coollang.ml +++ b/test/test_coollang.ml @@ -1,8 +1,220 @@ -let () = assert (String.length Coollang.Version.string > 0) +open Coollang + +let failures = ref 0 + +let check name cond = + if not cond then ( + incr failures; + Printf.printf "FAIL %s\n" name) + +let kinds src = + match Lexer.lex_result src with + | Ok ts -> List.map (fun t -> t.Token.kind) ts + | Error e -> + failwith + (Printf.sprintf "예상치 못한 렉서 오류 %d:%d %s" e.pos.line e.pos.col e.msg) + +let lex_error src = + match Lexer.lex_result src with Ok _ -> None | Error e -> Some e.msg + +(* --- 키워드와 이름 --- *) let () = - match Coollang.Driver.check [] with - | Error [ _ ] -> () - | _ -> failwith "빈 입력에는 오류가 나야 한다" + check "키워드 인식" + (kinds "fn own affine" + = [ Token.Kw_fn; Token.Kw_own; Token.Kw_affine; Token.Eof ]); + check "이름은 키워드가 아니다" + (kinds "own_er" = [ Token.Ident "own_er"; Token.Newline; Token.Eof ]) -let () = print_endline "ok" +(* --- 두 글자 연산자를 먼저 본다 --- *) + +let () = + check "화살표" + (kinds "-> => == != <= >= && ||" + = [ + Token.Arrow; + Token.FatArrow; + Token.EqEq; + Token.BangEq; + Token.Le; + Token.Ge; + Token.AmpAmp; + Token.PipePipe; + Token.Eof; + ]); + check "한 글자로 갈리는 자리" + (kinds "- = ! < > |" + = [ + Token.Minus; + Token.Eq; + Token.Bang; + Token.Lt; + Token.Gt; + Token.Pipe; + Token.Eof; + ]) + +(* --- NEWLINE 삽입 (grammar.ebnf 어휘 절) --- *) + +let () = + check "값으로 끝난 줄 뒤에 삽입" + (kinds "a\nb" + = [ + Token.Ident "a"; + Token.Newline; + Token.Ident "b"; + Token.Newline; + Token.Eof; + ]); + check "여는 괄호로 끝난 줄은 이어진다" + (kinds "f(\na)" + = [ + Token.Ident "f"; + Token.LParen; + Token.Ident "a"; + Token.RParen; + Token.Newline; + Token.Eof; + ]); + check "연산자로 끝난 줄은 이어진다" + (kinds "a +\nb" + = [ Token.Ident "a"; Token.Plus; Token.Ident "b"; Token.Newline; Token.Eof ] + ); + check "빈 줄은 구분자를 만들지 않는다" + (kinds "a\n\n\nb" + = [ + Token.Ident "a"; + Token.Newline; + Token.Ident "b"; + Token.Newline; + Token.Eof; + ]); + check "주석만 있는 줄도 마찬가지" + (kinds "a\n// 설명\nb" + = [ + Token.Ident "a"; + Token.Newline; + Token.Ident "b"; + Token.Newline; + Token.Eof; + ]); + check "닫는 괄호 뒤에는 삽입" + (kinds "f()\ng()" + = [ + Token.Ident "f"; + Token.LParen; + Token.RParen; + Token.Newline; + Token.Ident "g"; + Token.LParen; + Token.RParen; + Token.Newline; + Token.Eof; + ]); + check "? 뒤에는 삽입" + (kinds "f()?\ng" + = [ + Token.Ident "f"; + Token.LParen; + Token.RParen; + Token.Question; + Token.Newline; + Token.Ident "g"; + Token.Newline; + Token.Eof; + ]); + check "빈 입력" (kinds "" = [ Token.Eof ]) + +(* --- 리터럴 --- *) + +let () = + check "정수와 밑줄" + (kinds "1_000" = [ Token.Int "1_000"; Token.Newline; Token.Eof ]); + check "문자열 이스케이프" + (kinds "\"a\\nb\"" = [ Token.Str "a\nb"; Token.Newline; Token.Eof ]); + check "밑줄 단독" (kinds "_" = [ Token.Underscore; Token.Eof ]) + +(* --- 오류 --- *) + +let () = + check "닫히지 않은 문자열" (lex_error "\"abc" <> None); + check "줄바꿈 전에 닫지 않은 문자열" (lex_error "\"abc\ndef\"" <> None); + check "알 수 없는 이스케이프" (lex_error "\"a\\qb\"" <> None); + check "이름은 문자로 시작" (lex_error "_foo" <> None); + check "단독 &" (lex_error "a & b" <> None); + check "정수 뒤 글자" (lex_error "12abc" <> None); + check "예상치 못한 문자" (lex_error "a @ b" <> None) + +(* --- 오류 위치 --- *) + +let () = + match Lexer.lex_result "a\nb @ c" with + | Ok _ -> check "위치 보고" false + | Error e -> check "위치 보고" (e.pos.line = 2 && e.pos.col = 3) + +(* --- 샘플 전체가 어휘 분석을 통과해야 한다 --- *) + +let () = + let dir = "../samples" in + let files = + Sys.readdir dir |> Array.to_list + |> List.filter (fun f -> Filename.check_suffix f ".cool") + |> List.sort compare + in + check "샘플이 존재한다" (List.length files >= 7); + List.iter + (fun f -> + let path = Filename.concat dir f in + match Driver.tokens path with + | Ok ts -> check (f ^ " 어휘 분석") (List.length ts > 10) + | Error errors -> + List.iter + (fun e -> Printf.printf " %s\n" (Driver.string_of_error e)) + errors; + check (f ^ " 어휘 분석") false) + files + +(* --- 기존 계약 --- *) + +let () = + check "버전 비어있지 않음" (String.length Version.string > 0); + match Driver.check [] with Error [ _ ] -> () | _ -> check "빈 입력에는 오류" false + +let () = + if !failures = 0 then print_endline "ok" + else ( + Printf.printf "%d개 실패\n" !failures; + exit 1) + +(* --- ASI 함정: effects 절이 줄 끝에 오면 } 뒤에 NEWLINE이 삽입된다. + 렉서는 이대로 두고 문법이 { NEWLINE }으로 흡수한다 (grammar.ebnf). --- *) + +let () = + check "닫는 중괄호 뒤 줄바꿈은 삽입된다" + (kinds "effects {A.b}\n-> Int" + = [ + Token.Kw_effects; + Token.LBrace; + Token.Ident "A"; + Token.Dot; + Token.Ident "b"; + Token.RBrace; + Token.Newline; + Token.Arrow; + Token.Ident "Int"; + Token.Newline; + Token.Eof; + ]); + check "후행 콤마가 있으면 목록이 이어진다" + (kinds "f(\na,\nb,\n)" + = [ + Token.Ident "f"; + Token.LParen; + Token.Ident "a"; + Token.Comma; + Token.Ident "b"; + Token.Comma; + Token.RParen; + Token.Newline; + Token.Eof; + ])