본문으로 건너뛰기
Skillpedia
일반 코딩48k · #6309

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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/prisma/orm/blob/main/skills-contrib/ast-visitor-pattern/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

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

  • MongoAstNode base — packages/2-mongo-family/4-query/query-ast/src/ast-node.ts
  • MongoDdlCommandVisitor interface — 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.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬