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

Function parse

packages/effect/src/internal/schema/codeImports.ts:25–142  ·  view source on GitHub ↗
(source: string)

Source from the content-addressed store, hash-verified

23}
24
25export function parse(source: string): Imports {
26 const fail = (): never => {
27 throw new Error(`Invalid import declaration: ${source}`)
28 }
29 const decode = (text: string): string =>
30 text.replace(
31 /\\(?:u\{([\da-fA-F]+)\}|u([\da-fA-F]{4})|x([\da-fA-F]{2})|(\r\n|[\s\S]))/gu,
32 (match, point, unit, hex, char, offset) => {
33 const digits = point ?? unit ?? hex
34 if (digits !== undefined) {
35 const value = Number.parseInt(digits, 16)
36 return value <= 0x10ffff ? String.fromCodePoint(value) : fail()
37 }
38 if (
39 char === "u" || char === "x" || /[1-9]/.test(char) ||
40 (char === "0" && /\d/.test(text[offset + match.length] ?? ""))
41 ) return fail()
42 return escapes[char] ?? char
43 }
44 )
45 const tokens = tokenize(source).map((token) => {
46 const value = decode(token.kind === "string" ? token.text.slice(1, -1) : token.text)
47 if (token.kind === "identifier" && !/^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(value)) return fail()
48 return { kind: token.kind, value }
49 })
50
51 let index = 0
52 const at = (value: string): boolean => tokens[index]?.value === value && tokens[index]?.kind !== "string"
53 const take = (value: string): boolean => at(value) ? (index++, true) : false
54 const expect = (value: string): void => {
55 if (!take(value)) fail()
56 }
57 const identifier = (): string => {
58 const token = tokens[index++]
59 return token?.kind === "identifier" ? token.value : fail()
60 }
61 const string = (): string => {
62 const token = tokens[index++]
63 return token?.kind === "string" ? token.value : fail()
64 }
65 const imports: Array<Imports[number]> = []
66 while (index < tokens.length) {
67 expect("import")
68 const clause: Array<Omit<Import, "module" | "attributes">> = []
69 let typeOnly = false
70 if (tokens[index]?.kind !== "string") {
71 typeOnly = at("type") && tokens[index + 1]?.value !== "from" && tokens[index + 1]?.value !== ","
72 ? (index++, true)
73 : false
74 if (tokens[index]?.kind === "identifier") {
75 clause.push({ kind: "Default", imported: "default", local: identifier(), typeOnly })
76 if (!take(",")) expect("from")
77 }
78 if (take("*")) {
79 expect("as")
80 clause.push({ kind: "Namespace", imported: "*", local: identifier(), typeOnly })
81 expect("from")
82 } else if (take("{")) {

Callers

nothing calls this directly

Calls 12

tokenizeFunction · 0.90
sliceMethod · 0.80
decodeFunction · 0.70
failFunction · 0.70
expectFunction · 0.70
atFunction · 0.70
identifierFunction · 0.70
takeFunction · 0.70
stringFunction · 0.70
pushMethod · 0.65
mapMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected