Skip to content

Instantly share code, notes, and snippets.

@alexeagle
Created March 25, 2015 21:28
Show Gist options
  • Save alexeagle/497ff83bc00bc866c0e9 to your computer and use it in GitHub Desktop.
Save alexeagle/497ff83bc00bc866c0e9 to your computer and use it in GitHub Desktop.
diff --git a/src/compiler/types.ts b/src/compiler/types.ts
index a18cc84..4467b91 100644
--- a/src/compiler/types.ts
+++ b/src/compiler/types.ts
@@ -357,6 +357,10 @@ module ts {
FailedAndReported = 3
}
+ export interface NodeVisitor<R, P> {
+ visitSourceFile(node: SourceFile, p: P): R;
+ }
+
export interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
@@ -371,6 +375,8 @@ module ts {
locals?: SymbolTable; // Locals associated with node (initialized by binding)
nextContainer?: Node; // Next container in declaration order (initialized by binding)
localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
+ // Support for the Visitor pattern
+ accept<R, P>(visitor: NodeVisitor<R, P>, p: P): R;
}
export interface NodeArray<T> extends Array<T>, TextRange {
diff --git a/src/services/services.ts b/src/services/services.ts
index 658f29f..0877f02 100644
--- a/src/services/services.ts
+++ b/src/services/services.ts
@@ -144,7 +144,9 @@ module ts {
public flags: NodeFlags;
public parent: Node;
private _children: Node[];
-
+public accept<R, P>(visitor: NodeVisitor<R, P>, p: P): R {
+ throw new Error("Node kind " + (<any>ts).SyntaxKind[this.kind] + " does not support visitor pattern");
+}
public getSourceFile(): SourceFile {
return getSourceFileOfNode(this);
}
@@ -718,6 +720,10 @@ module ts {
}
class SourceFileObject extends NodeObject implements SourceFile {
+ public accept<R,P>(visitor: NodeVisitor<R,P>, p: P): R {
+ this.statements.forEach((n) => n.accept(visitor, p));
+ return visitor.visitSourceFile(this, p);
+ }
public _declarationBrand: any;
public fileName: string;
public text: string;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment