100 Commits
Author SHA1 Message Date
coolguy b4f947b643 audit: 프런트엔드 빈틈 열하나와 진법 리터럴
전부 구현 쪽이었다. SPEC 은 §6.2(체이닝·단항 뒤 as), §5 R9(asm), §6.1·§7.3
(extern, 빈 enum/error)을 이미 옳게 적고 있었고 구현만 따라가지 않았다.

  const A: i32 = r();        전역 초기값에 호출. lowering 이 조용히 버리고 0
  static A: i32 = r();       같은 것을 저장소 0 으로
  true == false == true      비교 체이닝
  -x as u32                  괄호 없이 단항 뒤 as
  asm { }                    unsafe 밖에서
  extern fn f();             ABI 문자열 없이
  extern "stdcall" fn f();   c 아닌 ABI
  extern "c" fn f() { }      extern 에 본문
  fn f() -> i32;             extern 아닌데 본문 없음
  enum E { }  error E { }    빈 선언

FRONT-01/02 는 SPEC 에도 규칙이 없었다. §7.1 에 넣었다 -- 전역의 바이트는
이미지에 들어가므로 초기값이 실행될 순간이 없다. 리터럴과 다른 const, 배리언트,
error.Name, 그리고 그것들에 대한 연산까지가 허용된다.

-x as T 와 비교 체이닝을 잡으려면 괄호가 트리에 남아야 해서 FE_NODE_PAREN 을
두었다. 파싱 뒤에는 -x as T 와 -(x as T) 가 같은 트리다.

그리고 0b1010 이 0, 0o17 이 0 이었다. 10진으로 읽다가 b 에서 멈춰 0 을 내는데
0 도 숫자라 아무도 눈치채지 못한다. 값 계산 두 군데를 고쳤다.

262/262, 40/40.
2026-08-17 17:00:29 +09:00
coolguy c7a1b98654 audit: 프런트엔드 빈틈 조사를 기록한다
parser, checker, 전역 lowering 의 경계에서 11 건. 기준 커밋 6dc298d.
2026-08-17 16:52:30 +09:00
coolguy 730bcac282 audit: SPEC-파서 괴리 일곱을 정리한다
구현 셋, SPEC 다섯. 어느 쪽이 틀렸는지는 항목마다 따로 판정했다.

구현:
- ~ 를 넣었다. ^ 는 xor 과 .^ 가 가져가서 비트 NOT 이 자기 철자를 못 갖고
  있었다. 렉서·파서·검사·lowering(전부 1 과의 xor).
- 전역 static/var 는 타입을 적는다. 다른 유닛이 읽는 링커 심볼이라 초기값의
  생김새에 타입을 맡기면 그쪽이 보는 것이 달라진다. const 는 그대로 추론한다.
- error code 는 정수 리터럴 하나다. 식이면 중복도 예약된 0 도 검사할 수 없다.

SPEC:
- 최상위 comptime if 를 뺐다. comptime 조건은 타입 술어뿐인데(§7.5) 유닛
  바깥에는 바인딩된 타입 파라미터가 없어 물어볼 것이 없다. §11 v0.2.
- 타입 이름은 [binding.]Name 이다. import 가 마지막 segment 를 바인딩하므로
  점 둘 이상은 만들어질 수 없는데 문법이 unit_path 를 쓰고 있었다.
- catch 의 EBNF 가 §4.6 보다 넓었다. 값을 주는 짧은 형태와 에러를 받는 블록
  형태 둘로 나눠 적었다.
- | 와 ^ 를 한 단계로 둔 것을 쪼갰다. 합치면 a | b ^ c 가 좌결합으로
  (a|b)^c 가 되어 C 에서 온 사람을 속인다. 구현이 C 순서로 옳았다.
- 마지막 필드 쉼표 생략을 명세에 적었다. enum 은 이미 허용하고 있었다.

그리고 tests/run.py 가 마커를 진단 스트림에만 맞춘다. --dump-ast 모드에서는
AST 덤프가 stdout 으로 먼저 나와서 parse/ fixture 는 마커를 쓸 수 없었다.

249/249, 39/39.
2026-08-17 16:52:12 +09:00
coolguy 6dc298d828 docs: 문서 하나가 질문 하나에 답하게
GOAL.md 는 계획일 때 값어치가 있었는데 완료 보고로 바꾸는 순간 git log 의
중복이 됐다. 끝난 계획은 문서가 아니라 히스토리다. 내용은 이미 TODO 와 SPEC
에 들어갔으니 지운다.

fixture-report.md 도 지운다. 기준선이 150/188 인 일회성 조사 스냅샷이고
지금은 245/245 다. 필요하면 2f140e1 에 있다.

TODO 의 '정해진 것' 이 두 종류를 섞고 있었다. 언어 규칙은 SPEC 문장을 옮겨
적은 것이라 한쪽만 고치면 갈라지고, 구현 결정은 SPEC 에 없어서 여기가 유일한
출처다. 둘로 쪼갰다 -- 앞의 표는 §번호만 담고, 뒤의 표는 내용과 그것이 사는
파일을 담는다.

SPEC 의 §7.9 를 §7.7 로 옮겼다. 7.7 과 7.8 없이 7.9 가 떠 있었다.

1847 → 1173 줄. 245/245, 38/38.
2026-08-17 16:40:50 +09:00
coolguy 52aaff62e4 docs: TODO 를 지금 상태로
셀프호스팅 목록을 다시 매겼다. 다음은 리졸버를 Ferro 로이고 도구는 다 있다:
intern, map, Node.bind, Map.clear.

정해진 것에 셋을 더했다: 정수 리터럴의 타입, store 폭은 값이 아니라 자리가
정한다는 것, std 밖 unsafe 예산이 0 이며 run.py 가 검사한다는 것.

남은 구멍에 둘: ?^T 의 자동 해제가 아직 없고, 컨테이너 두 원소의 동시 &mut
는 인덱스가 갈라지지 않아 stdlib 안에서 푼다.

245/245, 38/38.
2026-08-17 16:34:15 +09:00
coolguy 3d226d890b docs: GOAL 을 결과로, TODO 를 지금 상태로
P0~P4 가 끝났다. GOAL.md 는 계획이 아니라 무엇이 나왔는지를 적는다 --
특히 각 항목이 어떤 fixture 로 고정됐는지.

TODO 의 셀프호스팅 목록을 다시 매겼다. 다음은 리졸버를 Ferro 로이고,
도구는 다 있다: intern, map, Node.bind, Map.clear.

정해진 것에 셋을 더했다: 정수 리터럴의 타입, store 폭은 자리가 정한다는 것,
그리고 std 밖 unsafe 예산이 0 이며 run.py 가 그것을 검사한다는 것.

245/245, 38/38.
2026-08-17 16:33:25 +09:00
coolguy f06a12f341 GOAL P4: --report-unsafe 와 --report-instances, 그리고 예산을 CI 에
'ffec 에서 unsafe 가 몇 군데인가' 는 좋은 지표인데 세는 방법이 없으면 지표가
아니다. 이제 센다.

  unit                   unsafe       *T  unchecked
  std.io                      6        1          0
  std.sys                    10       12          0
  total                      16       13          0
  outside std                 0        0          0

Ferro 렉서와 파서, interner, 아레나, 맵을 쓰는 프로그램 전부가 std 바깥에서
0 이다. 목표치를 이미 지키고 있었던 셈인데, 그것을 아무도 확인할 수 없었다.

run.py 가 그 숫자를 검사한다. std.mem 과 std.sys 밖의 unsafe 와 *T 는 검사기가
약속한 것에 뚫린 구멍이므로 0 을 유지해야 하고, 늘어나면 알아채는 것이 아니라
빌드가 실패해야 한다. unsafe 블록 하나를 넣어 실패하는 것까지 확인했다.

--report-instances 는 제네릭이 무엇이 됐는지 센다. interns.fe 는 20 인스턴스,
타입 4 개에 저장소 80 바이트, 메서드 16 개다.

245/245, 38/38.
2026-08-17 16:31:57 +09:00
coolguy b0cc737c6b GOAL P3-5: StrId 를 키로 -- 별도 IntMap 은 필요 없다
std.map 은 바이트 열을 키로 받는다. 이름의 번호를 네 바이트로 써 내려놓으면
그대로 심볼 표가 된다. 감사가 권한 IntMap(V) 를 따로 만들 이유가 없고, 그
쪽이 trait 없는 v0.1 과도 덜 싸운다.

intern.key_of 가 그 네 바이트를 써준다. 리졸버가 스코프마다 할 일이라
손으로 풀게 두지 않았다.

  scope x 10 y 20 of 2

245/245, 38/38.
2026-08-17 16:28:47 +09:00
coolguy b7ce16f65e GOAL P3-4: StringInterner, 그리고 그것이 드러낸 배치 버그
이름 하나당 사본 하나와 그것을 대신하는 숫자. 컴파일러는 이름을 끊임없이
비교하고 사방에 저장하는데, StrId 둘을 비교하는 것은 정수 둘을 비교하는
것이고 하나를 저장하는 것은 4바이트에 소유권 없음이다.

str 을 꺼내는 API 를 일부러 두지 않았다. 텍스트를 빌리는 것은 interner 를
빌리는 것인데, interner 는 이름을 든 채로 계속 더 넣고 싶은 바로 그 물건이다
-- 파서는 식별자를 읽으면서 같은 숨에 다음 것을 등록한다. 텍스트를 열어서
하려던 일은 전부 여기 있다: eq, len_of, hash_of, find, copy_into.

그리고 이것이 제네릭 인스턴스를 필드로 담는 구조체를 통째로 깨뜨리던 버그를
드러냈다.

  Holder{ bytes: ^[]mut u8, used: usize, seen: map.Map(u32) }
  36 바이트여야 하는데 12 로 잡혔다.

Map(u32) 를 짓는 중에 그 안의 Slot(u32) 를 인스턴스화하면 거기서 배치 패스가
다시 돈다. 그때 Map(u32) 는 field_count 는 4 인데 필드 배열이 아직 아무것도
말하지 않는 상태라, 크기 0 으로 확정되고 굳었다. 이미 크기가 있는 타입은
아무도 다시 계산하지 않으니 Holder 는 그 0 을 읽었다.

셋을 고쳤다: 짓는 중인 인스턴스는 building 을 세워 배치를 거절하고, 멤버가
아직 자리를 못 잡은 집합 타입은 틀린 답으로 굳느니 물러나며, 배치 패스는
움직임이 없을 때까지 돈다.

245/245, 38/38.
2026-08-17 16:27:47 +09:00
coolguy 63baa4f523 GOAL P3-3: List 에 pop take swap slice slice_mut clear
컴파일러가 실제로 쓰는 나머지 표면이다. take 는 R7 대로 대체값을 남기고
꺼내므로 리스트에 구멍이 생기지 않는다.

slice() 를 쓰려면 언어가 한 걸음 필요했다. &Self 로 읽어도 필드가 ^[]mut T
이니 슬라이스가 []mut T 로 나오는데, 선언한 반환은 []T 다. 호출 인자 자리의
약화만 있고 반환 자리에는 없었다.

반환 위치의 약화를 허용했다. R8 이 이미 그 파생을 허용한 뒤라면 []mut T 를
[]T 로 넘기는 것은 가진 것보다 적게 넘기는 일이라 새 별칭을 만들지 않는다.
&Self 메서드가 자기가 소유한 것의 읽기 전용 뷰를 내주는 길이 이것뿐이다.
SPEC §4.2 에 적었고, let 은 여전히 안 된다는 것을 badletwk 가 고정한다.

243/243, 37/37.
2026-08-17 16:22:11 +09:00
coolguy b255396850 GOAL P3-1/3-2: 핸들로 닿는 아레나
R11 이 데이터가 데이터를 가리킬 때 내놓는 답이다. 아레나가 값을 소유하고
핸들은 숫자라서 참조가 아니고, R4 가 반대할 것이 없다. mem.Arena 옆에 두되
다른 자료구조다 -- 저쪽은 크기가 제각각인 것을 오프셋으로 나눠주고, 이쪽은
슬롯마다 고정된 T 를 담고 슬롯을 되받는다.

핸들은 믿는 것이 아니라 검사받는다. 슬롯의 세대, 아레나의 epoch, 어느
아레나에서 왔는지를 8바이트에 담아서, 놓아준 뒤에 쓰거나 reset 뒤에 쓰거나
다른 아레나에 물어보면 옆값이 아니라 null 이 나온다. 여덟 바이트는 빌드마다
같다 -- --no-checks 는 비교를 건너뛸 뿐 배치를 바꾸지 않는다.

세대가 다 닳은 슬롯은 재사용 목록에 넣지 않고 버린다. 한 바퀴 돌면 옛 핸들이
다시 유효해지는데, 그것이 세대가 막으려던 바로 그 일이다.

get 은 사본을 돌려준다. 대여가 문장을 넘기지 않는 이유가 그것이고, 그래서
한 슬롯을 읽으면서 다른 슬롯에 쓸 수 있다. get_mut 은 두지 않았다 -- 아레나
하나를 통째로 잠그는 참조를 오래 들고 있게 하는 API 다.

길에서 고친 것: 메서드 호출이 시그니처를 호출자 유닛에서 풀고 있었다. 그래서
Arena(T) 안의 Handle(T) 를 부르는 쪽 유닛에서 찾다가 실패했다. 필드 타입에
쓰던 enter_declaring_unit 을 method_type 에도 물렸다.

241/241, 36/36.
2026-08-17 16:19:30 +09:00
coolguy ef7939f609 GOAL P2: SPEC 에서 죽은 C 백엔드를 걷어낸다
파이프라인은 .fe → i386 asm → wasm → wlink → .exe 인데 명세는 아직 C 를
방출하는 컴파일러를 서술하고 있었다. 외부 감사가 그 문서를 충실히 읽고
존재하지 않는 문제(C 의 부호 있는 오버플로 UB)를 보고했다 -- 명세가 거짓말을
하면 그것을 읽는 사람이 틀린 답을 낸다.

걷어낸 것: .fei 심볼 파일과 그 위에 얹힌 증분 빌드 서술, fe_errors.h,
--emit-c 와 --error-table, '호스트 C 방출', 'C 방출 시 static inline',
'별도 C 표현'.

오류 코드 절은 실제대로 다시 썼다: 빌드 하나가 모든 유닛의 소스를 함께 읽고,
드라이버가 emit 전에 쓰인 이름을 모아 철자순으로 1부터 매긴다. 유닛 하나만
따로 코드 생성까지 밀고 갈 수 없다는 것도 그 결과로 적었다.

R7 이 컴파일러 소스 파일 이름(own.c)을 대고 있던 것도 언어의 말로 바꿨고,
이동은 변수 단위이고 대여는 place 단위라는 구분을 붙였다.

--target= 과 --model= 은 드라이버에서 없앴다. 타깃이 하나인데 받아들여서
무시하는 플래그는 안 받는 것보다 나쁘다.

SPEC 이 약속만 하고 구현이 없는 것 셋을 TODO 에 적었다: --strip-error-names,
fmt.fmt_error, 0b/0o 리터럴 값 계산.

240/240, 35/35.
2026-08-17 16:12:53 +09:00
coolguy d9bced830c GOAL P1-4: 작은 규칙 일곱을 정하고, 어긋난 둘을 고친다
일곱 중 다섯은 구현이 이미 옳게 답하고 있었다 -- match 는 enum 전용이고,
enum payload 에 소유 타입을 담을 수 있고, undefined 배열은 원소 단위로
추적하지 않고, 다른 유닛에서 private 필드가 있는 리터럴은 거부되고,
by-value self 의 부분 이동도 mem.replace 가 필요하다. SPEC §7.9 에 적었다.

나머지 둘은 그냥 통과하고 있었다.

defer { return 1; } 이 받아들여졌다. 지연 블록은 함수가 무엇을 반환할지 이미
정한 뒤 스코프 정리 중에 도는데 거기서 return 이 뜻할 것이 없다.

for x in xs { xs[0] = 9; } 도 받아들여졌다. x 가 xs 안을 가리키는 참조이니
순회 몸통에서 xs 에 쓰는 것은 그 참조가 가리키는 것을 옮기는 일이다 (R6).
순회는 이제 도는 동안 대여한다. 읽기는 공유 순회에서 그대로 된다.

240/240, 35/35.
2026-08-17 16:10:44 +09:00
coolguy 1a368dc13f GOAL P1-1..1-3: 리터럴이 자기 타입에 안 맞으면 거부한다
그리고 그 자리를 파다가 더 나쁜 것이 나왔다.

store 의 폭이 목적지가 아니라 값에서 왔다. 정수 리터럴은 더 좁은 것이
요구하기 전까지 i32 이므로 let b: u8 = 200; 은 4바이트가 1바이트 자리로
가는 것으로 도착하고, 4바이트를 쓰면 프레임이 그 옆에 놓은 것을 지운다.

  let a: i32 = 5;  let b: u8 = 300;  let d: u8 = 44;
  a 0 / b 0 / d 44        →   a 5 / b 44 / d 44

폭 넓은 지역 하나만 있으면 드러나지 않아서 여태 살아 있었다. exec/narrow.fe
가 폭이 섞인 지역을 나란히 두어 고정한다.

규칙 자체는 SPEC §3 에 넣었다: 리터럴의 타입은 문맥이 요구하는 정수 타입이고,
없으면 i32 다. 범위를 벗어나면 잘리는 것이 아니라 거부된다. 앞의 단항 -
는 리터럴의 일부로 보아 i8 = -128 은 되고 u8 = -1 은 안 된다.

같이 넣은 문장 둘:
- §9 미사용 타입 파라미터는 정상이다. typed handle 이 그 모양이고 구현은
  이미 그렇게 동작했다.
- §7.4 --no-checks 에서 오버플로는 랩어라운드로 정의된다. 타깃이 실제로
  하는 일이고 미정의로 두지 않는다.

237/237, 35/35.
2026-08-17 16:07:45 +09:00
coolguy 32da64d7c1 GOAL P0-2: Name(args){...} 로 제네릭 인스턴스를 짓는다
Name{...} 과 binding.Name{...} 만 있고 호출 뒤의 { 를 아무도 받지 않았다.
그래서 타입 인자를 명시한 리터럴이 파싱되지 않았고, 제네릭의 인스턴스는
Self{...} 나 생성자 함수로만 만들 수 있었다.

파서는 호출 뒤의 { 를 struct 리터럴로 받고, 체커는 그것을 타입 표기와 똑같은
resolver 에 넘긴다 -- 같은 철자니 같은 답이어야 한다. { 의 애매함은 이미
Name{...} 에 있던 것과 같고 같은 guard 가 정리한다.

  hold.Cell(i32){ v: 7 }        다른 유닛의 제네릭
  hold.Handle(Node){ raw: 3 }   본문에서 T 를 안 쓰는 것
  Boxed(i32){ v: 9 }            이 유닛의 제네릭

미사용 타입 파라미터는 그대로 둔다. typed handle 이 바로 그 모양이고,
Handle(Node) 와 Handle(Kind) 가 실제로 다른 타입이라는 것은 badphant 가
거부로 고정한다.

233/233, 34/34.
2026-08-17 15:59:08 +09:00
coolguy dacf1e1b1b GOAL P0-1: 니치 옵셔널이 포인터 대신 포인터가 든 자리를 넘겼다
?T 의 페이로드가 null 이 될 수 없으면 태그를 따로 두지 않고 그 불가능한 값을
null 로 쓴다. ?^T 와 ?&T 가 그렇다. 그런데 if let 이 그것을 풀 때 두 경우를
한 갈래로 처리하고 있었다.

바인딩이 참조인 이유가 둘이다. 페이로드가 값이면 바인딩은 그것이 래퍼 안에
앉은 자리를 가리켜야 하고(주소), 페이로드가 이미 포인터면 바인딩은 그
포인터여야 한다(값). 후자에 주소를 쓰면 포인터의 포인터가 되고, 프로그램은
값이 있어야 할 자리에서 주소를 읽는다. 컴파일도 되고 실행도 됐다.

  ?i32   5          (맞았음 -- 태그가 있어서 다른 길로 갔다)
  ?^i32  6125480 → 5
  ?&i32  6125496 → 5

그리고 옵셔널을 null 과 비교하는 것이 lowering 되지 않았다 -- 래퍼 전체를
값으로 읽으려 해서 'cannot lower an aggregate as a value' 였다. 태그만 보면
되는 질문이다. optional/oknull.fe 가 검사만 하는 fixture 라 드러나지 않았다.

exec/optref.fe 가 세 모양을 전부 고정한다: if let, orelse, .?, == null,
그리고 R7 관용구인 mem.replace(&mut box, null).? 로 소유자를 꺼내 놓는 것까지.

229/229, 33/33.
2026-08-17 15:56:48 +09:00
coolguy 51f555a830 리졸버를 위한 자리: Node.bind 와 Map.clear
ast.Node 가 이름이 무엇으로 해석됐는지 들고, Map 이 저장소를 유지한 채 키만
잊는다. 스코프가 끝날 때 표를 다음 스코프에 넘기는 것이 리졸버가 원하는
모양이다 -- 함수마다가 아니라 중첩 단계마다 표 하나.

bind 는 Name 노드의 남는 a 필드를 재활용할 수도 있었지만 명시적인 쪽을 골랐다.
노드가 32 에서 36 바이트가 되는 값으로 그 자리가 무엇인지 이름이 말한다.

clear 는 아무도 부르지 않는 채로 들어와 있었다. maps.fe 가 이제 부른다: 키가
사라지고, 방은 64 로 남고, 그 위에 다시 채워도 버퍼를 새로 잡지 않는다.

  cleared 0 room 64 gone 0 / refilled 3 / balanced

GOAL.md 를 더했다. 외부 감사와, 그 항목들을 실제로 빌드해서 확인한 결과를
합친 P0~P4 다.

228/228, 32/32.
2026-08-17 15:50:58 +09:00
coolguy f7e667652e 대여는 변수가 아니라 place 단위다
p.a 와 p.b 는 서로 다른 자리인데 한쪽을 대여하면 다른 쪽까지 잠겼다. 메서드가
하는 일의 대부분이 한 필드에 쓰면서 다른 필드를 읽는 것이라, std.map 의 keep 은
그것 때문에 함수 둘로 갈라져 있었고 파서도 같은 자리에서 걸렸다.

FeOwnState 가 필드별 칸을 넷 갖는다. 값으로 복사되는 구조체라 흐름 병합과
스냅샷은 손댈 것이 없었다. 전체를 대여하면 모든 필드와 충돌하고, 필드를
대여하면 전체 및 같은 필드와 충돌한다. 칸이 모자라면 전체 대여로 되돌아가
더 많이 보고할 뿐 놓치지 않는다.

읽기는 식별자에서 일어나는데 그 자리에서는 자기가 무엇의 밑동인지 알 수 없다.
그래서 투영이 내려가는 길에 어느 필드인지 적어두고 식별자가 그것을 집는다.
인덱스는 갈라지지 않는다 -- xs[i] 의 i 는 상수가 아닐 수 있고, 필드 이름은
상수다.

길에서 나온 것: mem.replace 가 목적지 대여를 가져가고 돌려주지 않았다. 일반
호출 인자는 문장 끝에 돌려주는데 intrinsic 경로에만 그것이 없었다. 전에는
그 자리가 어차피 거부돼서 드러나지 않았다.

  var p = Pair{ a: 1, b: 2 };
  let r = &mut p.a;
  p.b = 3;      // ok -- 전에는 에러
  p.a = 3;      // 에러
  take(p);      // 에러

SPEC §5 R6 을 고쳤고, 옛 규칙을 그대로 적어둔 문단과 예제를 갈아치웠다.
own/badrfld 는 이제 허용되는 코드였으므로 같은 필드를 건드리도록 다시 겨눴고
okrfld·badrall·badrsame·exec/fieldbrw 를 더했다.

228/228, 32/32.
2026-08-17 15:29:12 +09:00
coolguy 120a36eef5 spec: 완화했던 이동 규칙 둘을 명세에 넣는다
구현만 알고 있으면 둘 중 하나가 틀린 것이다.

- 배타 대여를 호출에 넘기는 것은 재대여 -- 이미 §4.2 에 있었다.
- 자기 drop 안의 부분 이동은 R7 예외다. 객체가 사라지는 중이라 drop 이 돌아간
  뒤에 그 반쪽짜리 값을 읽을 코드가 없다. 다른 함수에는 예외가 없다.

TODO 의 '판단을 기다리는 것' 이 비었다.
2026-08-17 15:16:24 +09:00
coolguy d1d031019a docs: TODO 와 fixture README 를 지금 상태로
파서까지 끝났으니 남은 길을 다시 적는다. 필드 단위 대여가 목록에 올라왔다 --
map 도 파서도 같은 자리에서 걸렸다.

224/224, 31/31.
2026-08-17 12:57:27 +09:00
coolguy 63ad48cd8a 트랩은 검사가 쓰인 파일을 댄다
빌드 전체가 한 모듈이라 파일 이름도 하나였다. std.list 안에서 터진 경계 검사가
프로그램의 파일 이름을 대고 있었으니, 줄 번호는 맞는데 파일이 틀려서 엉뚱한 줄을
가리켰다 -- 이름을 안 대는 것보다 나쁘다.

모듈이 파일 표를 들고 트랩은 그 인덱스를 든다. 생성기는 파일마다 FE_FILE_n 을
한 번씩 찍는다.

  before: index out of bounds at main.fe:2
  after:  index out of bounds at pick.fe:6

그리고 Parser.on 이 구조체 리터럴 안에서 다시 try 를 쓴다. 앞서 그것이 깨졌던
것은 try 때문이 아니라 Parser 가 1 바이트로 자리잡았기 때문이었다.

224/224, 31/31.
2026-08-17 12:56:34 +09:00
coolguy abdb049d05 lowering: .n 은 슬라이스에게만 길이다
구조체도 필드를 n 이라 부를 수 있다. lowering 은 이름만 보고 슬라이스 길이
자리(포인터 다음 4바이트)를 읽어서, 그 자리에 있던 그럴듯한 숫자를 돌려주고
있었다. 체커는 제대로 필드로 풀고 있었으니 같은 함수 안에서 쓰기와 읽기가
어긋났다.

  Box{ room: ^[]mut u8, n: usize, m: usize }
  n 777 m 999   (전에는 n 12 -- room 의 길이)

배열/슬라이스/str 일 때만 길이로 읽는다. fieldn.fe 가 이것과, 옆의 슬라이스가
여전히 길이로 답하는 것을 함께 고정한다.

222/222, 30/30.
2026-08-17 12:52:38 +09:00
coolguy e84f892147 Ferro 파서를 Ferro 로, 그리고 그것이 드러낸 네 가지
렉서 다음은 파서다. 노드는 한 배열에 살고 자식은 그 안의 인덱스다 -- 노드는
^Node 를 들 수 없고(여럿이며 한 번씩 소유하지 않는다) &Node 도 들 수 없다(R4).
인덱스는 둘 다 아니다. 소스도 필드가 아니라 매 단계에 같이 다닌다.

  unit demo / fn answer @2 / let n = (+ 1 (* 2 3)) / return n / balanced

전위 표기로 다시 찍는 것이 시험의 요점이다. 1 + 2 * 3 이 어떻게 묶였는지는
그렇게만 보인다.

쓰면서 나온 컴파일러 버그 넷:

1. 다른 유닛의 타입을 필드로 쓰면 그 필드 타입이 영영 UNKNOWN 이었다. 필드
   해석이 유닛마다 선언 직후에 돌아서, 아직 선언되지 않은 유닛의 타입을 찾다
   실패하고 그 답을 굳혔다. 이제 모든 유닛이 선언을 마친 뒤에 한 번 푼다.

2. 그리고 그 해석은 타입을 선언한 유닛에서 해야 한다. 필드 타입은 그 유닛의
   import 로 쓰였는데 아무 유닛에서나 풀고 있었다. 타입 계층에 enter/leave
   콜백을 두고 체커가 그 자리로 데려간다.

3. cycle_state 를 재귀 검사와 크기 계산이 같이 썼다. 첫 번째가 보는 중인 구조체
   가 두 번째에게는 다 끝난 것으로 보여서, 필드가 하나뿐인 것처럼 1 바이트로
   자리를 잡았다 -- Parser 가 그래서 자기 토큰을 밟았다. layout_state 로 나눴다.

4. 다른 유닛의 상수(ast.NONE)를 lowering 이 필드 접근으로 봤다. 체커가 이미
   링크 이름을 붙여두었으니 그것이 있으면 전역이다.

그리고 R1 을 실제로 지키게 했다: 소유자를 놓으면 그것이 가진 것도 놓는다.
전에는 자기 drop 이 있거나 자기가 owned 일 때만이어서, drop 을 가진 타입을
필드로 담은 구조체는 그것을 놓을 방법이 없었다(drop 은 손으로 못 부른다).
이제 release_at 이 drop 을 부르고 필드로 내려간다. 그 덕에 List/Arena/Map 의
drop 이 전부 필요 없어져서 지웠다 -- 버퍼가 owned 이니 R1 이 알아서 한다.

221/221, 29/29.
2026-08-17 12:49:53 +09:00
coolguy 8c4e80e246 std: map 을 쓴다 -- 바이트 열에서 값으로
컴파일러는 이름을 끊임없이 찾는데 리스트 선형 탐색은 그 모양이 아니다. 키는
맵이 소유하는 한 버퍼에 복사되고 슬롯은 그 안의 어디인지만 적는다 -- R11 이
말하는 아레나와 핸들 모양이고, 그래서 맵을 놓는 것이 엔트리마다 하나가 아니라
두 번의 해제다.

개방 주소법에 선형 탐사. 표는 2의 거듭제곱이라 나눗셈이 아니라 마스크이고,
탐사가 길어지는 것이 표가 차는 것보다 먼저라 3/4 에서 자란다.

길에서 고친 것 넷:

- 인스턴스를 만들 때 선언 유닛으로 전환하지 않아서, 필드 타입 Slot(V) 를
  호출자 유닛에서 찾고 있었다.
- mem.alloc_slice 가 원소 타입으로 단순한 이름만 받았다. Slot(V) 같은
  인스턴스도 받는다.
- 쓸 수 있는지를 바인딩이 아니라 소유된 것이 정한다. let p: ^[]mut T 는 p 를
  고정하고 그것이 소유한 것은 쓸 수 있게 둔다. 슬라이스 인덱스도 마찬가지다.
- 메서드 인자에 자유 함수와 같은 호출 한정 약화가 없었다.

알게 된 것: 대여는 루트 단위라 self 의 한 필드에 쓰는 동안 다른 필드를 읽을 수
없다. 지역으로 빼거나 메서드를 나누면 되지만, 필드 단위 대여가 있으면 훨씬
편할 자리다.

  count 5 / fn 2 let 3 missing 0 / grown 64 / after 40 / balanced

218/218, 28/28.
2026-08-17 12:23:52 +09:00
coolguy c7cba061b3 docs: 셀프호스팅 전 목록이 끝난 상태를 적는다
렉서가 알려준 것도 함께: R11 의 모양 -- 아레나가 소유하고 인덱스가 가리킨다 --
은 쓸 수 있다. 토큰이 from/len 을 들고 소스가 옆에서 같이 다니는 것은 장황하지만
막히지 않는다. 모든 함수가 src 를 하나 더 받는 것이 그 값이다.

파일 크기 규칙을 AGENTS 에 넣었다.
2026-08-17 07:36:14 +09:00
coolguy 76cb7e254c lexer: Ferro 의 렉서를 Ferro 로 쓴다
셀프호스팅에 손대기 전의 강제 함수다. 아픈 자리를 전부 건드린다: R4 아래의
토큰 구조체, 태그드 유니온, 진단 출력, 유닛 경계.

토큰은 자기가 나온 글자를 담지 않는다. R4 가 대여를 집합 저장소에서 막으므로,
어디서 시작해 얼마나 긴지를 적고 소스는 옆에서 같이 다닌다. 위치도 &mut usize
로 옆에서 다닌다 -- 슬라이스와 함께 구조체에 들어갈 수 없기 때문이다. 이것이
R11 이 말하는 모양이고, 쓸 수 있다.

  first keyword unit @1 / number 42 @3 / text "hi" @3 / arrow -> @5
  keyword 6 name 7 number 1 text 1 punct 15 / total 30

길에서 고친 것:

- binding.Type.Variant 가 안 풀렸다. 유닛 경계 이름 조회가 심볼만 보고 타입을
  보지 않았다.
- 문자열 const 전역이 빈 슬라이스로 나갔다. 포인터는 링커만 아는 수라서 바이트에
  구멍을 두고 링커가 채우게 한다.
- exec.py 가 OUTPUT 마커를 여러 개 적어도 마지막 하나만 검사했다. 고치자마자
  readfile 의 낡은 기대가 드러났다.

run.py 217/217, exec.py 27/27.
2026-08-17 07:35:21 +09:00
coolguy 4fe0073365 backend: 레지스터를 할당한다
임시값마다 스택 슬롯을 주던 것을 바꿨다. ebx, esi, edi 세 개를 나눠준다 --
eax/ecx/edx 는 이 방출기가 계산하는 자리이고, 남는 셋은 호출을 저장 없이
넘긴다.

IR 은 '임시값은 블록을 넘지 않는다'로 설계했지만 lowering 이 실제로는 넘기는
것을 만든다 -- 경계 검사가 인덱스를 계산한 자리와 쓰는 자리 사이에서 블록을
쪼갠다. 그래서 자격은 함수 전체를 보고 정하고, 블록 안의 선형 스캔은 살아남은
것만 다룬다.

그리고 목적지 레지스터에 직접 계산한다. 상수, 적재, 주소, 그리고 전폭 산술과
비교가 스크래치 레지스터를 거치지 않는다. 좁은 연산은 여전히 eax 를 거친다 --
esi 와 edi 에는 바이트 반쪽이 없다.

버그 둘:
- 프롤로그에 ebx 를 넣는 편집이 copy 의 push 까지 같이 바꿔서 pop 없는 push 가
  생겼다. 스택이 어긋나 17개가 죽었다.
- load_place_base 가 load_temp 을 거치지 않고 슬롯을 직접 읽었다. 레지스터에
  있는 포인터를 쓰지 않은 메모리에서 읽었다.

  calc      4437 -> 3796 줄  (-14%)
  wordfreq  6023 -> 5348 줄

214/214, 26/26.
2026-08-17 07:30:22 +09:00
coolguy ae83f5b142 std: mem.Arena 를 구현한다
SPEC R11 은 재귀·그래프 모양 데이터를 아레나가 값을 소유하고 정수 핸들이
가리키는 것으로 답한다. 그 답은 아레나가 실제로 있어야 쓸 수 있다.

핸들은 오프셋이라 아레나가 사는 동안 유효하고, 두 핸들을 비교하는 것은 두 수를
비교하는 것이다. 아레나는 몰래 자라지 않는다 -- 움직인 핸들은 더 이상 아무것도
가리키지 않기 때문이다.

길에서 고친 것 셋:

- Self 가 제네릭 인스턴스에서만 타입으로 묶여 있어서, 평범한 구조체의 Self{..}
  가 안 풀렸다. 이제 모든 메서드에서 묶는다.
- binding.Type.method() 가 식 자리에서 해석되지 않았다.
- 다른 유닛의 비제네릭 구조체 메서드가 lowering 되지 않고 extern 으로만 나갔다.
  파일을 나눌 때 그 가지가 빠졌다.

  handles 0 4 8 / value 65 / full / reset 0 / balanced

exec.py 26/26.
2026-08-17 07:21:40 +09:00
coolguy c06f5c50c4 compiler: 조용히 잘리던 상한을 없앤다
lowering 의 변수·정리 목록·오류 이름 세 배열은 넘치면 오류가 아니라 넘친 것을
버리고 틀린 코드를 냈다. 한계에 닿는 방식 중 최악이다. 이제 자란다.

코드 생성기는 지역이 512개를 넘으면 함수를 아예 방출하지 않고 지나갔다. 이제
지역 수만큼 자리를 잡는다.

유닛 64 -> 256, 제네릭 인스턴스 512 -> 4096. 둘 다 원래 보고는 했지만 장난감을
기준으로 고른 숫자였다.

209 -> 213 fixture, exec 25/25.
2026-08-17 07:18:47 +09:00
coolguy 0fd3f187f4 lower: 태그드 유니온을 해체한다 -- match 페이로드와 if let
AST 도 IR 도 본질이 태그드 유니온이다. 태그 비교만 되고 안을 꺼내지 못하면
검사 없이 필드를 읽어야 하고, 그러면 안전성 이야기가 통째로 무너진다.

무언가를 담는 변이는 메모리다: 태그가 앞, 페이로드가 뒤. 태그를 읽는 것은
어느 쪽이든 같은 질문이고 자리만 다르다. 페이로드는 가리키지 않고 복사한다 --
매치한 것의 소유권을 arm 이 가져가는 것이 보통이고, 그게 허용되는지는 검사기가
이미 판단했다.

레코드 변이의 필드 오프셋을 아무도 기록하지 않고 있었다. 레이아웃이 크기는
재면서 자리는 버렸다.

Enum.Variant{...} 와 Enum.Variant(x) 와 페이로드 없는 Enum.Variant 를 모두
만든다. 마지막 것은 페이로드를 가진 enum 안에서는 태그만 든 값이다.

  some 7 / none / point 3 4 / empty

exec.py 25/25.
2026-08-17 07:15:57 +09:00
coolguy 676fef88fb std: 프로그램이 바깥 세상과 이야기한다 -- 파일과 명령줄
런타임에 open/read/close 와 명령줄을 넣었다. std.io 가 그 위에 파일 열기,
읽기, 쓰기, 그리고 명령줄을 조각으로 나누는 것을 얹는다. 인용부호 처리는
런타임이 알 일이 아니라 라이브러리가 할 일이다.

길에서 고친 것들:

- *T 가 타입 시스템에 실체가 없어서 덩어리로 취급됐다. 이제 진짜 종류다 --
  주소일 뿐이고 추적할 대여도 실행할 drop 도 없는 Copy 타입. 그 결과 &u8 이
  *u8 에 자동으로 맞지 않게 됐는데, 그게 맞다: R9 는 그 변환을 unsafe 안의
  @ptr_cast 로만 허용한다.
- raw 포인터에 정수를 더하면 더 뒤의 주소다. 소유자나 대여에는 허용하지
  않는다 -- 자기 자리가 있는 것에서 걸어나가는 것이 *T 의 용도다.
- @volatile_load / @volatile_store / @ptr_cast 를 내린다.
- undefined 가 선언된 타입을 따른다. 없으면 손으로 타이핑할 수 있는 것보다
  큰 버퍼를 선언할 방법이 아예 없었다.

R8 이 정확히 동작하는 것도 확인했다: 참조성 파라미터가 둘인 함수는 슬라이스를
반환할 수 없다. 어디서 파생됐는지 시그니처가 말하지 않기 때문이다.

exec.py 24/24.
2026-08-17 07:11:56 +09:00
coolguy e014c95a75 lower: @print 과 @fprint 를 컴파일 단계에서 전개한다
SPEC 6.3.1: 포매팅 빌트인은 가변 인자 함수가 아니다. 호출 하나가 리터럴
조각마다 쓰기 하나, 값마다 쓰기 하나로 펴진다. 언어에 가변 인자 호출 규약이
생기지 않고, 포맷 문자열은 실행 시점에 이미 사라져 있다.

verb: {} 십진, {x} 16진, {c} 한 바이트, 문자열은 포인터와 길이, bool 은
분기 두 개와 리터럴 두 개.

코드 생성기가 호출됐지만 정의되지 않은 이름을 스스로 extern 선언한다. lowering
이 런타임 호출을 직접 내므로, 손으로 관리해야 하는 목록 대신 호출 자체에서
이름을 모은다.

  @print("n={} neg={} hex={x}\n", 42, 0-7, 255)  ->  n=42 neg=-7 hex=ff
2026-08-17 07:05:55 +09:00
coolguy 390345ef85 refactor: check.c 와 lower.c 를 사람이 머리에 담을 크기로 나눈다
check.c 3,937 줄, lower.c 1,913 줄이었다. 가장 큰 파일이 978 줄이 됐다.

           check.c     679   스코프·심볼·흐름·소유권 접착
           checkexp.c  739   포매팅 검사와 표현식
           checkstm.c  635   문장, 함수, 메서드
           checkgen.c  618   제네릭 실체화
           checkcal.c  978   유닛 경계 호출과 옵셔널/에러 유니온
           checkpro.c  184   선언 패스와 프로그램

           lower.c     567   타입·슬롯·지역·블록·mem.*
           lowerprn.c  238   포매팅 빌트인 전개
           lowerexp.c  468   표현식
           lowerstm.c  543   문장·함수·프로그램

줄 범위로 잘랐다. 주제별로 묶는 것보다 정확한데, 한 줄도 잃거나 겹치지
않기 때문이다. 파일 순서가 이미 단계를 따라가서 경계가 실제 이음매에 떨어진다.

모든 정의가 static 을 잃고 비공개 헤더에 프로토타입을 갖는다. 대안 --
static 을 유지하고 #include 로 텍스트만 나누는 것 -- 은 결합을 보여주는 대신
숨긴다.

두 스위트 그대로: 209/209, 21/21.
2026-08-17 07:04:35 +09:00
coolguy e6de12ca94 docs: 완성된 상태에 맞춰 AGENTS 와 TODO 를 다시 쓴다
파이프라인이 끝에서 끝까지 도는 상태다. 검증이 두 스위트로 나뉜다 -- 컴파일러가
프로그램에 대해 뭐라고 하는가, 그리고 컴파일된 프로그램이 실제로 무엇을 하는가.
전자만 보면 진단은 옳은데 코드가 안 나오는 상태를 놓친다.

세션 중에 완화한 이동 규칙 두 곳을 TODO 맨 위에 사람의 판단을 기다리는
항목으로 적었다. 규칙을 건드리기 전에 프로그램 쪽을 먼저 고쳐보라는 것도
작업 흐름에 넣었다.
2026-08-17 06:48:06 +09:00
coolguy 7f871a5d5f tests: 단어 빈도 프로그램
컬렉션과 문자열을 함께 쓴다. 구조체를 담는 제네릭 리스트, 슬라이스 비교,
처음 본 순서 유지, 그리고 할당과 해제가 맞는지 확인.

  the 3 / cat 2 / sat 1 / distinct 5 / balanced

run.py 209/209, exec.py 21/21.
2026-08-17 06:46:47 +09:00
coolguy 432d073104 lang: 배타 대여를 호출에 넘기는 것은 이동이 아니라 재대여다
&mut T 를 &mut T 파라미터에 넘기면 호출이 끝날 때 돌려받는다. 호출이 도는
동안 호출자는 그 값에 손댈 수 없으므로 별칭이 생기지 않는다. 이것이 없으면
배타 파라미터를 다시 넘기는 일이 함수당 한 번만 가능해서 &mut 가 사실상 쓸 수
없었다 -- 재귀 하강 파서를 쓰다가 걸렸다.

페이로드 없는 enum 은 이름 붙은 수라서 수로 읽을 수 있다. 반대 방향은 안 된다:
임의의 수는 변이가 아니다.

calc 프로그램: 재귀 하강 수식 계산기. 우선순위, 괄호, 오류 전파.

  1+2*3 = 7   (1+2)*3 = 9   2*(3+4)-5 = 9   10/3 = 3
  1+ = error  (1+2 = error
2026-08-17 06:45:19 +09:00
coolguy 206799d1cb std: str 과 list, 그리고 자동 drop 이 사용자 타입까지 닿는다
std.str 은 eq/starts_with/find/trim/parse_int 을 바이트 슬라이스 위에서 한다.
std.list 는 자라는 제네릭 시퀀스다 -- 버퍼를 소유하므로 리스트를 놓으면
원소도 놓인다. 성장은 두 배씩이라 push 당 복사량이 상수로 눌린다.

찾은 버그 넷:

- 메서드가 자기 타입의 유닛이 아니라 호출한 유닛에 속한 것으로 계산됐다.
  다른 유닛의 제네릭 타입을 쓰면 필드가 전부 private 으로 보였다.
- 참조로 도달한 메서드를 찾지 못했다. self.grow() 가 안 됐다.
- 이미 참조인 수신자의 주소를 한 번 더 떠서 넘겼다. 포인터의 포인터를 받은
  메서드가 그것을 구조체로 읽었다.
- 유닛으로 한정된 제네릭 타입(list.List(i32))이 타입 자리에서도 식 자리에서도
  해석되지 않았다.

drop 을 가진 타입은 인스턴스마다 그 메서드가 존재해야 한다 -- 이름으로 부르는
사람이 없어도 스코프 정리가 부른다. 그리고 자기 drop 안에서는 필드를 꺼낼 수
있다. 객체가 사라지는 중이라 뒤에 남아 읽힐 것이 없다.

run.py 207/207, exec.py 19/19.
2026-08-17 06:42:16 +09:00
coolguy b0c9338cf3 tests: pending-backend 격리를 없앤다
코드 생성기가 없어서 돌릴 수 없던 것들이다. 이제 돌아간다. 경계 트랩,
--no-checks 차등, 슬라이스 범위 검사, 소유권 해제가 전부 exec/ 에서
실행으로 검증되므로 격리할 이유가 없다.

run.py 205/205, exec.py 17/17.
2026-08-17 06:32:57 +09:00
coolguy 3a01cb4c51 lower: 소유 값을 스코프 끝에서 자동으로 해제한다
defer 목록을 '스코프가 아직 갚아야 할 것' 목록으로 일반화했다. defer 블록과
소유 값 해제가 같은 목록에 쓰인 순서대로 들어가고, 모든 이탈 경로가 역순으로
갚는다.

해제에는 값 옆에 플래그를 둔다. 값이 저장될 때 세우고 넘겨줄 때 지운다. 값이
아직 여기 있는 경로에서만 해제되는데, 그건 코드의 모양만 봐서는 알 수 없는
것이다. 검사기가 소유권을 넘기는 사용을 이미 표시해두므로 그것을 읽는다.

!void 함수의 빈 return 은 성공이다. 줄 값도 없고 오류도 없다는 뜻인데
프론트엔드가 타입 불일치로 거부하고 있었다.

런타임이 할당/해제 횟수를 센다. owndrop 프로그램이 그 둘이 일치함을
실행으로 증명한다 -- 이른 반환, 이미 넘긴 값, 스코프 끝 전부.
2026-08-17 06:32:15 +09:00
coolguy 9510f12643 lower: mem.create / alloc_slice / destroy / replace
할당하는 내장 함수들이다. 평범한 호출이 아니라서 여기서 편다. create 는 값을
받아 그 복사본을 가리키는 소유 포인터를 주고, 할당이 실패할 수 있으므로 결과가
에러 유니온이다. 실패 코드는 OutOfMemory 이고, 소스 어디에도 그 이름이 적혀
있지 않지만 다른 이름과 같은 표에 들어간다.

갓 할당한 저장소는 통째로 소유하므로 쓸 수 있다 -- 방해할 사람이 없다. 그래서
alloc_slice 는 ^[]mut T 를 준다. 소유 슬라이스는 포인터와 길이가 값 자체라서
.^ 로 통과할 것이 없고, destroy 는 그 안의 포인터를 푼다.

heap 프로그램이 할당·try·defer 해제·for 순회를 한꺼번에 돈다: sum 4950
2026-08-17 06:29:18 +09:00
coolguy 231c7d564b lower: 제네릭 인스턴스와 메서드
모노모피제이션이 실제로 코드를 만드는 자리가 여기다. 프론트엔드는 어떤
인스턴스가 존재하는지만 정했다. 검사기가 인스턴스마다 선언·바인딩·유닛·링크
이름을 기록하고, lowering 이 그 바인딩을 다시 걸고 같은 본문을 자기 이름으로
내린다. 제네릭 선언 자체는 코드가 없다.

comptime 인자는 값이 아니므로 호출에서 넘기지 않고 파라미터 자리도 잡지
않는다. 메서드 호출은 도달한 대상을 첫 인자로 넘긴다 -- self: Self 든
self: &Self 든 수신자의 주소로 같다. 구조체 메서드가 아예 lowering 되지
않고 있었다.

exec.py 13/13.
2026-08-17 06:26:20 +09:00
coolguy eba6f63530 lower: 슬라이싱
x[a..b] 는 인덱스가 아니라 포인터와 길이를 만든다. 양쪽 끝을 -- 서로에 대해,
그리고 있는 것에 대해 -- 검사한 뒤에 포인터를 만든다. 유효한 범위의 빈
슬라이스는 괜찮고 끝보다 늦게 시작하는 것은 아니다.

파서가 x[a] 와 x[a..] 를 구분하지 못했다. 둘 다 b 만 있고 c 가 없어서
모양이 같았다. '..' 가 있었으면 노드에 표시한다.

정수 출력이 된다: fizz 12345 -678
2026-08-17 06:20:17 +09:00
coolguy 0de10f37b5 std: io 와 fmt 를 Ferro 로 쓰고, 컴파일된 프로그램이 출력한다
io.Writer 는 핸들 하나짜리 enum 이다. 참조도 컨텍스트 포인터도 담지 않으므로
Copy 이고 자유롭게 오간다 (SPEC 5 R8). fmt 는 sink 를 소유하지 않는다 --
호출자가 버퍼를 주고 앞에서 몇 바이트가 쓰였는지 돌려받는다.

lowering 에 추가: enum 변이 상수, match, 정수 캐스트, 문자열 이스케이프.

프론트엔드 정밀도 하나: 항상 빠져나가는 분기의 상태를 병합하지 않는다. 그
분기가 소비한 값이 그 분기를 지나지 않은 경로에서도 소비된 것처럼 보였다.
fmt_i32 가 이것 때문에 못 쓰였다.

extern "c" 이름은 유닛 접두사를 붙이지 않는다. 링커가 이미 아는 이름이라는
것이 그 선언의 요점이다.

run.py 199/199, exec.py 11/11.
2026-08-17 06:18:16 +09:00
coolguy 4624c6d0ec std: 표준 라이브러리가 컴파일러 옆에서 해석되고 호출된다
std 는 예약된 이름이고 프로그램이 아니라 컴파일러와 함께 있으므로 자기 루트를
갖는다 (--std=). 본문 없는 선언은 링커가 찾을 것 -- 런타임이나 C 라이브러리 --
이므로 IR 에 extern 으로 나간다.

런타임에 write/alloc/free/exit 를 넣었다. 이것이 표준 라이브러리가 스스로
말할 수 없는 전부이고 나머지는 Ferro 로 쓴다.

@trap @unreachable @size_of @align_of @line 을 내린다.

링크 이름에서 점과 괄호를 걸렀다. 유닛 경로에는 점이 있고 제네릭 인스턴스에는
괄호가 있는데 어셈블러가 받지 않는다.
2026-08-17 06:12:44 +09:00
coolguy 174e6c569d lower: 전역과 문자열 리터럴, 그리고 defer 실행 검증
전역은 정적 저장소다. 초기값이 컴파일타임 상수면 이미지에 박고 아니면 0이다.
문자열 리터럴은 바이트를 이미지에 두고 포인터와 길이를 값으로 만든다. 같은
글자는 같은 저장소를 쓴다 -- 읽기 전용이라 공유가 공짜다.

defers 프로그램이 defer 순서를 실행으로 고정한다. 등록 역순이고, 이른 return
과 끝까지 간 경로 양쪽 다 돈다.
2026-08-17 06:08:33 +09:00
coolguy 096a5db411 lower: 옵셔널, 에러 유니온, try/catch/orelse, defer, for
옵셔널은 태그와 페이로드, 에러 유니온은 오류 코드와 페이로드다. 코드 0 이
'오류 없음'이다. 페이로드 위치 규칙을 types.c 로 옮겨서 레이아웃 패스와 코드
생성기가 같은 것을 본다.

try 는 분기다. 실패면 지금 함수의 에러 유니온을 그 코드로 만들어 나간다 --
그 전에 defer 를 돌린다. catch 와 orelse 는 오른쪽을 필요할 때만 평가하므로
역시 분기다.

for 는 세 형태를 공유한다: 세는 것, 원소를 도는 것, 위치까지 받는 것. 개수는
본문 전에 한 번 읽는다. 원소 바인딩은 참조다 -- 그래서 루프가 원본에 쓸 수
있다.

error.Name 은 빌드 전체에서 이름을 모아 철자 순으로 1부터 번호를 준다
(SPEC 4.6). 빌드 순서가 결과를 바꾸지 않는다.

run.py 197/197, exec.py 9/9.
2026-08-17 06:06:35 +09:00
coolguy 43555b261c lower+backend: 배열, 경계검사, 구조체, 그리고 실행 테스트 스위트
인덱스는 부호 없는 비교와 트랩으로 펴진다. --no-checks 는 메시지가 아니라
비교와 분기 자체를 없앤다 -- 그게 그 플래그의 전부다.

버그 셋:

- 값으로 넘긴 구조체 파라미터는 주소로 도착하는데 lowering 이 그걸 몰라서
  포인터를 구조체로 읽었다. 변수마다 by_address 를 기록한다.
- 덩어리 반환의 숨은 결과 인자를 지역이 아니라 임시값으로 다뤘다.
- store 에 폭이 없어서 1바이트 bool 을 4바이트로 썼다. 옆 지역변수가
  뭉개졌고 logic 프로그램이 틀린 답을 냈다.

tests/exec.py 가 새 스위트다. run.py 는 컴파일러가 프로그램에 대해 뭐라고
하는지 보고, 이쪽은 프로그램이 실제로 무엇을 하는지 본다. 보고만 되고
방출되지 않는 경계검사는 저기서는 통과하고 여기서는 실패한다.

run.py 194/194, exec.py 6/6.
2026-08-17 06:00:33 +09:00
coolguy e5093e690d backend: i386 어셈블리를 내고 Windows 11 실행 파일을 만든다
fec --emit-asm -> wasm -> wlink -> .exe. 툴체인은 고정된 Open Watcom 그대로다.

레지스터 할당기가 없다. 임시값마다 스택 슬롯을 주고, 명령마다 피연산자를
고정 레지스터로 읽어 계산하고 다시 저장한다. 느린 코드지만 명백히 옳은
코드이고, 옳은 것이 먼저다. 나중에 할당기를 끼워도 나머지는 모른다 --
임시값이 어디 사는지만 바뀐다.

런타임 fec/rt/start.asm 은 진입 스텁과 fe_trap 이다. trap 은 이유와 파일과
줄을 stderr 에 쓰고 3으로 끝낸다.

처음으로 Ferro 프로그램이 실행됐다:

  1..10 합         -> 55
  (7*6-2)/4        -> 10
  루프+호출+분기   -> 1

tests/build.py 가 컴파일하고 링크하고 돌린다.
2026-08-17 05:55:34 +09:00
coolguy 6ee3764667 lower: 검사된 AST 를 IR 로 내린다 (1차)
함수, 파라미터, 지역, 리터럴, 이름, 산술과 비교, 대입, if, while,
break/continue, 호출, 참조, 필드 접근, 포인터 역참조까지.

Slot 이 표현식의 결과다 -- 임시값에 든 값이거나 메모리 안의 자리다. 덩어리는
언제나 자리다. 임시값은 레지스터이고 덩어리는 거기 안 들어가기 때문이다.

and/or 는 연산이 아니라 제어 흐름으로 내린다. 오른쪽을 평가하지 않아야 하는
경우가 있어서다.

블록에 terminated 플래그를 뒀다. 없으면 분기 안의 return 이 join 으로 가는
점프에 덮인다.

--dump-ir 로 볼 수 있다. try/catch/defer/drop/for/배열/옵셔널/에러유니온과
제네릭 인스턴스는 아직이다.
2026-08-17 05:51:01 +09:00
coolguy ddea962d14 ir: 중간 표현을 정의한다
명령 12개와 종결자 4개. 함수 단위 기본 블록이고 임시값은 블록을 넘지 않아
phi 노드가 없다 -- 블록을 넘겨야 하는 값은 지역을 경유한다. 코드가 조금 더
생기지만 레지스터 할당기를 블록 단위로 유지해 준다.

Ferro 타입은 여기서 사라진다. 구조체·슬라이스·옵셔널·에러 유니온이 전부
mem<N> 이고 필드는 lowering 이 계산한 바이트 오프셋이다. 모노모피제이션이
프론트엔드에서 끝나므로 IR 에 제네릭이라는 개념도 없다.

덩어리는 언제나 주소로 오간다. 크기 임계값이 없어서 ISA 마다 다른 구조체 전달
규칙을 통째로 피해간다. trap 은 이유와 줄 번호만 남기고 파일 이름 문자열은
유닛당 하나를 공유한다.

IR.md 가 설명이고 ir.h/ir.c 가 그 형태다. 아직 아무도 만들지 않는다.
2026-08-17 05:44:56 +09:00
coolguy b0e55e072e spec: FE_TOK_FAR 토큰 제거 2026-08-17 05:41:10 +09:00
coolguy 718c323938 spec: 타깃을 i386 하나로 정하고 far 를 언어에서 뺀다
세그먼트 주소 지정은 x86 리얼모드에만 있는 개념이고, 평평한 주소 공간을 가진
다른 32비트 프로세서에는 대응물이 없다. 영구 제외다.

usize/isize 는 타깃의 포인터 폭이며 특정 비트 수를 약속하지 않는다. 오늘
32비트지만 u32 와 자동 변환되지 않는다. bits16 에서 배울 것은 '32로 정하자'가
아니라 '폭이 언어 의미론으로 새어나가지 않게 하자'이고, 그것이 나중에 다른
폭의 타깃을 여는 유일한 장치다.

타깃이 하나이므로 레이아웃에서 pointer_bits 분기가 전부 사라졌다. 인터럽트
핸들러와 공유 상태는 v0.2 로 내렸다 -- 문법은 아직 파싱되지만 명세의 약속은
아니다.
2026-08-17 05:40:49 +09:00
coolguy 25d9de65e1 implement: 제네릭 모노모피제이션 (SPEC 9)
타입 인자를 바인딩한 상태로 선언을 인스턴스마다 한 번씩 검사한다. 바인딩된
이름은 그냥 그 인자 타입이므로 본문, 필드 타입, 시그니처가 모두 같은 규칙으로
풀린다. 인스턴스 정체성은 선언 유닛 + 선언 + 인자 철자다.

찾은 버그 셋:

- 파서가 comptime 파라미터의 이름을 'comptime' 이라는 키워드에서 가져갔다.
  타입 파라미터 이름이 전부 comptime 이 되어 아무것도 바인딩되지 않았다.
- 인스턴스 이름이 중첩마다 길어져서, 깊은 사슬에서 잘린 이름끼리 충돌해
  재귀가 깊이 제한에 닿기 전에 조용히 멈췄다. 길어지면 인자를 일련번호로
  적어 정체성을 유지한다.
- 순서 비교 연산자가 피연산자 타입을 보지 않아 구조체끼리 비교해도 통과했다.
  제네릭과 무관한 기존 구멍이다.

fixture 셋이 명세와 어긋나 있어 명세를 따랐다. badbody 와 badop 은 호출 지점을
primary error 로 기대했지만 SPEC 9 는 본문의 연산이 primary 이고 호출에는
'instantiated here' note 를 붙이라고 한다. okscope 는 제네릭 본문이 호출자의
이름을 본다고 기대했지만 SPEC 9 는 정의 유닛에서 해석한다 -- badscope 로 옮기고
이유를 적었다.

188/188.
2026-08-17 05:24:36 +09:00
coolguy cb20cce81a docs: TODO 와 핸드오프 문서를 추적한다
지난번 에이전트가 handoff1 만 지우라는 지시에 두 문서까지 같이 지웠다.
untracked 였기 때문에 git 에 기록이 없어 복구할 수 없었다.
2026-08-17 05:08:07 +09:00
coolguy a265901d7e implement: 유닛 경계를 넘는 이름, 가시성, 기본 에러 집합
import 가 만든 binding 으로 다른 유닛의 선언에 닿는다. 호출, 구조체 리터럴,
값 참조 세 자리다. 시그니처의 타입은 그 시그니처가 쓰인 유닛에서 해석한다 --
호출한 쪽에서 해석하면 같은 이름이 다른 타입을 가리킨다.

pub 없는 선언과 필드는 자기 유닛 밖에서 보이지 않는다.

error.Name 은 구현된 적이 없었다. 기본 에러 집합 core.Error 의 멤버이고, 그
집합은 선언이 아니라 수집으로 채워지므로 변이 목록 없이 정체성만 갖는다.

units 34/34. dotpriv/main 은 위반이 있는 유닛을 import 하므로 받아들여질 수
없다 -- 마커를 붙이고 이유를 적었다.
2026-08-17 05:06:16 +09:00
coolguy 96e05aba5b refactor: 빌드 전체를 하나의 검사기로 본다
유닛마다 FeCheck 를 새로 만들면 타입 문맥도 유닛마다 따로 생겨서 유닛 경계를
넘는 이름을 볼 수가 없었다. 검사기가 빌드 전체를 맡고, 모든 유닛의 선언을
등록한 뒤에 어느 본문이든 보기 시작한다.

스코프와 심볼과 타입은 현재 유닛보다 오래 살아야 하므로 AST 아레나가 아니라
검사기 자신의 아레나에서 잡는다. 이름이 같아도 유닛이 다르면 다른 타입이므로
nominal 타입은 선언한 유닛으로도 구분한다.

pub 은 파서가 버리고 있었다. 이제 FE_NODE_PUB 으로 남긴다.
2026-08-17 05:00:31 +09:00
coolguy de02b8bbbe tests: bad_bufw 가 무엇을 막는지 기록하고 진단을 고정한다
보고서가 '애매'로 남긴 하나다. io.buf_writer 는 351e5db 가 Writer 핸들 enum
으로 교체하면서 없앤 콜백 방식 writer이고, 이 fixture 는 그것이 돌아오지 않게
막으려고 그 커밋에서 추가됐다. 파일만 봐서는 알 수 없어 주석으로 남긴다.

pin 94 -> 95. 마커 없는 fixture는 이제 없다.
2026-08-17 04:52:48 +09:00
coolguy 1be47fa11c tests: 마커 없던 fixture 36개에 진단을 고정한다
마커가 없으면 러너는 '거부되기만 하면 통과'로 판정한다. 엉뚱한 이유로
거부돼도 초록이었다. fixture 별로 무엇을 검사하는지 읽고 지금 나오는 진단이
그 규칙을 짚는지 확인한 뒤 줄과 문구를 고정했다. 근거는 fixture-report.md에
있다.

pin 58 -> 94. 통과 수는 150/188 그대로다.
2026-08-17 04:51:58 +09:00
coolguy c7d0a900bd fix: 남은 중복 진단 두 건을 정리한다
format 검사는 인자가 떨어진 자리에서 개수 불일치를 말하고 문자열을 다 훑은
뒤 같은 말을 또 했다. aggregate storage 검사는 M7 쪽이 optional 뒤의 참조를
보려고 도는 김에 평범한 &T 필드까지 잡아서, 뒤이어 도는 M6 검사와 겹쳤다.

fixture 전수 검사 결과 --check 경로에 중복 진단이 남아 있지 않다.
2026-08-17 04:51:19 +09:00
coolguy f5bffec7dd fix: 같은 위반을 두 번 보고하던 두 경로를 정리한다
이동한 값을 쓰면 진단이 두 번 나왔다. 원인이 둘이다. 식별자를 읽으면
FE_OWN_READ 가 이미 보고하는데 mark_moved 가 FE_OWN_MOVE 로 같은 자리를 다시
보고했고, member lvalue 는 check_lvalue 가 base 를 검사한 뒤 check_lvalue_core
가 또 검사했다. M6/M7 두 검사기를 합칠 때 남은 자국이다.

러너는 진단의 첫 줄만 마커와 대조하므로 fixture 188개가 이것을 잡지 못했다.
2026-08-17 04:49:05 +09:00
coolguy c900e0f61c spec: 640KB 셀프호스팅을 목표에서 내린다
철학 2의 근거가 사실과 달랐다. 전역 분석 금지만으로는 메모리가 줄지 않고,
현재 프론트엔드는 이미 그 예산을 한 자릿수 넘겼다 — FeBuild 하나가 26,892바이트
스택 지역 변수이고, 유닛 64개의 소스와 AST를 동시에 들고 있다.

전역 분석 금지는 국소적 진단과 작은 컴파일러라는 자체 근거로 유지한다.
컴파일러가 도는 곳을 §2.1로 분리했다. bits16 타깃은 그대로다 -- 8086용
프로그램을 만드는 것과 8086에서 컴파일러를 돌리는 것은 다른 일이다.
2026-08-17 04:39:58 +09:00
coolguy 2f140e1e48 fixture 진단 증거 보고서 작성 2026-08-17 04:30:45 +09:00
coolguy 5217c352b0 docs: AGENTS에 남은 옛 참조를 정리
사라진 tools/README.md, SPEC.AUDIT.md, pytest, 없는 --keep-failed 플래그를
가리키고 있었다. 마일스톤 언급도 뺀다.
2026-08-17 04:21:52 +09:00
coolguy 7636a41a4e Revert "tests: fixture 파일명과 unit 동기화"
밑줄만 제거하고 충돌한 이름에 숫자를 붙인 결과라 이름이 무엇을 검사하는지
오히려 덜 드러낸다. own/badfld 와 types/badfld 가 서로 다른 것을 검사하는데
둘 다 badfmem 이 된 것이 그 증거다. 파일을 열어 판단하는 작업이므로
마커 판정과 함께 다시 한다.
2026-08-17 04:21:13 +09:00
coolguy 43646647af docs: AGENTS를 프런트엔드 전용 상태로 갱신 2026-08-17 04:14:37 +09:00
coolguy 79aa2208f1 tests: pending-backend README 추가 2026-08-17 04:14:35 +09:00
coolguy d22964cdb6 tests: fixture 파일명과 unit 동기화 2026-08-17 04:14:30 +09:00
coolguy fe5f853feb grammar.js를 parser 기준 규칙으로 정합화 2026-08-17 04:05:15 +09:00
coolguy 88b0c83538 fixture README를 현재 상태에 맞게 정리 2026-08-17 04:05:13 +09:00
coolguy d1a4020087 own fixture 파일명과 unit 식별자 정리 2026-08-17 04:05:11 +09:00
coolguy 38dddc234c implement: load the unit graph -- imports, cycles, bindings
The driver handled one file. It now loads the graph rooted at the entry file
and checks every unit in it.

The import root is derived rather than configured: a unit named `a.b` read
from `<root>/a/b.fe` fixes `<root>`, so a sibling `import c.d;` is looked for
at `<root>/c/d.fe`. That is enough for the fixtures and for any tree that
follows 8.1, and it means there is no path flag to get wrong yet.

Loading is depth-first with the chain of units currently open kept on a stack,
so meeting one again is a cycle rather than a revisit -- a unit reached twice
by different paths is loaded once. Cycles, imports with no source file, and two
imports claiming the same binding are all reported.

One thing this exposed: FeDiags held a single source buffer, so once a build
spanned several files every excerpt was drawn from whichever file was parsed
last. `cycle/b.fe:3` printed the text of a.fe. fe_diags_source switches it, and
loading and checking both set it per unit.

The cycle fixtures lost their line markers on purpose. Which import closes the
cycle depends on which file you enter from -- entering at a.fe reports b.fe,
entering at b.fe reports a.fe -- so pinning a line would pin an arbitrary half
of a symmetric pair. The message is pinned; the line is not.

units: missing, bindconf and cycle pass, on top of the identity cases.
146 -> 148 of 188. What is left in units/ needs cross-unit name resolution and
visibility: an importer still cannot see `util.answer`.
2026-08-17 03:54:43 +09:00
coolguy 51e2568ba7 implement: unit identity -- dotted paths, name rules, source path
Units start here, with the part that needs no import graph: what a unit is
called and where it must live.

The parser only ever read a single identifier after `unit` and `import`, so
`unit game.main;` and `import std.io;` were syntax errors -- which is why the
dotted fixtures failed at the semicolon. It now reads a dotted path and stores
it canonically, dots included, since that spelling is the unit's identity
everywhere else. `import a.b as c;` parses too, with the alias on the node.

resolve.c is the new pass between parsing and checking, for the questions that
span files. It carries SPEC 8.1 so far: each path segment is ASCII lowercase,
starts with a letter, continues with letters, digits or underscore, and is at
most eight characters; and the dotted path must match the source path it was
read from, so game.world.map has to come from game/world/map.fe. The source
side is folded to lowercase before comparing, because a case-insensitive host
must not let two spellings become two units.

That rule then applied to the fixtures, which were not obeying it: 57 declared
a unit name unrelated to their file, left over from the milestone directories,
and eight had names too long to be legal. Both are now aligned -- the rule is
worth having only if the tree follows it.

units: badupper, badlong and unitbad pass. 138 -> 146 of 188. The rest of
units/ needs the import graph, which is the next piece: resolution, cycles,
bindings and visibility.
2026-08-17 03:47:28 +09:00
coolguy 547d8c5ec2 fix: reconcile the ERROR markers with what the checker reports
Checking the markers for the first time found five disagreements in areas that
are implemented. Four were the marker's fault:

- own/badarg pinned "self", but the rule being broken is that a returned
  reference must derive from a parameter -- `self` has nothing to do with it.
- own/badbrmov pinned line 9, which is the closing brace; the second destroy is
  on line 8.
- own/badloop pinned line 8, the destroy after the loop. The diagnostic is on
  line 6, inside it, and line 6 is right: the second iteration moves the same
  value again, so the loop body is where it is caught. Whoever wrote the marker
  expected the error after the loop.
- optional/badcatch pinned line 14, the body of the catch block. The catch
  expression on line 13 is what cannot fall through.

The fifth was the compiler's. own/badweak assigns a `&mut i32` to a `&i32` and
got "initializer type mismatch", which says nothing about why. Weakening an
exclusive borrow to a shared one is a specific rule and now says so, for
references and slices alike.

own/ is fully green: 50/50. Overall 133 -> 138 of 188. The six remaining marker
disagreements are all under units/ and generic/, where nothing is implemented
yet, so there is no diagnostic to compare against and no way to tell whether
the marker is right.
2026-08-17 03:42:06 +09:00
coolguy fb65152901 refactor: keep the front end, drop everything downstream of it
The milestone structure had stopped describing the compiler and started
shaping it: m7.c, check_m7.c, tests/m2..m9, and a checker and emitter that had
each grown past 2,500 lines because there was nowhere else to put anything.
Restart from the pipeline instead.

What is left is the front end -- lexer, parser, types, ownership, semantic
analysis -- and the fixtures that describe it. The C backend, the DOSBox-X
runner, the milestone registry and the batch build are removed. The driver now
stops after semantic analysis; a code generator attaches where emit_c did.

Fixtures move from milestone directories to what they check:

    parse/     grammar            own/       ownership and borrowing
    types/     type rules         optional/  optionals and error unions
    format/    formatting, try    units/     units and visibility
    generic/   generics           pending-backend/

pending-backend/ holds the three fixtures that can only be checked by running
a program -- that the bounds check traps, that --no-checks removes it, and that
drops and defers actually fire, verified through a fake allocator. Those are
not front-end tests and are not pretending to be; they come back first when
there is a code generator.

tests/run.py replaces the DOSBox-X harness. It builds the front end with the
pinned Watcom's Windows-hosted driver and runs every fixture in about two
seconds, and it does something the old runner structurally could not: it reads
the `// ERROR:line:text` marker each fixture carries and checks the diagnostic
against it. Those markers have been in the tree all along, unverified, because
DOS could not redirect the compiler's stderr and only the exit code was ever
compared.

133/188 pass. The 55 failures are not regressions -- they are what was already
true and invisible:

- units (27) and generic (23): `import`, `comptime` and generic declarations
  parse and are then dropped on the floor. No pass looks at them. The old
  registry did not list these fixtures at all, so nothing said so.
- five in own/, optional/ and generic/: a marker disagrees with the diagnostic
  about the line or the wording. Each is either a wrong marker or a wrong
  diagnostic and has to be read individually.

Everything removed is in git history.
2026-08-17 03:33:23 +09:00
coolguy 2696dd2abc docs: reduce SPEC.md to a language-only specification
Abandon the milestone-driven organisation of SPEC.md. The document now
contains only design philosophy (§1) and the language specification
proper (lexical structure, types, ownership/borrow rules, grammar,
semantics, module/unit semantics, and the minimal stdlib surface the
language itself depends on).

Removed:
- All milestone content (M1-M12: descriptions, completion criteria,
  ordering) and the roadmap/schedule framing.
- Compiler implementation directives: bootstrap strategy, pipeline,
  directory layout, C emission rules, own.c algorithm (§11 in full).
- Test/fixture plans and pass/fail/run16/boot fixture listings (§12
  in full).
- Build-driver/tooling detail that isn't part of the language itself:
  import-root search and ambiguity resolution, .fei cache/hash format,
  the full CLI flag reference table, C-backend evaluation-order
  lowering notes, and the generic-instance C emission ordering.
- SPEC.AUDIT.md entirely (git rm) — the accumulated change log for the
  old milestone-driven spec no longer applies.

Kept and reorganised: §2-§9 (targets, lexical structure, type system,
ownership/borrow rules R1-R11, grammar, statement/expression
semantics, unit/import/visibility semantics, generics) are otherwise
unchanged in wording. §10 (stdlib) is now a short placeholder noting
the stdlib spec is pending, while retaining the minimal surface the
language rules and builtins directly reference (core.Error, str alias
methods, mem.replace/create/destroy/alloc_slice, io.Writer/Reader,
fmt.fmt_*, sys.exit/on_exit). §13 (excluded features) is renumbered to
§11 and kept as-is since it documents language-design decisions, not
implementation.

AGENTS.md's document map is updated to drop the SPEC.AUDIT.md row and
reflect that SPEC.md is now language-only.

Implementation and stdlib specs are intended to be written as separate
documents going forward.
2026-08-17 02:42:12 +09:00
coolguy d5ba699744 dev: require the pinned toolchain, and clear the QEMU-era leftovers
The host gate accepted a WATCOM environment override and skipped when nothing
was found. Both are wrong for what it is: a system-wide Open Watcom is a
different version reporting different diagnostics, and a gate that skips is a
gate that is not running, which is the exact shape of the problem this file was
added to close. It now uses .dosboxx/watcom only and fails with the setup
command when that is absent, matching how dosboxx.py already behaves.

Nothing else in the project reaches for a system install: the DOS session sets
WATCOM=W: before calling BUILD.BAT, so the C:\DEVEL\WATCOMC fallback inside it
is unreachable.

fec/test-dos.bat was tracked but dead -- the runner generates RUN.BAT and only
copies build-dos.bat -- so it goes, along with the comment claiming it drives
the build and the three fixture READMEs that still pointed at it. The registry
decides what runs now.

(.qemu/ is untracked local debris from the same era and is left alone.)
2026-08-17 02:26:02 +09:00
coolguy 32ad50b14a dev: run the host gate as 16-bit, and drop what it found dead
The gate was using a system-wide Open Watcom that only ships the 32-bit
compiler. The project downloads its own toolchain, and .dosboxx/watcom/binnt
has the Windows-hosted 16-bit wcl.exe -- the same compiler and the same target
as the DOS build. Run that instead, with build-dos.bat's exact command.

The difference is not academic. Compiling 16-bit immediately reported three
functions the unification had orphaned: emit_type_helpers, which the M7
program emitter replaced, and emit_drop_helpers and emit_drop_fields, which it
was the only caller of. The 32-bit check had been clean.

Those warnings were going to the DOS screen, where the runner cannot see them:
COMMAND.COM redirects handle 1 only, and Watcom writes diagnostics to handle 2.
So the suite was green while the build was not quiet. Nothing in the runner
would ever have said so.

Found while chasing W210/W107 reported from a DOS screen, which this does not
yet explain -- those are not among what the compiler build emits now.

M1-M7: 214 passed.
2026-08-17 02:22:44 +09:00
coolguy ee2b417013 fix: restore the rules the M7 half never had to implement
Unifying the two engines exposed what the split had been hiding: every rule
that lived only in the M6 body was silently dropped for units the M7 half
claimed, and since M1-M6 sources never reached that half, nothing failed until
they all did. Eleven cases across m3, m5 and m6 caught it.

Checker, all from the M6 statement and lvalue cases:

- writing a struct field needs a writable place, so `p.x = 3` on a `let` is an
  error again (m3-badfield)
- `let` cannot bind a mutable slice, a var with no initializer needs a type,
  and a void expression cannot initialize (m3-bad-mlet)
- a returned reference must derive from a parameter or a static, and a void
  expression cannot be returned from a value function (m6-badarg, badret,
  badself, badtwo, badlocsl)
- rebinding a reference must not outlive its source scope, and must release the
  previous borrow (m6-badscop)
- the loop case delegates to the core, which carries the flow capture and merge
  that detects a value moved on every iteration; the M7 version had none of it
  (m5-bad-loop)

Emitter:

- builtins other than the print family (@size_of, @align_of) and the str alias
  methods are lowered by the core, which the M7 call path never reached, so
  they were emitted verbatim into the C (m3-struct)
- the trim helper is emitted from the M7 type-helper pass as well, not only the
  core one, or the call has no definition to link (m6-oktrim)

M1-M7 all green: 16, 19, 50, 20, 16, 57, 42.
2026-08-17 02:07:26 +09:00
coolguy eb85e9fa3d dev: run host syntax gates before starting DOSBox-X
There is an Open Watcom install on this host (C:\WATCOM19), and its Windows
build compiles the compiler's own sources in about a second. Every declaration
mismatch in the unification commits was found that way; each one would
otherwise have cost a DOSBox-X boot and a full compiler build to surface, with
a DOS-side message that names the wrong thing.

Add tools/tests/test_host_syntax.py: compile all twelve sources with the flags
build-dos.bat uses (-za -wx -wcd=202) and fail on any diagnostic. It skips when
Watcom is absent, so the suite still runs elsewhere. Two structural checks come
with it -- that build-dos.bat, the Makefile and the test agree on the source
list, and that no .c under fec/src is compiled by nothing. Both would have
caught check.c and emit_c.c quietly leaving the build when the M7 wrappers
included them textually.

ferro-test now runs these and the 8.3 name check before starting the VM, and
stops if they fail.

This is not verification and does not claim to be: wcc386 targets 32-bit where
the real build is 16-bit large model, so it sees syntax, types and declarations
and nothing about code generation. The DOS build and the milestone suite remain
the gate. It only moves the cheap failures earlier.
2026-08-17 01:57:06 +09:00
coolguy 4adfe60574 fix: repair the unified emitter's declarations
Compiling the merged sources with the Open Watcom install on this host
(C:\WATCOM19\binnt) found four things the merge got wrong, none of which any
amount of reading would have caught reliably:

- FE_M7_FLOW_CAP and <stdlib.h> lived in check_m7.c's preamble, above the
  textual include, and were dropped with the wrapper.
- emit_error_return takes a const char *, not a FeNode *; the hand-written
  forward declaration disagreed with the definition.
- emit_match was never defined by the M7 half, only called, so renaming it
  alongside the other delegating pairs left a declared-but-undefined static.
- type_needs_drop and emit_lvalue are used a few hundred lines before the
  declaration block, so their declarations had to be hoisted.

Also drop two locals that existed only to be cast to void.

All twelve compiler sources now compile with -za -wx -wcd=202 and produce no
warnings. That is a syntax and type check, not verification -- the DOS build
and the milestone suite remain the gate.
2026-08-17 01:54:17 +09:00
coolguy 3b8c8ac674 refactor: unify M7 lowering and C emission
emitcm7.c was the same wrapper trick as the checker: nineteen #define renames,
a textual include of emit_c.c, and a per-unit feature scan choosing between two
emitters. Five of the M7 halves fell through to their M6 counterpart, so those
become the single entry point with the old body renamed to *_core; the other
thirteen never delegated at all and simply replace the M6 version.

The scan is gone from both places it was used -- the program entry and the
expression emitter, whose switch already ended in a default that delegates.
fe_emit_c_program_core went with the dispatch that was its only caller.

emitcm7.c is deleted and the build compiles emit_c.c directly. Nothing in the
compiler now selects an implementation by looking for `?` or `!` in a unit.

This is the pair to the checker commit; together they end the two-engine split
that produced four of the five defects fixed while getting M7 to pass.
2026-08-17 01:49:02 +09:00
coolguy 3091df7a78 refactor: unify the M1-M7 checker
check_m7.c textually included check.c, renamed three entry points aside, and
selected between two whole checkers by scanning each unit for `?`, `!`, `try`
and friends. A unit that mentioned any of them was checked by a second
implementation, so an M1-M6 rule fixed in check.c never reached it -- and the
split hid real defects, since the M7 half was reached by no existing fixture
until M7 cases were registered.

The split was cheaper to undo than it looked: every M7 dispatcher already
delegated to its M6 counterpart for nodes it did not handle. So the M7 entry
points become the single check_expr/check_stmt/check_lvalue/check_call, and
the former M6 bodies become check_expr_core/check_stmt_core/check_lvalue_core,
reached as the fallback. Recursion runs through the unified entry, which is
what makes an optional nested inside otherwise-M6 code get checked at all.

m7_check_fn and m7_check_method were identical to the M6 versions apart from
which check_stmt they called, so they are dropped. The feature scanner
(m7_type_ast, m7_node_feature, m7_program_feature) is gone with the dispatch
it fed, including the loop case that still consulted it. fe_check_program and
fe_check_expr_type keep the M7 bodies, which are supersets.

The build compiles check.c directly again.

No behaviour intended to change: the unified checker applies the union of the
rules to every unit, which for M1-M6 sources is what the M6 half already did.
2026-08-17 01:45:04 +09:00
coolguy d5e7a8d8d6 dev: restore core=dynamic; the trap failures were the PATH bug
The previous commit blamed core=dynamic for the M3 bounds cases exiting 0
instead of trapping. That was wrong. Both suspects were live at the time --
the recompiler and a cache hit that skipped BUILD.BAT's `set PATH` -- and the
core was ruled out before the PATH line was restored, so the test proved
nothing.

Retested with the PATH fix in place: core=dynamic gives 50 passed on m3, the
traps included. abort() reports its exit status fine under the recompiler.

Per milestone, warm cache, all green:

    m1  2s   m2  3s   m3  7s   m4  3s
    m5  3s   m6  6s   m7  5s        29s total

against 65s on the interpreter.
2026-08-17 01:36:48 +09:00
coolguy 0132ad4135 fix: lower short catch as statements, and drop core=dynamic
Compiling okcatmov.fe's output crashed wcc386 hard enough to take DOSBox-X
down with it -- "no byte handler for write to ffffffc", emulator exit 1, the
whole suite lost rather than one case failing. `result catch fallback` in
return position lowered to `((tmp = X), tmp.e ? fallback : tmp.v)`, and with a
moved operand X is itself `(fe_live_x=0, x)`, so the compiler met a struct
assignment whose right side was a comma expression. Lower it as statements,
and clear a move flag on its own line rather than inside the assignment.

Revert core=dynamic from the previous commit. It was about 5x faster and it is
wrong: the recompiler loses abort()'s exit status, so a trapping program exits
0 and the M3 bounds cases stop reporting the trap they exist to prove. Checked
against a compiler built under core=normal, so the fault is in running the
generated program, not in building the compiler.

Also fix the build cache: BUILD.BAT puts the Watcom binaries on PATH, and
skipping it on a cache hit left the case commands without it, which silently
changed how the trap programs terminated. Reproduce that line.

Per milestone, warm cache: m1 2s, m2 5s, m3 20s, m4 7s, m5 6s, m6 14s, m7 11s.
All green, 220 cases.
2026-08-17 01:34:20 +09:00
coolguy 044c0f0e98 dev: cache the compiler build and drop unused headers
Every run rebuilt fec from scratch inside DOS, about 14 seconds, even when no
source had changed. Key a cache on the hash of fec/src plus build-dos.bat and
restore FEC.EXE when it matches; the toolchain itself is pinned by
dosboxx.lock.json so it cannot drift under a hit. Only a passing build is
cached, and the batch skips BUILD.BAT on a hit because it would delete and
rebuild the executable it was just given.

Generated C included stdio.h unconditionally, but only the M4 writer runtime
reaches it. A 26-line unit was pulling in roughly 1900 lines of headers, paid
once per compile check. Emit it only when the runtime is emitted.

--only m6, 57 passed, over three changes:

    31s   before
    17s   core=dynamic
     2s   warm compiler cache

Cold runs still pay the build once.
2026-08-17 01:17:40 +09:00
coolguy aaf31302d5 dev: compile the generated C, and fix what that caught
Thirty-one cases only ever emitted C and never built it -- m5 owned/defer, and
every ok* acceptance fixture in m6 and m7. They asserted that fec produced a
file, not that the file was a program, so a malformed emission sat unnoticed.
Compile each one with wcl386 -c. Fixtures without a main cannot be run, so this
is the floor for them; it is a conformance check on the backend's output, not an
assertion about C, so a future backend swaps the command rather than the intent.

It found two defects in the M6 emitter immediately, both predating M7:

&s[0] took the address of an rvalue. Borrowing went through emit_expr, which
lowers an index to the bounds-checking accessor, so `&s[0]` became
`&fe_idx_slice_type_2(s, 0)`. emit_lvalue spells the same element as `s.p[0]`.
The M7 emitter already did this correctly; only the M6 path was wrong.

line.trim() was never lowered. SPEC lists trim among the built-in alias methods
on str and the checker accepts it, but no emitter case existed, so it emitted
`fe_l_line_0.trim()` -- a member access on a slice struct. Emit the helper, and
only for programs that actually trim.

Also set core=dynamic and cycles=max. core=auto uses the interpreter in real
mode, which is where the 16-bit compiler build spends its time; nothing here is
timing sensitive. m6 drops from 31s to 17s. Raise the DOSBox timeout to match a
whole-suite run, which now pays a process spawn per compile check.

Verified: --only m6, 57 passed.
2026-08-17 01:14:47 +09:00
coolguy 23079ba9fb spec: mark the try enforcement entry resolved by M7 2026-08-17 00:03:26 +09:00
coolguy a2428ca5da fix: enforce the try rule at every position
SPEC.md allows `try` only inside a function returning an error union, but the
check sat in the FE_N_EXPR_STMT case, so it only ever saw a bare `try e;` and
walked past `var x = try e;` and `x = try e;`. Move it onto the try expression
in check_expr and drop the statement-level copy.

This could not land before M7: closing the hole forces m5/runtime.fe's `run` to
return an error union, and value returns from `-> !T` need contextual success
construction. That arrives with M7, and `run` is now `-> !i32`, so the rule can
be enforced. Supersedes the SPEC.AUDIT.md entry that recorded the blockage.

M1-M7: 183 passed.
2026-08-17 00:03:26 +09:00
coolguy 6713a934f5 fix: emit mem.create and mem.alloc_slice on the M7 path
m7_emit_call reimplements call emission and only carried over mem.destroy and
mem.replace, so every mem.create/mem.alloc_slice fell through to the generic
member path and emitted `fe_missing.create(0)`. wcc386 does not diagnose that
-- it terminates with exit 255, which wcl386 reports as "Unable to invoke
wcc386.exe" with no message at all.

The breakage covered all 17 allocation sites in m5/runtime.fe, and it was
invisible because m5-owned and m5-defer only emit C; m5-runtime is the one M5
fixture that compiles and links what was generated.

Also make runtime.fe legal: `run` used `try` while returning i32, which SPEC
allows only in a function returning an error union. It is `-> !i32` now, which
M7 accepts because contextual success construction lands with it, and
runtime.c takes the { error, value } struct the error union lowers to.

Found by calling wcc386 directly instead of through wcl386, which is the only
way to see a compiler crash here.

M1-M7: 183 passed.
2026-08-17 00:01:51 +09:00
coolguy 44dc5562ef fix: repair three M7 C emission defects
emitcm7.c reimplements the emitter for sources that mention M7 syntax, and
three things were lost in the port. All of them only reached M4 fixtures,
because M1-M3 and M6 take the M6 fast path.

Local initializers named "0". The LET/VAR case passed the declaration node to
emit_lvalue, which matches only IDENT/MEMBER/INDEX and otherwise falls through
to the raw expression path -- a declaration node renders there as "0", so every
`var x = init;` emitted `0 = init;`. Teach emit_lvalue that a declaration names
its own storage, which also fixes the catch path that had the same call.

Aggregate initializers were not constant. A string-literal `const` lowered to a
maker call, but C89 requires a constant expression for aggregate initializers
at file scope and for automatics alike, and the build runs with -za. Restore
the braced form for both the local and the global path.

Slice helpers were never emitted. The final loop in m7_emit_type_helpers is
commented as reusing the M3 index/slice generator but only ported the index
half, so bodies called fe_slice_*/fe_full_*/fe_tail_* that no declaration
defined. Emit the three slicers for array and slice types.

The first defect masked the other two: wcc386 died on `0 = ...` before it could
reach them, and wcl386 reports that as "Unable to invoke wcc386.exe" with no
diagnostic, which is why this needed bisecting against master's output rather
than reading an error message.

M1-M7: 7 failed, 176 passed -> 3 failed, 180 passed. The remainder is m5
runtime, which is a separate fixture issue.
2026-08-16 23:48:18 +09:00
coolguy 05ae2bea9a fix: unblock the DOS build for M7 sources 2026-08-16 23:39:05 +09:00
coolguy ff98176cc2 Merge branch 'master' into m7-trial 2026-08-16 23:30:36 +09:00
coolguyandClaude Opus 5 0a434d8a9a spec: record why the try rule cannot be enforced yet
SPEC.md allows `try` only inside a function returning an error union, but
check.c only tests it in the FE_N_EXPR_STMT case, so `var x = try e;` and
`x = try e;` walk straight past. m5/owned.fe and m5/runtime.fe both depend on
that gap.

Moving the check onto the try expression is a four-line change and it is
correct, but it cannot land yet. runtime.fe's `run` allocates and returns a
value, so closing the hole forces it to return an error union -- and master
rejects `return <value>;` in `-> !i32` ("return type mismatch") as well as a
bare `return;` in `-> !void` ("void expression returned from value function").
Both need contextual success construction, which is M7 work. `catch` and
`@trap()`, the two spellings SPEC offers as alternatives, are also M7-only, so
there is no way to express `run` legally on master today. All three paths were
tried in DOSBox-X, not assumed.

Fix owned.fe now, since `main() -> !void` is legal today and matches
m4/try-fpr.fe, and leave the checker alone until M7 lands with the rest.

Verified: 155 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BScg8CF1sAAM2zVHAu5zvW
2026-08-16 23:23:47 +09:00
coolguy 9e074e2e16 Merge branch 'master' into m7-trial 2026-08-16 23:09:39 +09:00
coolguyandClaude Opus 5 86bff9a06d dev: capture compiler diagnostics under DOS
Every fec error message was written to stderr, and COMMAND.COM can only
redirect handle 1 -- ">" is the whole vocabulary, "2>" is not parsed at all.
So a failing compile recorded exit code 1 and a zero-byte log, and the actual
message went to a screen nobody reads. Confirmed directly: `FEC.EXE --check`
on a fixture that must fail produced rc=1 and 0 bytes of stdout.

That is why an unexpected compiler failure was undiagnosable. It also means
the M6 reject cases have only ever asserted "exit code was nonzero" -- the
error text they nominally check has never been observable to the runner.

Add fe_diag_stream(), which resolves once to stdout when FE_DIAG_STDOUT is set
and stderr otherwise, and route diag.c and driver.c through it. The default is
unchanged, so interactive use keeps writing to stderr; the runner sets the
variable in RUN.BAT. The stderr references in check.c and emit_c.c are the
Ferro language's own std.io.stderr writer and are deliberately untouched.

Verified in DOSBox-X: 155 passed. A rejecting compile now records its message,
source excerpt and caret in RESULTS\<key>.LOG.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BScg8CF1sAAM2zVHAu5zvW
2026-08-16 23:09:30 +09:00
coolguy e457ee46b2 Merge branch 'master' into m7-trial 2026-08-16 23:02:43 +09:00
coolguy 7a25447281 trial: unblock the DOS build (local only, not for merge) 2026-08-16 23:02:43 +09:00
coolguyandClaude Opus 5 8b7d6a8d09 dev: make DOS build failures diagnosable
Reviewing an M7 branch took six DOSBox-X runs to find three build blockers
that each take a second to explain. The runner threw away everything needed to
see them.

Capture the compiler build's output. Case commands were redirected to
RESULTS\<key>.LOG but `call BUILD.BAT` was not, so the step that fails first
and blocks every case left only BUILD.FAIL containing the string "FAIL". The
twelve wcl invocations inside it were invisible; finding "Unable to open
src\emit_c_m7.c" meant hand-editing build-dos.bat to add a redirect and
re-running the VM.

Record exit codes. The batch collapsed every outcome to `if errorlevel 1`, so
a compiler that aborted and one that exited 1 with a diagnostic were the same
FAIL. RC.BAT now walks a descending errorlevel ladder into RESULTS\<key>.RC
and the host derives pass/fail from it, which immediately separates an
ordinary rejection (1) from a trap (255). Note the space in `echo 0 >FILE`:
without it DOS parses `0>` as a redirect of handle 0.

Stop falling back to CONSOLE.LOG. That is DOSBox-X's own log -- display
enumeration and INT15 chatter -- so a crashed command reported fifty lines of
emulator noise instead of saying it produced no output.

Add tools/tests/test_dos_names.py. An over-long source name reaches the DOS
build as `Unable to open "src\..."`, which reads as a missing file rather than
a name FAT cannot represent, and only after a VM boot and ten object builds.
The check runs on the host in 0.03s and flags emit_c_m7.c (9-character stem)
on the branch that prompted this.

Also pass -k through to pytest so a single case can be re-run without its
whole milestone, and print the resolved ROOT at startup: an editable install
plus a git worktree will otherwise silently build a different checkout than
the one the shell is in.

Verified on master: 155 passed, unchanged. Recorded codes are 0 for success,
1 for rejections, 255 for the three bounds traps.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BScg8CF1sAAM2zVHAu5zvW
2026-08-16 23:02:28 +09:00
coolguy 63bc8e8724 Merge branch 'master' into m7-trial 2026-08-16 22:37:51 +09:00
coolguyandClaude Opus 5 5529e3dc14 test: prove --no-checks removes the bounds check
The bounds-no-checks cases emitted and built but never ran, so they only
proved that --no-checks produces compilable C -- not that it removes the
check, which is the entire point of the flag.

A run case could not simply be appended. BOUNDS.FE returns the out-of-bounds
element directly, so with checks removed its exit code is whatever sits past
the array on the stack and there is no correct status to assert. Asserting on
the generated C instead does not work either: emit_c.c defines fe_trap_bounds
unconditionally and --no-checks only suppresses the call sites.

Add NOCHK.FE, which reads one element past a [2]i32 and returns x - x. That
is 0 for whatever garbage the unchecked read produced, so the same source has
a defined outcome both ways: compiled with checks it must trap, compiled with
--no-checks it must run to completion and exit 0. Register both halves and
drop the two BOUNDS-N cases they supersede.

Verified in DOSBox-X: 155 passed, including m3-nochk-trap failing as expected
and m3-nochk-off-run succeeding.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BScg8CF1sAAM2zVHAu5zvW
2026-08-16 22:23:41 +09:00