grammar: 문법 문서를 기계가 읽는 소스로 — LL(1)이 처음으로 검증된다
설명서와 파서가 어긋나 있었다. 그냥 어긋난 게 아니라, 그 설명서를 안 읽고
"else if가 안 된다"고 마찰 보고서에 잘못 적었다 — 설명서로서 제 역할을 한
번도 못 했다는 뜻이다.
lib/ebnf.ml: EBNF를 데이터로 읽는다. nullable, FIRST, FOLLOW를 계산하고
LL(1) 충돌을 보고한다. 매개변수 프로덕션(name<p>)을 지원한다 — expr_ns와
목록을 복제 없이 적기 위한 것이다.
문법 첫머리의 "설계 제약: LL(1)"은 지금까지 사람의 주장이었다. 기계로 재니
충돌 18건이 나왔다. 세 부류였다:
- 구조적 3건: stmt(assign/expr), primary(ident/struct_lit), pattern —
파서는 왼쪽 인수분해를 손으로 했는데 문법에 안 적혀 있었다
- 후행 콤마 9건: X , { "," , X } , [ "," ]는 콤마를 본 시점에 갈리지 않는다.
우재귀로 다시 적었다
- 줄바꿈 흡수 6건: 어느 쪽이 먹어도 파스 트리가 같다. greedy 규칙을 표기에
명시하고 그렇게 해소되는 것만 따로 분류한다
지금은 진짜 충돌 0건이고, 테스트가 이를 고정한다.
병렬 조사에서 나온 드리프트도 모두 반영했다:
- named_type, name_pattern에 한정 이름(Shapes.Shape, Shapes.Circle)
- name_pattern이 인자 0개와 괄호 없는 한정 생성자를 받는다
- string_lit의 이스케이프
- cap_method의 gen_params (파서가 이미 허용하고 있었다)
- field/variant/field_init/arm 사이의 콤마는 필수다
- stmt 사이의 NEWLINE도 필수다 — 선택적으로 적었더니 그것 하나가 LL(1)
충돌 셋을 만들었다
- { NEWLINE }을 전부 [ NEWLINE ]으로. 렉서가 연속 줄바꿈을 만들 수 없다
expr_ns는 산문 주석이었고 파서 상태 플래그로 구현돼 있었다. 매개변수
프로덕션으로 형식화해 문맥자유가 됐다.
렉서 쪽: Token.next_kind가 모든 토큰을 한 번씩 잇는다. 나열이 빠지면
컴파일러가 지적한다. 문법 문서의 키워드 표와 줄 끝 판정 목록은 이제
lib/lexical_doc.ml이 거기서 생성하고 테스트가 대조한다.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019ZVDeU6KLuUVL3gs18Hm3E
This commit is contained in:
+141
-80
@@ -7,10 +7,24 @@
|
||||
* { } 반복 (0 이상)
|
||||
* ( ) 묶음
|
||||
* " " 단말
|
||||
* < > 매개변수 (아래 참고)
|
||||
* (* *) 주석
|
||||
*
|
||||
* 설계 제약: LL(1). backtracking 없음, 렉서 피드백 없음.
|
||||
* 어떤 프로덕션도 무한 선읽기를 요구해서는 안 된다 (철학 2).
|
||||
* 이 제약은 주장이 아니라 검사된다 — tools/ebnf_tool.exe가 이 파일을 읽어
|
||||
* FIRST/FOLLOW를 계산하고 충돌을 보고하며, 충돌이 있으면 테스트가 깨진다.
|
||||
*
|
||||
* 매개변수 프로덕션:
|
||||
* name<p> = ... p ... 로 정의하고 name<arg> 로 참조한다.
|
||||
* 인자마다 하나의 평범한 프로덕션으로 펼쳐진다. 인자에 따라 몸통이 달라야
|
||||
* 하면 머리에 인자를 박아 특수화한다 (name<yes> = ... ; name<no> = ... ;).
|
||||
* 목록과 expr_ns를 복제 없이 적기 위한 것이다.
|
||||
*
|
||||
* 흡수 규칙:
|
||||
* [ NEWLINE ]은 최대한 먹는다(greedy). 줄바꿈은 값을 갖지 않으므로 바깥
|
||||
* 프로덕션이 먹든 안쪽이 먹든 파스 트리가 같다. 이 규칙이 없으면 흡수
|
||||
* 지점마다 형식적 중의성이 생기지만, 어느 쪽으로 읽어도 결과가 같다.
|
||||
*)
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
@@ -20,39 +34,71 @@
|
||||
(* 주석은 // 부터 줄 끝까지. 블록 주석 없음 (중첩 규칙이라는 변종을 만들지 않는다) *)
|
||||
|
||||
(* 문 구분자 NEWLINE은 렉서가 삽입한다:
|
||||
* 줄의 마지막 토큰이 ident, 리터럴, ")", "]", "}", "?", "return" 중 하나이면
|
||||
* 그 줄 끝에 NEWLINE 토큰을 넣는다. 그 외에는 넣지 않는다.
|
||||
* 따라서 연산자나 여는 괄호로 끝나는 줄은 다음 줄로 이어진다.
|
||||
* 줄의 마지막 토큰이 값으로 끝날 수 있는 토큰이면 그 줄 끝에 NEWLINE을 넣는다.
|
||||
* 그 목록은 아래 생성 블록에 있다 — 손으로 적지 않고 코드에서 뽑는다.
|
||||
* 그 외에는 넣지 않는다. 따라서 연산자나 여는 괄호로 끝나는 줄은 이어진다.
|
||||
* 빈 줄과 주석만 있는 줄은 NEWLINE을 만들지 않는다.
|
||||
*
|
||||
* NEWLINE은 결코 연달아 나오지 않는다. 삽입 판정이 "마지막으로 낸 토큰"을
|
||||
* 보는데 NEWLINE 자신은 값으로 끝날 수 있는 토큰이 아니기 때문이다.
|
||||
* 그래서 이 문법의 모든 흡수 지점은 { NEWLINE }이 아니라 [ NEWLINE ]이다.
|
||||
*
|
||||
(* 여기부터 lib/token.ml에서 생성됩니다 — 손으로 고치지 마십시오 *)
|
||||
* 줄을 끝낼 수 있는 토큰. 줄의 마지막 토큰이 이 중 하나이면 그 줄 끝에
|
||||
* NEWLINE이 삽입된다. Token.can_end_statement가 원본이다.
|
||||
*
|
||||
* ident | int_lit | string_lit | "return" | "true" | "false" | ")" |
|
||||
* "}" | "]" | "?"
|
||||
*
|
||||
* 키워드. 이름으로 쓸 수 없다. Token.keyword가 원본이다.
|
||||
*
|
||||
* "pub" | "fn" | "struct" | "enum" | "capability" | "const" |
|
||||
* "import" | "as" | "reexport" | "let" | "mut" | "own" | "affine" |
|
||||
* "copyable" | "effects" | "return" | "if" | "else" | "match" |
|
||||
* "scope" | "true" | "false"
|
||||
(* 생성 끝 *)
|
||||
*
|
||||
* 다중 줄 목록(파라미터, 인자, 필드, variant, 리스트 리터럴)은 후행 콤마가
|
||||
* 필수다. 콤마로 끝난 줄은 NEWLINE을 만들지 않으므로 목록이 자연히 이어진다.
|
||||
* 공식 formatter가 이를 강제한다.
|
||||
*
|
||||
* 중괄호 목록(struct 정의, enum 정의, struct 리터럴, effect 집합, match 팔)
|
||||
* 안에서는 항목 구분자 주변의 NEWLINE이 무시된다. 문이 놓이는 자리가 아니므로
|
||||
* 구분자로 쓰이지 않는다. 아래 프로덕션에 { NEWLINE }으로 적혀 있다.
|
||||
*
|
||||
* 시그니처 머리에서는 NEWLINE이 문법적으로 허용되고 무시된다. effects 절이
|
||||
* 줄 끝에 오면 "}"가 값 종료 토큰이라 NEWLINE이 삽입되는데, 이 자리는 문이
|
||||
* 끝날 수 있는 자리가 아니므로 아래 프로덕션이 { NEWLINE }으로 흡수한다.
|
||||
* 끝날 수 있는 자리가 아니므로 아래 프로덕션이 [ NEWLINE ]으로 흡수한다.
|
||||
* 흡수 위치를 프로덕션에 명시적으로 적는다 — 파서가 임의로 건너뛰지 않는다.
|
||||
*)
|
||||
|
||||
ident = letter , { letter | digit | "_" } ;
|
||||
int_lit = digit , { digit | "_" } ;
|
||||
string_lit = '"' , { char - '"' } , '"' ;
|
||||
string_lit = '"' , { str_char } , '"' ;
|
||||
str_char = ( char - '"' - "\" ) | escape ;
|
||||
escape = "\" , ( "n" | "t" | "\" | '"' ) ;
|
||||
bool_lit = "true" | "false" ;
|
||||
literal = int_lit | string_lit | bool_lit ;
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 목록 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
(* 후행 콤마를 허용하는 목록. 우재귀로 적는 이유는 LL(1)이다 —
|
||||
* X , { "," , X } , [ "," ] 로 적으면 콤마를 본 시점에 "항목이 더 있는지"와
|
||||
* "이게 후행 콤마인지"가 갈리지 않는다. 콤마를 먹은 뒤 닫는 토큰을 보고
|
||||
* 갈리는 것이 파서가 실제로 하는 일이고, 아래가 그것이다. *)
|
||||
list<item> = item , list_rest<item> ;
|
||||
list_rest<item> = [ "," , [ list<item> ] ] ;
|
||||
|
||||
(* 중괄호 안의 목록. 항목 사이에 줄바꿈이 올 수 있다는 점만 다르다.
|
||||
* 항목 사이의 콤마는 필수이고 마지막 항목 뒤에서만 생략된다. *)
|
||||
brace_list<item> = [ NEWLINE ] , [ item , brace_rest<item> ] ;
|
||||
brace_rest<item> = [ NEWLINE ] ,
|
||||
[ "," , [ NEWLINE ] , [ item , brace_rest<item> ] ] ;
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 모듈 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
module = { NEWLINE } , { item } ;
|
||||
item = ( import | reexport | decl ) , { NEWLINE } ;
|
||||
(* decl이 이미 NEWLINE을 흡수했을 수 있으므로 항목 구분자는 0개 이상이다.
|
||||
* 문 수준에서는 그렇지 않다 — stmt는 NEWLINE 하나를 반드시 요구한다 *)
|
||||
module = [ NEWLINE ] , { item } ;
|
||||
item = ( import | reexport | decl ) , [ NEWLINE ] ;
|
||||
|
||||
import = "import" , string_lit , "as" , ident ;
|
||||
reexport = "reexport" , ident ;
|
||||
@@ -65,53 +111,47 @@ decl = [ "pub" ] , ( fn_decl | struct_decl | enum_decl
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
fn_decl = "fn" , ident , [ gen_params ] , "(" , [ params ] , ")" ,
|
||||
{ NEWLINE } ,
|
||||
[ eff_result , { NEWLINE } ] ,
|
||||
[ "->" , type , { NEWLINE } ] ,
|
||||
[ NEWLINE ] ,
|
||||
[ eff_result , [ NEWLINE ] ] ,
|
||||
[ "->" , type , [ NEWLINE ] ] ,
|
||||
[ block ] ;
|
||||
(* block이 없으면 시그니처 선언. interface 파일과 capability 본문에서 쓴다 *)
|
||||
(* block이 없으면 시그니처 선언. std/*.cool과 capability 본문에서 쓴다 *)
|
||||
|
||||
struct_decl = [ "copyable" ] , "struct" , ident , [ gen_params ] ,
|
||||
"{" , { field } , "}" ;
|
||||
field = ident , ":" , type , { NEWLINE } ,
|
||||
[ "," , { NEWLINE } ] ;
|
||||
"{" , brace_list<field> , "}" ;
|
||||
field = ident , ":" , type ;
|
||||
|
||||
enum_decl = "enum" , ident , [ gen_params ] , "{" , { variant } , "}" ;
|
||||
variant = ident , [ "(" , type_list , ")" ] , { NEWLINE } ,
|
||||
[ "," , { NEWLINE } ] ;
|
||||
enum_decl = "enum" , ident , [ gen_params ] ,
|
||||
"{" , brace_list<variant> , "}" ;
|
||||
variant = ident , [ "(" , type_list , ")" ] ;
|
||||
|
||||
capability_decl = "capability" , ident , "{" , { NEWLINE } , { cap_method } , "}" ;
|
||||
cap_method = "fn" , ident , "(" , [ params ] , ")" , { NEWLINE } ,
|
||||
[ eff_result , { NEWLINE } ] , [ "->" , type ] ,
|
||||
{ NEWLINE } ;
|
||||
capability_decl = "capability" , ident , "{" , [ NEWLINE ] , { cap_method } , "}" ;
|
||||
cap_method = "fn" , ident , [ gen_params ] , "(" , [ params ] , ")" ,
|
||||
[ NEWLINE ] ,
|
||||
[ eff_result , [ NEWLINE ] ] ,
|
||||
[ "->" , type ] ,
|
||||
[ NEWLINE ] ;
|
||||
|
||||
const_decl = "const" , ident , ":" , type , "=" , expr ;
|
||||
|
||||
gen_params = "[" , gen_param , { "," , gen_param } , [ "," ] , "]" ;
|
||||
gen_params = "[" , list<gen_param> , "]" ;
|
||||
gen_param = ident , [ ":" , "effects" ] ;
|
||||
(* ident 단독 = 타입 파라미터, ": effects" = effect 파라미터 *)
|
||||
|
||||
params = param , { "," , param } , [ "," ] ;
|
||||
params = list<param> ;
|
||||
param = [ "own" ] , [ "mut" ] , ident , ":" , type ;
|
||||
(* 무표기 = use(빌림). own만이 소유 이전을 뜻한다.
|
||||
* 수식어 순서 고정: 바인딩 수식어(own, mut)가 먼저, 타입 수식어(affine)는 type 안 *)
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* effect 절 *)
|
||||
(* effect *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
(* 결과 위치 — 함수 선언 자신의 effect. 합집합 허용 *)
|
||||
eff_result = "effects" , eff_union ;
|
||||
eff_union = eff_atom , { "|" , eff_atom } ;
|
||||
(* 결과 위치에서만 합집합이 가능하다 *)
|
||||
eff_result = "effects" , eff_atom , { "|" , eff_atom } ;
|
||||
|
||||
(* 파라미터 위치 — 함수 타입 안의 effect. 합집합이 문법에 없다.
|
||||
* "검사기가 거부"가 아니라 "그런 문장이 존재하지 않음"이다 *)
|
||||
(* 파라미터 위치. 합집합이 없다 — 문법에 그런 문장이 존재하지 않는다.
|
||||
* "검사기가 거부"가 아니라 "쓸 수 없다"이다 *)
|
||||
eff_param = "effects" , eff_atom ;
|
||||
|
||||
eff_atom = ident | eff_set ;
|
||||
eff_set = "{" , { NEWLINE } ,
|
||||
[ eff_name , { { NEWLINE } , "," , { NEWLINE } , eff_name } ,
|
||||
{ NEWLINE } , [ "," , { NEWLINE } ] ] , "}" ;
|
||||
eff_set = "{" , brace_list<eff_name> , "}" ;
|
||||
eff_name = ident , "." , ident ;
|
||||
(* 타입 수준 이름만. capability 값의 identity는 정적 층에 등장하지 않는다 *)
|
||||
|
||||
@@ -124,28 +164,35 @@ type = fn_type | named_type ;
|
||||
fn_type = [ "affine" ] , "fn" , "(" , [ type_list ] , ")" ,
|
||||
[ eff_param ] , [ "->" , type ] ;
|
||||
|
||||
named_type = ident , [ type_args ] ;
|
||||
type_args = "[" , targ , { "," , targ } , [ "," ] , "]" ;
|
||||
(* 다른 모듈의 타입은 별칭으로 한정한다: Shapes.Shape.
|
||||
* 한 단계뿐이다 — 별칭은 이 모듈의 이름이므로 더 이어질 자리가 없다 *)
|
||||
named_type = ident , [ "." , ident ] , [ type_args ] ;
|
||||
type_args = "[" , list<targ> , "]" ;
|
||||
targ = type | eff_set ;
|
||||
(* 제네릭 인자는 타입 또는 effect다. 맨 이름은 둘 다일 수 있으므로 파서는
|
||||
* 타입으로 읽고 이름 해소가 판정한다 — 구문 층에서 갈리지 않아도 된다 *)
|
||||
type_list = type , { "," , type } , [ "," ] ;
|
||||
type_list = list<type> ;
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 문과 블록 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
block = "{" , { NEWLINE } ,
|
||||
[ stmt , { stmt_sep , stmt } , [ stmt_sep ] ] , "}" ;
|
||||
stmt = let_stmt | return_stmt | assign_stmt | expr ;
|
||||
stmt_sep = NEWLINE , { NEWLINE } ;
|
||||
(* 마지막 문의 구분자는 "}" 앞에서 생략된다.
|
||||
block = "{" , [ NEWLINE ] , [ stmt , stmt_rest ] , "}" ;
|
||||
stmt_rest = [ NEWLINE , [ stmt , stmt_rest ] ] ;
|
||||
(* 문 사이의 NEWLINE은 필수다. 선택적으로 적으면 식이 식 뒤에 바로 올 수
|
||||
* 있게 되고, 그러면 "-"나 "("로 시작하는 다음 문과 앞 식의 이어짐이
|
||||
* 갈리지 않는다 — 한 토큰으로 결정할 수 없게 된다.
|
||||
* 마지막 문의 구분자는 "}" 앞에서 생략된다.
|
||||
* fn(s) { String.concat(prefix, s) } 처럼 한 줄로 쓰는 자리가 있기 때문이다 *)
|
||||
|
||||
stmt = let_stmt | return_stmt | expr_stmt ;
|
||||
let_stmt = "let" , [ "mut" ] , pattern , [ ":" , type ] , "=" , expr ;
|
||||
return_stmt = "return" , [ expr ] ;
|
||||
assign_stmt = place , "=" , expr ;
|
||||
place = ident , { "." , ident } ;
|
||||
(* 값 생략은 다음 토큰이 NEWLINE이거나 "}"일 때다 *)
|
||||
|
||||
expr_stmt = expr , [ "=" , expr ] ;
|
||||
(* 대입 왼쪽에 올 수 있는 것(이름 또는 필드 접근)은 구문이 아니라 정적 검사가
|
||||
* 판정한다. 구문으로 가르면 ident 하나로 대입과 식이 갈리지 않는다 *)
|
||||
|
||||
(* 블록의 값 = 마지막 stmt가 expr이면 그 값, 아니면 Unit.
|
||||
* return은 조기 탈출 전용이며, 꼬리 위치의 return은 formatter가 지적한다 *)
|
||||
@@ -154,62 +201,76 @@ place = ident , { "." , ident } ;
|
||||
(* 식 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
expr = or_expr ;
|
||||
or_expr = and_expr , { "||" , and_expr } ;
|
||||
and_expr = cmp_expr , { "&&" , cmp_expr } ;
|
||||
cmp_expr = add_expr , [ cmp_op , add_expr ] ;
|
||||
cmp_op = "==" | "!=" | "<" | "<=" | ">" | ">=" ;
|
||||
add_expr = mul_expr , { ( "+" | "-" ) , mul_expr } ;
|
||||
mul_expr = unary , { ( "*" | "/" | "%" ) , unary } ;
|
||||
unary = [ "!" | "-" ] , postfix ;
|
||||
(* 매개변수 s는 이 자리에서 struct 리터럴을 쓸 수 있는지다.
|
||||
* expr = 쓸 수 있는 자리 (거의 전부)
|
||||
* expr_ns = 쓸 수 없는 자리 (if/match의 머리)
|
||||
* if/match의 머리에서 "{"가 블록의 시작인지 struct 리터럴인지 갈리지
|
||||
* 않으므로, 그 자리의 struct 리터럴은 괄호로 감싼다.
|
||||
* 제약은 머리 식의 최상위에만 걸린다 — 괄호, 대괄호, 블록, 호출 인자 등
|
||||
* 새 구문 문맥에 들어가는 순간 풀린다. 그래서 primary<no>의 괄호 안이
|
||||
* expr(= yes)이다.
|
||||
* scope의 머리에는 식이 없다(이름 둘뿐) — 제약이 걸릴 자리가 없다 *)
|
||||
expr = or_expr<yes> ;
|
||||
expr_ns = or_expr<no> ;
|
||||
|
||||
postfix = primary , { call_sfx | field_sfx | inst_sfx | "?" } ;
|
||||
or_expr<s> = and_expr<s> , { "||" , and_expr<s> } ;
|
||||
and_expr<s> = cmp_expr<s> , { "&&" , cmp_expr<s> } ;
|
||||
cmp_expr<s> = add_expr<s> , [ cmp_op , add_expr<s> ] ;
|
||||
cmp_op = "==" | "!=" | "<" | "<=" | ">" | ">=" ;
|
||||
add_expr<s> = mul_expr<s> , { ( "+" | "-" ) , mul_expr<s> } ;
|
||||
mul_expr<s> = unary<s> , { ( "*" | "/" | "%" ) , unary<s> } ;
|
||||
unary<s> = [ "!" | "-" ] , postfix<s> ;
|
||||
|
||||
postfix<s> = primary<s> , { call_sfx | field_sfx | inst_sfx | "?" } ;
|
||||
call_sfx = "(" , [ args ] , ")" ;
|
||||
field_sfx = "." , ident ;
|
||||
inst_sfx = type_args ;
|
||||
(* 후위 "[" = 명시적 인스턴스화, 전위 "[" = 리스트 리터럴. 위치가 결정한다 *)
|
||||
args = expr , { "," , expr } , [ "," ] ;
|
||||
args = list<expr> ;
|
||||
|
||||
primary = literal
|
||||
| ident
|
||||
primary<s> = literal
|
||||
| list_lit
|
||||
| struct_lit
|
||||
| closure
|
||||
| if_expr
|
||||
| match_expr
|
||||
| scope_expr
|
||||
| "(" , expr , ")" ;
|
||||
| "(" , expr , ")"
|
||||
| name_or_struct<s> ;
|
||||
|
||||
list_lit = "[" , [ expr , { "," , expr } , [ "," ] ] , "]" ;
|
||||
(* ident 하나로는 이름인지 struct 리터럴인지 갈리지 않는다. "{"를 보고
|
||||
* 갈리므로 왼쪽으로 인수분해해 적는다 — 파서가 실제로 하는 일이다 *)
|
||||
name_or_struct<yes> = ident , [ struct_body ] ;
|
||||
name_or_struct<no> = ident ;
|
||||
struct_body = "{" , brace_list<field_init> , "}" ;
|
||||
field_init = ident , ":" , expr ;
|
||||
|
||||
list_lit = "[" , [ args ] , "]" ;
|
||||
(* 빈 리스트는 타입 주석이 필요하다: let xs: List[Int] = [] *)
|
||||
|
||||
struct_lit = ident , "{" , { field_init } , "}" ;
|
||||
field_init = ident , ":" , expr , { NEWLINE } , [ "," , { NEWLINE } ] ;
|
||||
|
||||
closure = "fn" , "(" , [ cl_params ] , ")" ,
|
||||
[ eff_param ] , [ "->" , type ] , block ;
|
||||
cl_params = cl_param , { "," , cl_param } , [ "," ] ;
|
||||
cl_params = list<cl_param> ;
|
||||
cl_param = ident , [ ":" , type ] ;
|
||||
(* 파라미터 타입 생략 가능. 호출 지점의 기대 타입에서 읽어온다 — 함수 로컬이다.
|
||||
* 기대 타입이 없는 자리에서 생략하면 error *)
|
||||
|
||||
if_expr = "if" , expr_ns , block , [ "else" , ( block | if_expr ) ] ;
|
||||
match_expr = "match" , expr_ns , "{" , { arm } , "}" ;
|
||||
arm = pattern , "=>" , ( expr | block ) , { NEWLINE } ,
|
||||
[ "," , { NEWLINE } ] ;
|
||||
match_expr = "match" , expr_ns , "{" , brace_list<arm> , "}" ;
|
||||
arm = pattern , "=>" , ( expr | block ) ;
|
||||
scope_expr = "scope" , ident , "=" , ident , block ;
|
||||
(* scope 자식 = 부모 { ... }
|
||||
* 부모를 구문에 적는다. 적지 않으면 자식의 부모가 "가장 가까운 스코프"가 되어
|
||||
* 정확히 ambient authority가 된다 — 이 언어가 배제하는 것 *)
|
||||
|
||||
(* expr_ns = struct_lit로 시작하지 않는 expr.
|
||||
* if/match/scope의 머리 자리에서 "{"가 블록의 시작인지 struct 리터럴인지
|
||||
* 갈리지 않으므로, 그 자리의 struct 리터럴은 괄호로 감싼다 *)
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 패턴 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
pattern = "_" | literal | ctor_pattern | ident ;
|
||||
ctor_pattern = ident , "(" , pattern , { "," , pattern } , [ "," ] , ")" ;
|
||||
pattern = "_" | literal | name_pattern ;
|
||||
|
||||
(* 이름 하나로는 바인딩인지 생성자인지 갈리지 않는다. 판정 규칙:
|
||||
* 한정되었으면(Shapes.Dot) 언제나 생성자다
|
||||
* 괄호가 붙으면 생성자다
|
||||
* 둘 다 아니면 바인딩이거나, 이름 해소가 생성자로 판정한다 *)
|
||||
name_pattern = ident , [ "." , ident ] , [ "(" , [ list<pattern> ] , ")" ] ;
|
||||
(* 가드 없음. 중첩은 제한 없음 (exhaustiveness 알고리즘이 처리한다) *)
|
||||
|
||||
+634
@@ -0,0 +1,634 @@
|
||||
(* EBNF 읽기.
|
||||
|
||||
docs/grammar.ebnf를 데이터로 읽어들인다. 여기서부터 문법은 사람이 읽는
|
||||
문서가 아니라 기계가 소비하는 소스가 된다.
|
||||
|
||||
이 파일이 존재하는 이유: 설명서와 파서가 따로 있으면 어긋난다. 실제로
|
||||
어긋났고, 어긋난 줄 아무도 몰랐다. 문법을 읽을 수 있게 되면 파서와
|
||||
기계적으로 대조할 수 있고, 나아가 파서를 여기서 뽑아낼 수 있다.
|
||||
|
||||
표기는 grammar.ebnf 머리에 적힌 그대로다:
|
||||
= 정의 | 선택 [ ] 선택적 { } 반복
|
||||
( ) 묶음 " " 단말 (* *) 주석 - 제외 *)
|
||||
|
||||
type expr =
|
||||
| Ref of string (* 다른 프로덕션 또는 토큰 이름 *)
|
||||
| RefArg of string * string (* 매개변수 프로덕션 참조: primary<ok> *)
|
||||
| Term of string (* "fn" 같은 리터럴 단말 *)
|
||||
| Seq of expr list
|
||||
| Alt of expr list
|
||||
| Opt of expr
|
||||
| Rep of expr
|
||||
| Except of expr * expr (* char - '"' *)
|
||||
|
||||
(* 매개변수 프로덕션. expr_ns를 표현하려면 필요하다 — if/match의 머리에서만
|
||||
struct 리터럴이 금지되는데, 그 제약은 식 문법 전체를 타고 내려간다.
|
||||
매개변수가 없으면 여덟 개 프로덕션을 통째로 복제해야 하고, 그러면 사람이
|
||||
읽는 문서로서의 값이 사라진다. *)
|
||||
type rule = { name : string; params : string list; body : expr; line : int }
|
||||
type t = rule list
|
||||
type error = { line : int; msg : string }
|
||||
|
||||
exception Error of error
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 어휘 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
type tok =
|
||||
| T_ident of string
|
||||
| T_str of string
|
||||
| T_eq
|
||||
| T_semi
|
||||
| T_comma
|
||||
| T_bar
|
||||
| T_lbracket
|
||||
| T_rbracket
|
||||
| T_lbrace
|
||||
| T_rbrace
|
||||
| T_lparen
|
||||
| T_rparen
|
||||
| T_minus
|
||||
| T_lt
|
||||
| T_gt
|
||||
| T_eof
|
||||
|
||||
let tokenize (src : string) : (tok * int) array =
|
||||
let n = String.length src in
|
||||
let out = ref [] in
|
||||
let line = ref 1 in
|
||||
let i = ref 0 in
|
||||
let emit t = out := (t, !line) :: !out in
|
||||
while !i < n do
|
||||
let c = src.[!i] in
|
||||
if c = '\n' then (
|
||||
incr line;
|
||||
incr i)
|
||||
else if c = ' ' || c = '\t' || c = '\r' then incr i
|
||||
else if c = '(' && !i + 1 < n && src.[!i + 1] = '*' then begin
|
||||
(* 주석. 중첩을 허용한다 — 문법 파일에 설명이 길게 들어간다 *)
|
||||
let depth = ref 0 in
|
||||
let fin = ref false in
|
||||
while (not !fin) && !i < n do
|
||||
if !i + 1 < n && src.[!i] = '(' && src.[!i + 1] = '*' then (
|
||||
incr depth;
|
||||
i := !i + 2)
|
||||
else if !i + 1 < n && src.[!i] = '*' && src.[!i + 1] = ')' then (
|
||||
decr depth;
|
||||
i := !i + 2;
|
||||
if !depth = 0 then fin := true)
|
||||
else (
|
||||
if src.[!i] = '\n' then incr line;
|
||||
incr i)
|
||||
done;
|
||||
if not !fin then raise (Error { line = !line; msg = "주석이 닫히지 않았습니다" })
|
||||
end
|
||||
else if c = '"' || c = '\'' then begin
|
||||
let quote = c in
|
||||
let start = !i + 1 in
|
||||
incr i;
|
||||
while !i < n && src.[!i] <> quote do
|
||||
if src.[!i] = '\n' then raise (Error { line = !line; msg = "단말이 닫히지 않았습니다" });
|
||||
incr i
|
||||
done;
|
||||
if !i >= n then raise (Error { line = !line; msg = "단말이 닫히지 않았습니다" });
|
||||
emit (T_str (String.sub src start (!i - start)));
|
||||
incr i
|
||||
end
|
||||
else if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c = '_' then begin
|
||||
let start = !i in
|
||||
while
|
||||
!i < n
|
||||
&&
|
||||
let d = src.[!i] in
|
||||
(d >= 'a' && d <= 'z')
|
||||
|| (d >= 'A' && d <= 'Z')
|
||||
|| (d >= '0' && d <= '9')
|
||||
|| d = '_'
|
||||
do
|
||||
incr i
|
||||
done;
|
||||
emit (T_ident (String.sub src start (!i - start)))
|
||||
end
|
||||
else begin
|
||||
let single t =
|
||||
emit t;
|
||||
incr i
|
||||
in
|
||||
(match c with
|
||||
| '=' -> single T_eq
|
||||
| ';' -> single T_semi
|
||||
| ',' -> single T_comma
|
||||
| '|' -> single T_bar
|
||||
| '[' -> single T_lbracket
|
||||
| ']' -> single T_rbracket
|
||||
| '{' -> single T_lbrace
|
||||
| '}' -> single T_rbrace
|
||||
| '(' -> single T_lparen
|
||||
| ')' -> single T_rparen
|
||||
| '-' -> single T_minus
|
||||
| '<' -> single T_lt
|
||||
| '>' -> single T_gt
|
||||
| _ ->
|
||||
raise
|
||||
(Error
|
||||
{ line = !line; msg = Printf.sprintf "알 수 없는 문자 %c" c }))
|
||||
end
|
||||
done;
|
||||
emit T_eof;
|
||||
Array.of_list (List.rev !out)
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 구문 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
type state = { toks : (tok * int) array; mutable p : int }
|
||||
|
||||
let cur st = fst st.toks.(st.p)
|
||||
let line st = snd st.toks.(st.p)
|
||||
let adv st = if st.p < Array.length st.toks - 1 then st.p <- st.p + 1
|
||||
|
||||
let fail st msg = raise (Error { line = line st; msg })
|
||||
|
||||
let eat st t what =
|
||||
if cur st = t then adv st
|
||||
else fail st (Printf.sprintf "%s이(가) 필요합니다" what)
|
||||
|
||||
(* alt := seq { "|" seq } *)
|
||||
let rec parse_alt st =
|
||||
let first = parse_seq st in
|
||||
if cur st <> T_bar then first
|
||||
else begin
|
||||
let acc = ref [ first ] in
|
||||
while cur st = T_bar do
|
||||
adv st;
|
||||
acc := parse_seq st :: !acc
|
||||
done;
|
||||
Alt (List.rev !acc)
|
||||
end
|
||||
|
||||
(* seq := factor { "," factor } *)
|
||||
and parse_seq st =
|
||||
let first = parse_factor st in
|
||||
if cur st <> T_comma then first
|
||||
else begin
|
||||
let acc = ref [ first ] in
|
||||
while cur st = T_comma do
|
||||
adv st;
|
||||
acc := parse_factor st :: !acc
|
||||
done;
|
||||
Seq (List.rev !acc)
|
||||
end
|
||||
|
||||
(* factor := primary { "-" primary } — 제외는 여러 번 올 수 있다 *)
|
||||
and parse_factor st =
|
||||
let a = ref (parse_primary st) in
|
||||
while cur st = T_minus do
|
||||
adv st;
|
||||
a := Except (!a, parse_primary st)
|
||||
done;
|
||||
!a
|
||||
|
||||
and parse_primary st =
|
||||
match cur st with
|
||||
| T_ident n ->
|
||||
adv st;
|
||||
if cur st = T_lt then begin
|
||||
adv st;
|
||||
let a =
|
||||
match cur st with
|
||||
| T_ident a ->
|
||||
adv st;
|
||||
a
|
||||
| _ -> fail st "매개변수 이름"
|
||||
in
|
||||
eat st T_gt ">";
|
||||
RefArg (n, a)
|
||||
end
|
||||
else Ref n
|
||||
| T_str s ->
|
||||
adv st;
|
||||
Term s
|
||||
| T_lbracket ->
|
||||
adv st;
|
||||
let e = parse_alt st in
|
||||
eat st T_rbracket "]";
|
||||
Opt e
|
||||
| T_lbrace ->
|
||||
adv st;
|
||||
let e = parse_alt st in
|
||||
eat st T_rbrace "}";
|
||||
Rep e
|
||||
| T_lparen ->
|
||||
adv st;
|
||||
let e = parse_alt st in
|
||||
eat st T_rparen ")";
|
||||
e
|
||||
| _ -> fail st "이름, 단말, 또는 묶음"
|
||||
|
||||
let parse (src : string) : t =
|
||||
let st = { toks = tokenize src; p = 0 } in
|
||||
let rules = ref [] in
|
||||
while cur st <> T_eof do
|
||||
let ln = line st in
|
||||
let name =
|
||||
match cur st with
|
||||
| T_ident n ->
|
||||
adv st;
|
||||
n
|
||||
| _ -> fail st "프로덕션 이름"
|
||||
in
|
||||
let params =
|
||||
if cur st = T_lt then begin
|
||||
adv st;
|
||||
let acc = ref [] in
|
||||
let rec loop () =
|
||||
(match cur st with
|
||||
| T_ident p ->
|
||||
adv st;
|
||||
acc := p :: !acc
|
||||
| _ -> fail st "매개변수 이름");
|
||||
if cur st = T_comma then (
|
||||
adv st;
|
||||
loop ())
|
||||
in
|
||||
loop ();
|
||||
eat st T_gt ">";
|
||||
List.rev !acc
|
||||
end
|
||||
else []
|
||||
in
|
||||
eat st T_eq "=";
|
||||
let body = parse_alt st in
|
||||
eat st T_semi ";";
|
||||
rules := { name; params; body; line = ln } :: !rules
|
||||
done;
|
||||
List.rev !rules
|
||||
|
||||
let parse_result src = match parse src with r -> Ok r | exception Error e -> Error e
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 조회 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
let find (g : t) name = List.find_opt (fun r -> r.name = name) g
|
||||
|
||||
(* 정의되지 않은 채 참조된 이름. 토큰 이름일 수도 있고 빠뜨린 프로덕션일
|
||||
수도 있으므로 판정하지 않고 목록만 준다. *)
|
||||
let undefined (g : t) : string list =
|
||||
let defined = List.map (fun r -> r.name) g in
|
||||
let seen = Hashtbl.create 32 in
|
||||
let rec walk = function
|
||||
| Ref n -> if not (List.mem n defined) then Hashtbl.replace seen n ()
|
||||
| RefArg (n, _) -> if not (List.mem n defined) then Hashtbl.replace seen n ()
|
||||
| Term _ -> ()
|
||||
| Seq xs | Alt xs -> List.iter walk xs
|
||||
| Opt e | Rep e -> walk e
|
||||
| Except (a, b) ->
|
||||
walk a;
|
||||
walk b
|
||||
in
|
||||
List.iter (fun r -> walk r.body) g;
|
||||
Hashtbl.fold (fun k () acc -> k :: acc) seen [] |> List.sort compare
|
||||
|
||||
(* 어디서도 참조되지 않는 프로덕션. 시작 기호는 제외한다. *)
|
||||
let unreachable (g : t) ~(start : string) : string list =
|
||||
let used = Hashtbl.create 32 in
|
||||
let rec walk = function
|
||||
| Ref n -> Hashtbl.replace used n ()
|
||||
(* 인자로 넘어간 이름도 쓰인 것이다: brace_list<field>의 field *)
|
||||
| RefArg (n, a) ->
|
||||
Hashtbl.replace used n ();
|
||||
Hashtbl.replace used a ()
|
||||
| Term _ -> ()
|
||||
| Seq xs | Alt xs -> List.iter walk xs
|
||||
| Opt e | Rep e -> walk e
|
||||
| Except (a, b) ->
|
||||
walk a;
|
||||
walk b
|
||||
in
|
||||
List.iter (fun r -> walk r.body) g;
|
||||
List.filter_map
|
||||
(fun r -> if r.name = start || Hashtbl.mem used r.name then None else Some r.name)
|
||||
g
|
||||
|
||||
let rec show_expr = function
|
||||
| Ref n -> n
|
||||
| RefArg (n, a) -> n ^ "<" ^ a ^ ">"
|
||||
| Term s -> "\"" ^ s ^ "\""
|
||||
| Seq xs -> String.concat " , " (List.map show_expr xs)
|
||||
| Alt xs -> String.concat " | " (List.map show_paren xs)
|
||||
| Opt e -> "[ " ^ show_expr e ^ " ]"
|
||||
| Rep e -> "{ " ^ show_expr e ^ " }"
|
||||
| Except (a, b) -> show_paren a ^ " - " ^ show_paren b
|
||||
|
||||
and show_paren e =
|
||||
match e with Alt _ | Seq _ -> "( " ^ show_expr e ^ " )" | _ -> show_expr e
|
||||
|
||||
let show_rule r =
|
||||
let ps = if r.params = [] then "" else "<" ^ String.concat ", " r.params ^ ">" in
|
||||
r.name ^ ps ^ " = " ^ show_expr r.body ^ " ;"
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 단일화 *)
|
||||
(* *)
|
||||
(* 매개변수 프로덕션을 실제로 쓰인 인자별로 펼친다. primary<ok>와 *)
|
||||
(* primary<no>가 각각 하나의 평범한 프로덕션이 되고, 그 뒤 분석은 매개변수를 *)
|
||||
(* 몰라도 된다. 문서는 짧게 유지하고 기계는 펼친 것을 본다. *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
let mangle n a = n ^ "<" ^ a ^ ">"
|
||||
|
||||
let expand (g : t) : t =
|
||||
(* 인자를 머리에 박아 특수화한 규칙이 있으면 그것을 먼저 쓴다.
|
||||
ident_or_struct<yes>와 ident_or_struct<no>처럼 인자에 따라 몸통이
|
||||
달라지는 자리를 위한 것이다. 없으면 일반 규칙에 인자를 대입한다. *)
|
||||
let by_name_arg n a =
|
||||
match List.find_opt (fun r -> r.name = n && r.params = [ a ]) g with
|
||||
| Some r -> Some r
|
||||
| None -> List.find_opt (fun r -> r.name = n && r.params <> []) g
|
||||
in
|
||||
let out = Hashtbl.create 64 in
|
||||
let queue = ref [] in
|
||||
(* 인자를 실제 값으로 바꾸며 몸통을 복사한다 *)
|
||||
let rec subst (env : (string * string) list) e =
|
||||
match e with
|
||||
| Term _ -> e
|
||||
(* 매개변수 이름이 그대로 참조된 자리도 인자로 바꾼다: list<item>의 item *)
|
||||
| Ref n -> ( match List.assoc_opt n env with Some v -> Ref v | None -> e)
|
||||
| RefArg (n, a) ->
|
||||
let a = match List.assoc_opt a env with Some v -> v | None -> a in
|
||||
(match by_name_arg n a with
|
||||
| Some r when r.params <> [] ->
|
||||
let key = (n, a) in
|
||||
if not (Hashtbl.mem out (mangle n a)) && not (List.mem key !queue) then
|
||||
queue := key :: !queue;
|
||||
Ref (mangle n a)
|
||||
| _ -> Ref n)
|
||||
| Seq xs -> Seq (List.map (subst env) xs)
|
||||
| Alt xs -> Alt (List.map (subst env) xs)
|
||||
| Opt x -> Opt (subst env x)
|
||||
| Rep x -> Rep (subst env x)
|
||||
| Except (x, y) -> Except (subst env x, subst env y)
|
||||
in
|
||||
(* 매개변수 없는 규칙부터 *)
|
||||
List.iter
|
||||
(fun r ->
|
||||
if r.params = [] then
|
||||
Hashtbl.replace out r.name { r with body = subst [] r.body })
|
||||
g;
|
||||
while !queue <> [] do
|
||||
let n, a = List.hd !queue in
|
||||
queue := List.tl !queue;
|
||||
let key = mangle n a in
|
||||
if not (Hashtbl.mem out key) then
|
||||
match by_name_arg n a with
|
||||
| None -> ()
|
||||
| Some r ->
|
||||
let env = match r.params with p :: _ -> [ (p, a) ] | [] -> [] in
|
||||
Hashtbl.replace out key
|
||||
{ name = key; params = []; body = subst env r.body; line = r.line }
|
||||
done;
|
||||
(* 원본 순서를 최대한 유지한다 — 문서와 대조하기 쉽게 *)
|
||||
let ordered =
|
||||
List.concat_map
|
||||
(fun r ->
|
||||
if r.params = [] then
|
||||
match Hashtbl.find_opt out r.name with Some x -> [ x ] | None -> []
|
||||
else
|
||||
Hashtbl.fold
|
||||
(fun k v acc ->
|
||||
if String.length k > String.length r.name
|
||||
&& String.sub k 0 (String.length r.name + 1) = r.name ^ "<"
|
||||
then v :: acc
|
||||
else acc)
|
||||
out []
|
||||
|> List.sort (fun a b -> compare a.name b.name))
|
||||
g
|
||||
in
|
||||
ordered
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* nullable과 FIRST *)
|
||||
(* *)
|
||||
(* 여기서부터가 "다음 한 토큰만 보고 결정할 수 있는가"를 기계가 판정하는 *)
|
||||
(* 근거다. 문법 첫머리의 LL(1) 주장은 지금까지 사람의 말이었다. *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
(* 단말 하나의 이름. 리터럴은 그 철자, 토큰 부류는 그 이름. *)
|
||||
module SS = Set.Make (String)
|
||||
|
||||
type analysis = {
|
||||
rules : t;
|
||||
tokens : SS.t; (* 단말로 취급할 Ref 이름 (ident, NEWLINE 등) *)
|
||||
nullable : (string, bool) Hashtbl.t;
|
||||
first : (string, SS.t) Hashtbl.t;
|
||||
}
|
||||
|
||||
let is_token a n = SS.mem n a.tokens || find a.rules n = None
|
||||
|
||||
let rec nullable_expr a = function
|
||||
| Term _ -> false
|
||||
| Ref n -> if is_token a n then false else Hashtbl.find_opt a.nullable n = Some true
|
||||
| RefArg (n, x) -> nullable_expr a (Ref (mangle n x))
|
||||
| Seq xs -> List.for_all (nullable_expr a) xs
|
||||
| Alt xs -> List.exists (nullable_expr a) xs
|
||||
| Opt _ | Rep _ -> true
|
||||
| Except (x, _) -> nullable_expr a x
|
||||
|
||||
let rec first_expr a = function
|
||||
| Term s -> SS.singleton s
|
||||
| Ref n ->
|
||||
if is_token a n then SS.singleton n
|
||||
else ( match Hashtbl.find_opt a.first n with Some s -> s | None -> SS.empty)
|
||||
| RefArg (n, x) -> first_expr a (Ref (mangle n x))
|
||||
| Alt xs -> List.fold_left (fun acc x -> SS.union acc (first_expr a x)) SS.empty xs
|
||||
| Opt x | Rep x -> first_expr a x
|
||||
| Except (x, _) -> first_expr a x
|
||||
| Seq xs ->
|
||||
let rec go acc = function
|
||||
| [] -> acc
|
||||
| x :: rest ->
|
||||
let acc = SS.union acc (first_expr a x) in
|
||||
if nullable_expr a x then go acc rest else acc
|
||||
in
|
||||
go SS.empty xs
|
||||
|
||||
(* 변화가 없을 때까지 돈다. 문법은 작으므로 단순한 고정점으로 충분하다. *)
|
||||
let analyze ?(tokens = []) (g : t) : analysis =
|
||||
let a =
|
||||
{
|
||||
rules = g;
|
||||
tokens = SS.of_list tokens;
|
||||
nullable = Hashtbl.create 64;
|
||||
first = Hashtbl.create 64;
|
||||
}
|
||||
in
|
||||
List.iter (fun r -> Hashtbl.replace a.nullable r.name false) g;
|
||||
List.iter (fun r -> Hashtbl.replace a.first r.name SS.empty) g;
|
||||
let changed = ref true in
|
||||
while !changed do
|
||||
changed := false;
|
||||
List.iter
|
||||
(fun r ->
|
||||
let nu = nullable_expr a r.body in
|
||||
if nu && Hashtbl.find_opt a.nullable r.name <> Some true then (
|
||||
Hashtbl.replace a.nullable r.name true;
|
||||
changed := true);
|
||||
let f = first_expr a r.body in
|
||||
let old = match Hashtbl.find_opt a.first r.name with Some s -> s | None -> SS.empty in
|
||||
if not (SS.equal f old) then (
|
||||
Hashtbl.replace a.first r.name (SS.union old f);
|
||||
changed := true))
|
||||
g
|
||||
done;
|
||||
a
|
||||
|
||||
let first a name =
|
||||
match Hashtbl.find_opt a.first name with Some s -> s | None -> SS.empty
|
||||
|
||||
let nullable a name = Hashtbl.find_opt a.nullable name = Some true
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* FOLLOW와 LL(1) 충돌 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
(* 이어지는 자리를 (올 수 있는 단말들, 규칙 끝에 닿을 수 있는가)로 나른다.
|
||||
끝에 닿을 수 있으면 그 규칙의 FOLLOW가 더해진다. *)
|
||||
type follow_env = {
|
||||
a : analysis;
|
||||
fol : (string, SS.t) Hashtbl.t;
|
||||
mutable deps : (string * string) list; (* (n, owner): follow n ⊇ follow owner *)
|
||||
}
|
||||
|
||||
let get_fol e n = match Hashtbl.find_opt e.fol n with Some s -> s | None -> SS.empty
|
||||
|
||||
let rec collect e owner expr (cont : SS.t) (cont_end : bool) =
|
||||
match expr with
|
||||
| Term _ -> ()
|
||||
| RefArg (n, x) -> collect e owner (Ref (mangle n x)) cont cont_end
|
||||
| Ref n ->
|
||||
if not (is_token e.a n) then begin
|
||||
Hashtbl.replace e.fol n (SS.union (get_fol e n) cont);
|
||||
if cont_end && not (List.mem (n, owner) e.deps) then
|
||||
e.deps <- (n, owner) :: e.deps
|
||||
end
|
||||
| Alt xs -> List.iter (fun x -> collect e owner x cont cont_end) xs
|
||||
| Opt x -> collect e owner x cont cont_end
|
||||
(* 반복은 자기 자신이 뒤따를 수 있다 *)
|
||||
| Rep x -> collect e owner x (SS.union cont (first_expr e.a x)) cont_end
|
||||
| Except (x, _) -> collect e owner x cont cont_end
|
||||
| Seq xs ->
|
||||
let acc_first = ref cont and acc_end = ref cont_end in
|
||||
List.iter
|
||||
(fun x ->
|
||||
collect e owner x !acc_first !acc_end;
|
||||
let f = first_expr e.a x in
|
||||
if nullable_expr e.a x then acc_first := SS.union f !acc_first
|
||||
else (
|
||||
acc_first := f;
|
||||
acc_end := false))
|
||||
(List.rev xs)
|
||||
|
||||
let follows ?(tokens = []) (g : t) : (string, SS.t) Hashtbl.t =
|
||||
let a = analyze ~tokens g in
|
||||
let e = { a; fol = Hashtbl.create 64; deps = [] } in
|
||||
List.iter (fun r -> collect e r.name r.body SS.empty true) g;
|
||||
(* 규칙 끝에 닿는 참조는 그 규칙의 FOLLOW를 물려받는다. 고정점. *)
|
||||
let changed = ref true in
|
||||
while !changed do
|
||||
changed := false;
|
||||
List.iter
|
||||
(fun (n, owner) ->
|
||||
let merged = SS.union (get_fol e n) (get_fol e owner) in
|
||||
if not (SS.equal merged (get_fol e n)) then (
|
||||
Hashtbl.replace e.fol n merged;
|
||||
changed := true))
|
||||
e.deps
|
||||
done;
|
||||
e.fol
|
||||
|
||||
type conflict = {
|
||||
c_rule : string;
|
||||
c_line : int;
|
||||
c_kind : string; (* "선택" | "선택적" | "반복" *)
|
||||
c_tokens : string list; (* 겹치는 단말 *)
|
||||
c_detail : string;
|
||||
(* greedy 규칙으로 해소되는가. [ X ]와 { X }가 "최대한 먹는다"로 정의되면,
|
||||
겹치는 토큰이 흡수 대상뿐일 때 결정이 갈린다. 어느 쪽으로 읽든 같은
|
||||
것을 뜻하는 자리에서만 쓸 수 있는 해소다 — 진짜 중의성을 덮지 않도록
|
||||
greedy 토큰 목록은 문법이 명시한다. *)
|
||||
c_greedy : bool;
|
||||
}
|
||||
|
||||
(* 같은 단말로 시작하는 대안이 둘 이상이면 한 토큰으로 결정할 수 없다. *)
|
||||
let conflicts ?(tokens = []) ?(greedy = []) (g : t) : conflict list =
|
||||
let a = analyze ~tokens g in
|
||||
let fol = follows ~tokens g in
|
||||
let out = ref [] in
|
||||
let add r kind toks detail =
|
||||
if toks <> [] then
|
||||
out :=
|
||||
{
|
||||
c_rule = r.name;
|
||||
c_line = r.line;
|
||||
c_kind = kind;
|
||||
c_tokens = toks;
|
||||
c_detail = detail;
|
||||
(* 선택/반복만 greedy로 해소된다. 대안(Alt) 충돌은 못 덮는다 *)
|
||||
c_greedy = kind <> "선택" && List.for_all (fun t -> List.mem t greedy) toks;
|
||||
}
|
||||
:: !out
|
||||
in
|
||||
let rec walk r expr (cont : SS.t) (cont_end : bool) =
|
||||
let cont_full =
|
||||
if cont_end then SS.union cont (match Hashtbl.find_opt fol r.name with Some s -> s | None -> SS.empty)
|
||||
else cont
|
||||
in
|
||||
match expr with
|
||||
| Term _ | Ref _ | RefArg _ -> ()
|
||||
| Except (x, _) -> walk r x cont cont_end
|
||||
| Alt xs ->
|
||||
let n = List.length xs in
|
||||
for i = 0 to n - 1 do
|
||||
for j = i + 1 to n - 1 do
|
||||
let fi = first_expr a (List.nth xs i) and fj = first_expr a (List.nth xs j) in
|
||||
let inter = SS.inter fi fj in
|
||||
if not (SS.is_empty inter) then
|
||||
add r "선택" (SS.elements inter)
|
||||
(Printf.sprintf "%d번째와 %d번째 대안이 같은 토큰으로 시작합니다: %s / %s"
|
||||
(i + 1) (j + 1)
|
||||
(show_expr (List.nth xs i))
|
||||
(show_expr (List.nth xs j)))
|
||||
done
|
||||
done;
|
||||
let nulls = List.filter (nullable_expr a) xs in
|
||||
if List.length nulls > 1 then
|
||||
add r "선택" [ "(빈 것)" ] "비어도 되는 대안이 둘 이상입니다";
|
||||
List.iter (fun x -> walk r x cont cont_end) xs
|
||||
| Opt x ->
|
||||
let inter = SS.inter (first_expr a x) cont_full in
|
||||
if not (SS.is_empty inter) then
|
||||
add r "선택적" (SS.elements inter)
|
||||
(Printf.sprintf "[ %s ]를 넣을지 말지가 다음 토큰으로 갈리지 않습니다" (show_expr x));
|
||||
walk r x cont cont_end
|
||||
| Rep x ->
|
||||
let inter = SS.inter (first_expr a x) cont_full in
|
||||
if not (SS.is_empty inter) then
|
||||
add r "반복" (SS.elements inter)
|
||||
(Printf.sprintf "{ %s }를 더 돌지 말지가 다음 토큰으로 갈리지 않습니다" (show_expr x));
|
||||
walk r x (SS.union cont (first_expr a x)) cont_end
|
||||
| Seq xs ->
|
||||
let acc_first = ref cont and acc_end = ref cont_end in
|
||||
List.iter
|
||||
(fun x ->
|
||||
walk r x !acc_first !acc_end;
|
||||
let f = first_expr a x in
|
||||
if nullable_expr a x then acc_first := SS.union f !acc_first
|
||||
else (
|
||||
acc_first := f;
|
||||
acc_end := false))
|
||||
(List.rev xs)
|
||||
in
|
||||
List.iter (fun r -> walk r r.body SS.empty true) g;
|
||||
List.rev !out
|
||||
@@ -0,0 +1,58 @@
|
||||
(* 문법 문서의 어휘 절을 코드에서 생성한다.
|
||||
|
||||
키워드 표와 "줄을 끝낼 수 있는 토큰" 목록은 지금까지 token.ml과
|
||||
grammar.ebnf 양쪽에 손으로 적혀 있었다. 그런 목록은 어긋난다 —
|
||||
실제로 이 프로젝트의 문법 문서 전체가 그렇게 어긋났다.
|
||||
|
||||
여기서 생성하고 테스트가 대조하므로, 이제 토큰을 추가하면 문서가 낡거나
|
||||
빌드가 깨진다. 사람이 두 곳을 맞출 의무가 없다. *)
|
||||
|
||||
let display (k : Token.kind) =
|
||||
match k with
|
||||
| Token.Ident _ -> Some "ident"
|
||||
| Token.Int _ -> Some "int_lit"
|
||||
| Token.Str _ -> Some "string_lit"
|
||||
| Token.Newline | Token.Eof -> None
|
||||
| _ -> Some ("\"" ^ Token.show_kind k ^ "\"")
|
||||
|
||||
let is_keyword (k : Token.kind) = Token.keyword (Token.show_kind k) = Some k
|
||||
|
||||
let keywords () =
|
||||
List.filter_map
|
||||
(fun k -> if is_keyword k then Some ("\"" ^ Token.show_kind k ^ "\"") else None)
|
||||
Token.all_kinds
|
||||
|
||||
let statement_enders () =
|
||||
List.filter_map
|
||||
(fun k -> if Token.can_end_statement k then display k else None)
|
||||
Token.all_kinds
|
||||
|
||||
let begin_mark = "(* 여기부터 lib/token.ml에서 생성됩니다 — 손으로 고치지 마십시오 *)"
|
||||
let end_mark = "(* 생성 끝 *)"
|
||||
|
||||
(* 한 줄이 길어지지 않게 접는다. 구분자는 줄 끝에 남겨 이어짐이 보이게 한다 *)
|
||||
let wrap ~indent items =
|
||||
let rec go acc line = function
|
||||
| [] -> List.rev (line :: acc)
|
||||
| x :: rest ->
|
||||
if line = indent then go acc (line ^ x) rest
|
||||
else if String.length line + String.length x + 3 > 72 then
|
||||
go ((line ^ " |") :: acc) (indent ^ x) rest
|
||||
else go acc (line ^ " | " ^ x) rest
|
||||
in
|
||||
String.concat "\n" (go [] indent items)
|
||||
|
||||
let render () =
|
||||
String.concat "\n"
|
||||
[
|
||||
begin_mark;
|
||||
" * 줄을 끝낼 수 있는 토큰. 줄의 마지막 토큰이 이 중 하나이면 그 줄 끝에";
|
||||
" * NEWLINE이 삽입된다. Token.can_end_statement가 원본이다.";
|
||||
" *";
|
||||
wrap ~indent:" * " (statement_enders ());
|
||||
" *";
|
||||
" * 키워드. 이름으로 쓸 수 없다. Token.keyword가 원본이다.";
|
||||
" *";
|
||||
wrap ~indent:" * " (keywords ());
|
||||
" " ^ end_mark;
|
||||
]
|
||||
@@ -152,6 +152,73 @@ let show_kind = function
|
||||
let show { kind; pos } =
|
||||
Printf.sprintf "%d:%d %s" pos.line pos.col (show_kind kind)
|
||||
|
||||
(* 모든 토큰 종류를 한 번씩 잇는 사슬. 아래 match가 전체 나열이므로 토큰을
|
||||
추가하면 컴파일러가 여기를 지적한다 — 목록이 조용히 낡지 않는다.
|
||||
문법 문서의 어휘 절이 이 나열에서 생성된다. *)
|
||||
let next_kind = function
|
||||
| Ident _ -> Some (Int "")
|
||||
| Int _ -> Some (Str "")
|
||||
| Str _ -> Some Kw_pub
|
||||
| Kw_pub -> Some Kw_fn
|
||||
| Kw_fn -> Some Kw_struct
|
||||
| Kw_struct -> Some Kw_enum
|
||||
| Kw_enum -> Some Kw_capability
|
||||
| Kw_capability -> Some Kw_const
|
||||
| Kw_const -> Some Kw_import
|
||||
| Kw_import -> Some Kw_as
|
||||
| Kw_as -> Some Kw_reexport
|
||||
| Kw_reexport -> Some Kw_let
|
||||
| Kw_let -> Some Kw_mut
|
||||
| Kw_mut -> Some Kw_own
|
||||
| Kw_own -> Some Kw_affine
|
||||
| Kw_affine -> Some Kw_copyable
|
||||
| Kw_copyable -> Some Kw_effects
|
||||
| Kw_effects -> Some Kw_return
|
||||
| Kw_return -> Some Kw_if
|
||||
| Kw_if -> Some Kw_else
|
||||
| Kw_else -> Some Kw_match
|
||||
| Kw_match -> Some Kw_scope
|
||||
| Kw_scope -> Some Kw_true
|
||||
| Kw_true -> Some Kw_false
|
||||
| Kw_false -> Some LParen
|
||||
| LParen -> Some RParen
|
||||
| RParen -> Some LBrace
|
||||
| LBrace -> Some RBrace
|
||||
| RBrace -> Some LBracket
|
||||
| LBracket -> Some RBracket
|
||||
| RBracket -> Some Comma
|
||||
| Comma -> Some Colon
|
||||
| Colon -> Some Dot
|
||||
| Dot -> Some Arrow
|
||||
| Arrow -> Some FatArrow
|
||||
| FatArrow -> Some Question
|
||||
| Question -> Some Underscore
|
||||
| Underscore -> Some Eq
|
||||
| Eq -> Some EqEq
|
||||
| EqEq -> Some Bang
|
||||
| Bang -> Some BangEq
|
||||
| BangEq -> Some Lt
|
||||
| Lt -> Some Le
|
||||
| Le -> Some Gt
|
||||
| Gt -> Some Ge
|
||||
| Ge -> Some Plus
|
||||
| Plus -> Some Minus
|
||||
| Minus -> Some Star
|
||||
| Star -> Some Slash
|
||||
| Slash -> Some Percent
|
||||
| Percent -> Some AmpAmp
|
||||
| AmpAmp -> Some PipePipe
|
||||
| PipePipe -> Some Pipe
|
||||
| Pipe -> Some Newline
|
||||
| Newline -> Some Eof
|
||||
| Eof -> None
|
||||
|
||||
let all_kinds =
|
||||
let rec go k acc =
|
||||
match next_kind k with None -> List.rev (k :: acc) | Some n -> go n (k :: acc)
|
||||
in
|
||||
go (Ident "") []
|
||||
|
||||
(* 줄 끝에서 문 구분자를 삽입할지 결정한다 (grammar.ebnf 어휘 절).
|
||||
값으로 끝날 수 있는 토큰 뒤에서만 삽입하므로, 연산자나 여는 괄호로
|
||||
끝나는 줄은 다음 줄로 이어진다. *)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
(deps
|
||||
(glob_files %{workspace_root}/samples/*.cool)
|
||||
(glob_files %{workspace_root}/std/*.cool)
|
||||
(glob_files %{workspace_root}/docs/*.ebnf)
|
||||
(glob_files %{workspace_root}/samples/app/*)
|
||||
(glob_files %{workspace_root}/samples/modules/*.cool)
|
||||
(glob_files %{workspace_root}/samples/run/*.cool)))
|
||||
|
||||
@@ -1306,3 +1306,72 @@ let () =
|
||||
(Printf.sprintf "런타임 구현 %s에 std 선언이 있다" name)
|
||||
(List.mem name declared))
|
||||
Interp.implemented
|
||||
|
||||
(* ------------------------------------------------------------------ *)
|
||||
(* 문법 파일 *)
|
||||
(* *)
|
||||
(* docs/grammar.ebnf는 이제 문서가 아니라 기계가 읽는 소스다. 여기서 *)
|
||||
(* 검사하는 것 셋: *)
|
||||
(* 1. 기계가 읽을 수 있는가 *)
|
||||
(* 2. 정의되지 않은 이름이 토큰 부류뿐인가 *)
|
||||
(* 3. LL(1)인가 — 문법 첫머리의 주장이 여기서 검증된다 *)
|
||||
(* ------------------------------------------------------------------ *)
|
||||
|
||||
let () =
|
||||
let src =
|
||||
let ic = open_in_bin "../docs/grammar.ebnf" in
|
||||
let n = in_channel_length ic in
|
||||
let s = really_input_string ic n in
|
||||
close_in ic;
|
||||
s
|
||||
in
|
||||
match Ebnf.parse_result src with
|
||||
| Error e ->
|
||||
Printf.printf " (문법 파일 %d행: %s)\n" e.line e.msg;
|
||||
check "grammar.ebnf를 읽을 수 있다" false
|
||||
| Ok g ->
|
||||
check "grammar.ebnf를 읽을 수 있다" true;
|
||||
check "프로덕션이 충분히 있다" (List.length g > 50);
|
||||
(* 어휘 층의 이름만 정의 없이 참조될 수 있다 *)
|
||||
let allowed = [ "NEWLINE"; "char"; "digit"; "letter" ] in
|
||||
let undef = Ebnf.undefined g in
|
||||
List.iter
|
||||
(fun n ->
|
||||
check
|
||||
(Printf.sprintf "grammar.ebnf: %s는 정의되었거나 토큰 부류다" n)
|
||||
(List.mem n allowed))
|
||||
undef;
|
||||
check "grammar.ebnf에 죽은 프로덕션이 없다"
|
||||
(Ebnf.unreachable g ~start:"module" = []);
|
||||
let g = Ebnf.expand g in
|
||||
let tokens = allowed @ [ "ident"; "int_lit"; "string_lit" ] in
|
||||
let real =
|
||||
List.filter
|
||||
(fun (c : Ebnf.conflict) -> not c.c_greedy)
|
||||
(Ebnf.conflicts ~tokens ~greedy:[ "NEWLINE" ] g)
|
||||
in
|
||||
List.iter
|
||||
(fun (c : Ebnf.conflict) ->
|
||||
Printf.printf " (LL(1) 충돌 %s:%d [%s] %s — %s)\n" c.c_rule c.c_line
|
||||
c.c_kind
|
||||
(String.concat " " c.c_tokens)
|
||||
c.c_detail)
|
||||
real;
|
||||
check "grammar.ebnf는 LL(1)이다" (real = [])
|
||||
|
||||
(* 문법 문서의 어휘 절은 코드에서 생성된다. 두 곳에 손으로 적힌 목록은
|
||||
어긋난다 — 이 프로젝트가 그것으로 한 번 데었다. *)
|
||||
let () =
|
||||
let src =
|
||||
let ic = open_in_bin "../docs/grammar.ebnf" in
|
||||
let n = in_channel_length ic in
|
||||
let s = really_input_string ic n in
|
||||
close_in ic;
|
||||
s
|
||||
in
|
||||
let block = Lexical_doc.render () in
|
||||
check "문법 문서의 어휘 절이 token.ml과 일치한다" (has_sub src block);
|
||||
if not (has_sub src block) then begin
|
||||
print_endline " 현재 코드가 만드는 블록:";
|
||||
print_endline block
|
||||
end
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
(executable
|
||||
(name ebnf_tool)
|
||||
(libraries coollang))
|
||||
@@ -0,0 +1,76 @@
|
||||
(* 문법 파일을 읽어 기계가 소비할 수 있는지 확인하는 도구. *)
|
||||
let read file =
|
||||
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;
|
||||
s
|
||||
|
||||
let () =
|
||||
if Array.length Sys.argv > 1 && Sys.argv.(1) = "--lexical" then (
|
||||
print_string (Coollang.Lexical_doc.render ());
|
||||
print_newline ();
|
||||
exit 0);
|
||||
let file = if Array.length Sys.argv > 1 then Sys.argv.(1) else "docs/grammar.ebnf" in
|
||||
match Coollang.Ebnf.parse_result (read file) with
|
||||
| Error e -> Printf.printf "%s:%d: %s\n" file e.line e.msg
|
||||
| Ok g ->
|
||||
Printf.printf "프로덕션 %d개\n" (List.length g);
|
||||
Printf.printf "\n정의되지 않은 채 참조된 이름:\n";
|
||||
List.iter (fun n -> Printf.printf " %s\n" n) (Coollang.Ebnf.undefined g);
|
||||
Printf.printf "\n어디서도 참조되지 않는 프로덕션 (시작 기호 module 제외):\n";
|
||||
List.iter
|
||||
(fun n -> Printf.printf " %s\n" n)
|
||||
(Coollang.Ebnf.unreachable g ~start:"module");
|
||||
(* 문법이 쓰는 단말 전부. 렉서가 만드는 토큰과 대조하기 위한 것. *)
|
||||
let terms = Hashtbl.create 64 in
|
||||
let rec walk : Coollang.Ebnf.expr -> unit = function
|
||||
| Term s -> Hashtbl.replace terms s ()
|
||||
| Ref _ | RefArg _ -> ()
|
||||
| Seq xs | Alt xs -> List.iter walk xs
|
||||
| Opt e | Rep e -> walk e
|
||||
| Except (a, b) -> walk a; walk b
|
||||
in
|
||||
List.iter (fun (r : Coollang.Ebnf.rule) -> walk r.body) g;
|
||||
let ts = Hashtbl.fold (fun k () acc -> k :: acc) terms [] |> List.sort compare in
|
||||
Printf.printf "\n문법이 쓰는 단말 %d개:\n %s\n" (List.length ts)
|
||||
(String.concat " " ts);
|
||||
(* 어휘 절의 이름은 파서 층에서 단말이다 *)
|
||||
let tokens =
|
||||
[ "ident"; "int_lit"; "string_lit"; "NEWLINE"; "letter"; "digit"; "char" ]
|
||||
in
|
||||
let g = Coollang.Ebnf.expand g in
|
||||
let a = Coollang.Ebnf.analyze ~tokens g in
|
||||
Printf.printf "\n비어도 되는(nullable) 프로덕션:\n %s\n"
|
||||
(String.concat " "
|
||||
(List.filter_map
|
||||
(fun (r : Coollang.Ebnf.rule) ->
|
||||
if Coollang.Ebnf.nullable a r.name then Some r.name else None)
|
||||
g));
|
||||
Printf.printf "\nFIRST 표본:\n";
|
||||
List.iter
|
||||
(fun n ->
|
||||
Printf.printf " %-14s %s\n" n
|
||||
(String.concat " "
|
||||
(Coollang.Ebnf.SS.elements (Coollang.Ebnf.first a n))))
|
||||
[ "decl"; "stmt"; "primary"; "type"; "pattern"; "item" ];
|
||||
let cs = Coollang.Ebnf.conflicts ~tokens ~greedy:[ "NEWLINE" ] g in
|
||||
let real = List.filter (fun (c : Coollang.Ebnf.conflict) -> not c.c_greedy) cs in
|
||||
let soft = List.filter (fun (c : Coollang.Ebnf.conflict) -> c.c_greedy) cs in
|
||||
Printf.printf "\n== LL(1) 충돌: 진짜 %d건, greedy로 해소 %d건 ==\n"
|
||||
(List.length real) (List.length soft);
|
||||
List.iter
|
||||
(fun (c : Coollang.Ebnf.conflict) ->
|
||||
Printf.printf "\n%s (%s:%d) [%s]\n 겹치는 토큰: %s\n %s\n" c.c_rule file
|
||||
c.c_line c.c_kind
|
||||
(String.concat " " c.c_tokens)
|
||||
c.c_detail)
|
||||
real;
|
||||
if soft <> [] then begin
|
||||
Printf.printf "\n-- greedy로 해소되는 것 --\n";
|
||||
List.iter
|
||||
(fun (c : Coollang.Ebnf.conflict) ->
|
||||
Printf.printf " %s:%d %s [%s]\n" file c.c_line c.c_rule
|
||||
(String.concat " " c.c_tokens))
|
||||
soft
|
||||
end
|
||||
Reference in New Issue
Block a user