-
Notifications
You must be signed in to change notification settings - Fork 1
/
recognize.ts
128 lines (118 loc) · 3.13 KB
/
recognize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import type { PSMapKey, PSString, PSTemplate, PSValue } from "./types.ts";
import { derive, read } from "./read.ts";
import * as data from "./data.ts";
export function recognize(value: PSValue): PSValue {
if (value.type === "string") {
let expressions = matchTemplate(value.value);
if (expressions.length > 0) {
return {
type: "template",
value,
expressions,
};
} else if (value.quote) {
return value;
} else {
let match = matchReference(value.value);
if (match) {
return {
type: "ref",
value,
key: match.key,
path: match.path,
};
} else {
return value;
}
}
} else if (value.type === "map") {
let entries = [...value.value.entries()];
let [first] = entries;
if (!first) {
return value;
} else {
let [firstKey, firstValue] = first;
let fnmatch = String(firstKey.value).match(/^\(\s*(.*)\)\s*=>$/);
if (fnmatch) {
let param = fnmatch[1];
let body = recognize(firstValue);
return {
type: "fn",
param: { name: param },
value: {
type: "platformscript",
head: firstKey as PSString,
body,
},
};
} else {
let $firstKey = recognize(firstKey);
if ($firstKey.type === "ref") {
let [, ...rest] = entries;
return {
type: "fncall",
value: $firstKey,
arg: firstValue,
rest: {
type: "map",
value: new Map(rest),
},
source: value,
};
}
return derive(value, {
type: "map",
value: new Map(entries.map(([k, v]) => {
let value = recognize(v);
//match method syntax
let mmatch = String(k.value).match(/^\s*(.+)\((.*)\)\s*$/);
if (mmatch) {
let [, key, param] = mmatch;
return [data.string(key), {
type: "fn",
param: { name: param },
value: {
type: "platformscript",
head: k as PSString,
body: value,
},
}];
} else {
return [k as PSMapKey, value];
}
})),
});
}
}
} else {
return value;
}
}
function matchTemplate(value: string) {
let valueIdx = 0;
let exprIdx = 1;
let regex = /%\(([\s\S]+?)\)/gmd;
let i = value.matchAll(regex);
let expressions: PSTemplate["expressions"] = [];
for (let next = i.next(); !next.done; next = i.next()) {
let match = next.value;
let expression = recognize(read(match[exprIdx]));
expressions.push({
expression,
//@ts-expect-error RegExpMatchArray#indices not yet in the default TS lib
range: match.indices[valueIdx],
});
}
return expressions;
}
function matchReference(value: string) {
let pathIdx = 1;
let match = value.match(/^\$(\S+)$/);
if (match) {
let [key, ...path] = match[pathIdx].split(".");
return {
key,
path,
};
}
}