Skip to content

Commit

Permalink
feat: add docs to metadata (#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
tjjfvi committed Feb 13, 2023
1 parent 1a4eb64 commit c931071
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
19 changes: 14 additions & 5 deletions common/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,20 @@ export abstract class Codec<T> {
}
try {
codecInspectCtx.set(this, null)
const metadata = this._metadata[0]
if (!metadata) return "?"
const content = metadata.type === "atomic"
? metadata.name
: `${metadata.name}(${inspect(metadata.args).replace(/^\[(?: (.+) |(.+))\]$/s, "$1$2")})`
let content = ""
for (const metadata of this._metadata) {
if (metadata.type === "docs") {
// TODO: print docs in inspect
} else {
if (metadata.type === "atomic") {
content += metadata.name
} else if (metadata.type === "factory") {
content += `${metadata.name}(${inspect(metadata.args).replace(/^\[(?: (.+) |(.+))\]$/s, "$1$2")})`
}
break
}
}
content ||= "?"
id = codecInspectCtx.get(this)
return id !== null ? `$${id} = ${content}` : content
} finally {
Expand Down
14 changes: 13 additions & 1 deletion common/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,23 @@ export type Metadata<T> = Array<
| {
type: "atomic"
name: string
docs?: never
factory?: never
args?: never
}
| {
type: "factory"
name: string
docs?: never
factory: (...args: any) => Codec<T>
args: any[]
}
| {
type: "docs"
docs: string
factory?: never
args?: never
}
>

/** Metadata for an atomic codec */
Expand Down Expand Up @@ -51,6 +59,10 @@ export function metadata<T>(
]
}

export function docs<T = any>(docs: string): Metadata<T> {
return [{ type: "docs", docs }]
}

export class CodecVisitor<R> {
#fallback?: <T>(codec: Codec<T>) => R
#visitors = new Map<Codec<any> | Function, (codec: Codec<any>, ...args: any[]) => R>()
Expand Down Expand Up @@ -91,7 +103,7 @@ export class CodecVisitor<R> {
const visitor = this.#visitors.get(codec)
if (visitor) return visitor(codec)
for (const metadata of codec._metadata) {
if (metadata.type === "atomic") continue
if (metadata.type !== "factory") continue
const visitor = this.#visitors.get(metadata.factory)
if (visitor) return visitor(codec, ...metadata.args)
}
Expand Down

0 comments on commit c931071

Please sign in to comment.