MCPcopy Create free account
hub / github.com/Effect-TS/effect / parse

Function parse

packages/effect/src/internal/schema/codeExpression.ts:6–179  ·  view source on GitHub ↗
(source: string, references: ReadonlyMap<string, Fragment>, kind: "runtime" | "Type")

Source from the content-addressed store, hash-verified

4
5/** Parse schema expressions and types, keeping their spelling except for tracked references. */
6export function parse(source: string, references: ReadonlyMap<string, Fragment>, kind: "runtime" | "Type"): Fragment {
7 const replacements: Array<{ readonly token: Token; readonly fragment: Fragment }> = []
8 let index = 0
9 const fail = (position: number = tokens[index]?.start ?? source.length): never => {
10 throw new Error(`Unsupported ${kind} syntax at offset ${position}: ${source}`)
11 }
12 const tokens = tokenize(source)
13 for (const token of tokens) {
14 if (token.kind === "identifier" && token.text.includes("\\")) fail(token.start)
15 }
16 const isLiteral = (token: Token | undefined): boolean => token?.kind === "string" || token?.kind === "number"
17
18 const at = (text: string): boolean => tokens[index]?.text === text
19 const take = (text: string): boolean => at(text) ? (index++, true) : false
20 const expect = (text: string): void => {
21 if (!take(text)) fail()
22 }
23 const identifier = (): Token => {
24 const token = tokens[index]
25 if (token?.kind !== "identifier") return fail()
26 index++
27 return token
28 }
29 const reference = (token: Token, shorthand = false): void => {
30 const fragment = references.get(token.text)
31 if (fragment !== undefined) {
32 replacements.push({ token, fragment: shorthand ? code`${token.text}: ${fragment}` : fragment })
33 }
34 }
35 const list = (end: string, item: () => void): void => {
36 if (take(end)) return
37 do {
38 item()
39 if (!take(",")) break
40 } while (!at(end))
41 expect(end)
42 }
43 const path = (): void => {
44 reference(identifier())
45 while (take(".")) identifier()
46 }
47 const type = (): void => {
48 typeMember()
49 while (take("|") || take("&")) typeMember()
50 }
51 const typeMember = (): void => {
52 if (take("readonly") || take("typeof")) {
53 typeMember()
54 return
55 }
56 if (take("(")) {
57 type()
58 expect(")")
59 } else if (take("[")) {
60 list("]", () => {
61 take("...")
62 type()
63 take("?")

Callers 1

Calls 7

tokenizeFunction · 0.90
joinFunction · 0.90
expressionFunction · 0.85
sliceMethod · 0.80
failFunction · 0.70
typeFunction · 0.70
pushMethod · 0.65

Tested by

no test coverage detected