ast-visitor-pattern
하는 일
동결된 클래스와 비지터를 사용해 관련 타입을 구조화하고, 그것을 처리하는 모든 곳이 검사되도록 안내합니다. 커지는 switch 문을 다루는 TypeScript 개발자를 위한 스킬입니다.
사용하는 경우
- ✓같은 변형 집합이 렌더러나 직렬화기처럼 두 곳 이상에서 처리될 때.
- ✓이미 여러 곳에서 switch 되는 타입에 새 변형을 추가할 때.
- ✓유니온 타입이 커져서 switch 문을 일관되게 유지하기 어려운 경우.
스킬 링크
https://github.com/prisma/orm/blob/main/skills-contrib/ast-visitor-pattern/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“이 유니온 타입과 switch 문을 리팩터링해서 빠진 케이스를 컴파일러가 잡도록 해 주실 수 있나요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
에이전트는 각 변형을 accept 메서드가 있는 동결된 클래스로 바꾸고, 모든 소비자가 구현해야 하는 비지터 인터페이스를 정의합니다. 그러면 비지터가 갱신되지 않은 곳마다 새 변형 추가 시 컴파일 오류가 납니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
AST Class/Visitor Pattern
When a discriminated union has 3+ variants and 2+ dispatch sites (renderers, serializers, classifiers, etc.), replace plain union + switch with frozen subclasses and a visitor interface. This makes adding a new variant a compiler error at every consumer, instead of a silent omission.
Structure
Four pieces, usually in one file — the Mongo DDL set below spreads them over three:
// 1. Abstract base (not exported — consumers use the union type)
abstract class FooNode {
abstract readonly kind: string;
abstract accept<R>(visitor: FooVisitor<R>): R;
protected freeze(): void { Object.freeze(this); }
}
// 2. Visitor interface
export interface FooVisitor<R> {
bar(node: BarNode): R;
baz(node: BazNode): R;
}
// 3. Concrete subclasses — readonly fields, freeze() in constructor
export class BarNode extends FooNode {
readonly kind = 'bar' as const;
readonly value: string;
constructor(value: string) {
super();
this.value = value;
this.freeze();
}
accept<R>(visitor: FooVisitor<R>): R { return visitor.bar(this); }
}
export class BazNode extends FooNode {
readonly kind = 'baz' as const;
readonly count: number;
constructor(count: number) {
super();
this.count = count;
this.freeze();
}
accept<R>(visitor: FooVisitor<R>): R { return visitor.baz(this); }
}
// 4. Union type
export type Foo = BarNode | BazNode;
Consuming
Define a visitor object (or class) per concern:
const renderVisitor: FooVisitor<string> = {
bar(node) { return node.value; },
baz(node) { return String(node.count); },
};
function render(node: Foo): string {
return node.accept(renderVisitor);
}
Always construct instances, never frozen object literals
This holds everywhere a node is built — tests and production construction surfaces (contract-free factories, builders). A factory must return new BarNode(...), never Object.freeze({ kind: 'bar', value: 'x' }). A frozen plain object has no prototype, so instanceof fails, accept() is missing, and a downstream shallow-copy ({ ...node }) silently strips the type back to an anonymous bag; constructor-time invariants are skipped too.
// ✅
const call = new BarNode('x');
export function bar(value: string): BarNode { return new BarNode(value); }
// ❌
const call: Foo = { kind: 'bar', value: 'x' };
export function bar(value: string): Foo { return Object.freeze({ kind: 'bar', value }); }
When NOT to use
- Single dispatch site → plain union + switch is simpler
- Fewer than 3 variants with no expected growth → not worth the boilerplate
Codebase examples
MongoAstNodebase —packages/2-mongo-family/4-query/query-ast/src/ast-node.tsMongoDdlCommandVisitorinterface —packages/2-mongo-family/4-query/query-ast/src/ddl-visitors.ts- Concrete DDL commands and their union —
packages/2-mongo-family/4-query/query-ast/src/ddl-commands.ts
자주 묻는 질문
이 패턴은 언제 가치가 있나요?
스킬은 유니온에 변형이 세 개 이상이고, 그것에 대해 switch 하는 곳이 두 곳 이상일 때 이 패턴을 제안합니다.
예시는 어떤 언어인가요?
예시는 TypeScript로 되어 있으므로, 이 패턴도 TypeScript 코드를 기준으로 작성되어 있습니다.
컴파일러는 무엇을 확인하나요?
새 변형을 추가하면 처리하지 않은 모든 소비자에서 오류가 나므로, 조용히 놓치는 일이 없습니다.
상세 정보
작성자의 원본 설명
Use the frozen-class/visitor pattern for discriminated unions that have multiple dispatch sites. Use when creating a new set of variants (commands, IR nodes, factory calls) that will be switched over in 2+ places, or when refactoring an existing union type that has grown multiple switch sites.
repo: prisma/orm
인기도
- GitHub 스타
- 48k
- 순위
- #6309
- 라이선스
- Apache-2.0
- 업데이트
- 2026. 11. 2.
댓글
- …
이 저장소의 다른 스킬
adr-review
48k아키텍처 결정 기록을 새로운 눈으로 검토한 뒤, 새 독자도 결정을 명확히 이해하도록 다시 씁니다.
markdown-no-artificial-line-wraps
48k마크다운 문단을 한 줄로 쓰도록 에이전트를 돕습니다. 화면에서 글이 깔끔하게 줄바꿈되고 파일 변경도 깨끗하게 유지됩니다.
multiline-commit-messages
48k셸에서 여러 줄 git 커밋 메시지를 안전하게 쓰는 방법을 에이전트에 보여 주어, 메시지가 깨지지 않게 합니다.
product-direction
48k기능 요청을 프로젝트가 문서로 정해 둔 제품 방향과 비교해 이유가 있는 판정을 내리고, 거절한 내용을 기록하도록 돕습니다.