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) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019ZVDeU6KLuUVL3gs18Hm3E
60 lines
2.0 KiB
OCaml
60 lines
2.0 KiB
OCaml
(* v0 파이프라인.
|
|
parse -> name resolution -> type check -> effect/capability check
|
|
-> interface artifact + hash -> (cool run 시) 얇은 typed IR -> interpreter
|
|
|
|
현재 구현된 단계: 어휘 분석. *)
|
|
|
|
type error = { file : string; line : int; col : int; message : string }
|
|
|
|
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 = "<none>"; 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; line = 0; col = 0; message = "interpreter가 아직 구현되지 않았습니다" } ]
|