-
Notifications
You must be signed in to change notification settings - Fork 0
/
stholite_compiler.js
304 lines (264 loc) · 9.65 KB
/
stholite_compiler.js
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// a prototype compiler
// we "commit" sourcemap many whenever we reiterate on the same source
// transforms with lezer should be much better
import MagicString from 'magic-string'
import {SourceMapConsumer,SourceMapGenerator} from 'source-map-js';
// combine sourcemaps (last first?)
export function merge_sourcemaps(first,second) {
first.file ||= 'doubleyconfusing'
let map = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(second));
map.applySourceMap(new SourceMapConsumer(first));
// toJSON makes data ready to become JSON
map = map.toJSON()
return map
}
// timer
function delta(t) {
const start_time = Date.now();
return function(min) {
let del = Date.now() - start_time
// says if thing takes more than min ms
if (min && min > del) return
console.log(del+"ms", t);
};
}
// transform to javascript something quite like it
export function stylehouse_lite (source,filename,agent) {
// rep(), commit_s()
if (typeof source != 'string') throw "!string"
filename ||= "???"
let s = new MagicString(source)
let timer = delta('stylehouse_lite '+(agent?agent+": ":"")+filename)
let bit_slow_ms = 9
let last_sourcemap
let staged_changes = 0
function commit_s () {
// < caching|laziness right, breaks everything now
if (0 && staged_changes == 0 && last_sourcemap) {
return last_sourcemap
}
staged_changes = 0
// < why|what should these be? works okay
const outputSourceMap = 'output.js.map';
const map = s.generateMap({
source: 'input.js',
file: outputSourceMap,
includeContent: true,
});
let it = {code: s.toString(), map: s.generateMap({ hires: true })}
// if that map goes on the end of another map
if (last_sourcemap) {
it.map = merge_sourcemaps(last_sourcemap,it.map)
}
// begin again
source = it.code
last_sourcemap = it.map
s = new MagicString(source)
return it
}
// concat array of regexp bits
let regbits = bits => bits.map(s => (typeof s == 'object' ? s.source : s)).join('')
// g flag allows many matches throughout string
// m multiline string: ^ and $ match the ends of lines
// eg "1\n2\n3".match(new RegExp('^2$','gm'))
let reg = (...bits) => new RegExp(regbits(bits),'gm')
let recursive = []
// < rep() adaptive indent when /\n/
// also globally avoid comments
let rep = (bits,cb,c) => {
let pattern = reg(...bits instanceof Array ? bits : [bits])
let match
let any = 0
while (match = pattern.exec(source)) {
any = 1
let whole = match[0]
let start = match.index
let end = start + whole.length
let it = cb(...match.slice(1))
if (typeof it != 'string') {
throw "Error replacing /"+pattern.source+"/: "+whole+"\nWith: "+it
}
s.overwrite(start, end, it)
if (c && c.recursive) {
// it may happen again later
delete c.recursive
recursive.push([bits,cb,c])
}
}
if (any) {
// commit_s() may then make a map, update source
staged_changes++
}
return any
}
// rep(...) use
// see shed.git/ghosts/j/41 / JaBabz
// anything on a line (was nnl in JaBabz)
let nnl = '[^\n]+'
// whitespace leading up to things not comments
let nls = '[ \t]*(?! *\/\/)'
// shorthands to access A* and C*
// A.1.2 -> A[1][2]
rep(/\b([a-zA-Z]+)((?:\.\d)+)\b/, (s,N) => s+N.split('.').slice(1).map(t => '['+t+']').join(''))
rep(/\b(\d)s&(\w+)\b/, (i,t) => 'A['+i+'].sc.'+t)
// capital A is the more empiricle (A.c)
rep(/\bA&(\w+)\b/, (t) => 'A.c.'+t)
rep(/\ba&(\w+)\b/, (t) => 'A.sc.'+t)
// etcs&thing and 3s&thing -> A.3.sc.thing
rep(
/\b(\w+)(s|c|y)&(\w+)\b/,
(s,nk,t) => (s*1==s ? 'A['+s+']' : s)+'.'+(nk == 's' ? 'sc' : nk)+'.'+t
)
rep(/\bc&(\w+)\b/, (t) => 'C.c.'+t)
rep(/\bs&(\w+)\b/, (t) => 'C.sc.'+t)
// # comment to // comment
// $C->{c}->{s} =~ s/^(\s*)#/$1\/\//gsm;
// $C->{c}->{s} =~ s/( \{|}|;) #/$1 \/\//gsm;
let commenty = [
rep(/^(\s*)#/, (indent) => indent+'//'),
rep(/( \{|}|;) #/, (indent) => indent+' //')
]
// the following patterns may use $nls to not work on comments
commenty.some(r=>r) && commit_s()
rep(/blatant/, () => 'blon_itn')
rep(/'one thing'/, () => "'un thing'\n'two thing'")
// left-hand if
// $C->{c}->{s} =~ s/^($nls)([^\n]+?) and ($nnl)(;)?$/$1if ($2) {
// $1 $3
// $1}/gm for 1..3;
rep(
['^(',nls,')(',nnl,'?) and (',nnl,')(;)?$'],
(indent,expr,block) => {
return indent+"if ("+expr+") {\n"
+indent+" "+block+"\n"
+indent+"}"
},
{recursive:1}
)
// one might: ... and ~...
// so we should commit now (if anything chaged)
commit_s()
// < ~... -> &c,"..." for random observations (debug statements)
rep(/^(\s*)~(.*?)$/, (indent,com) => indent+'// some &c: '+com)
// each etc data { -> for (var e in data) { etc
// < not DIY closing brackets (indent?)
// < more of an o, if more spec
rep(
/^(\s*)each (\w+(?:,\w+)*) (\S+) \{(\s*)$/,
(ind, input, from) => {
const inArray = input.split(',');
// if there is no ',', split by letter
const inValues = inArray.length === 1 ? inArray[0].split('') : inArray;
const openBrackets = [];
while (inValues.length) {
const key = inValues.shift();
const value = inValues.shift();
let more = inValues.length
if (more) {
inValues.unshift(value);
}
const s = `for (var ${key} in ${from}) {`;
const v = more ? value + 'v' : value;
const assignment = `var ${v} = ${from}[${key}];`;
const checkObject = `if (typeof ${v} !== 'object') { continue; }`;
const code = [s, ind + ' ' + assignment];
if (more) {
code.push(ind + ' ' + checkObject);
}
from = v;
openBrackets.push(code.join('\n'));
}
return openBrackets.map((bracket) => ind + bracket).join('\n');
}
)
// chuck error: throw "Something", C
// throws new Error("Something"), its .etc=[C]
// also handles concatenated bits for "Something":
// < preserving the keys of etc
rep(
[
'(', /^\s*(?:else *)?(?!#)/, '?)',
'throw (', /"[^\n"]+?"/, ')',
'(, ?', nnl, ')?;?', /\s*$/
],
(ind,msg,etc) => {
msg = msg.replace(/: ?"$/, '"')
let guts = `new Error(${msg})`
if (etc) {
etc = etc.replace(/^, ?/, '')
etc = etc.replace(/;$/, '')
guts = `{var er = ${guts}; er.etc = [${etc}]; throw er}`
} else {
guts = `throw ${guts};`
}
return ind + guts
}
)
// perlish elsif
rep(
/^(\s*)elsif ?\(/,
(ind) => ind+"else if ("
)
commit_s()
// delete returns the deleted
rep(/ = delete (\w+[\[\.][^\s;)]+)/,
(expr) => ' = '+expr+'; delete '+expr
)
// me&func,args -> me.func(A,C,G,T,args)
// see also shorthands to access A* and C*
// which has already replaced /\w[Aaycs]&\w+/
rep(/(G|me)\&(\$)?(\w+)(,[^\s;]+)?/,
(me,interp,name,args) => {
let t = interp ? name : "'"+name+"'"
let h = me == 'G' ? ".h(A,C,G,T,"+t : "["+t+"](A,C,G,T"
args ||= ''
return me+h+args+")"
}
)
commit_s()
// &etc{...} -> function(e,t,c){...}
// < (arfgunc) a way to write its args on it without having to read via toString parse
rep(
/(\W|^)&(acgt)?(\w+)?((?:,\w+)+?)?(,)?\{/,
(not, acgt, wordy, comma_wordy, comma_end) => {
wordy ||= ''
comma_wordy ||= ''
comma_end ||= ''
var args = [];
if (!acgt && wordy && (comma_wordy || comma_end)) {
// &many,things,explicitly{ or &justone,{
args = (wordy + comma_wordy).split(',');
} else {
// acgt then split wordy
args = [
...((acgt ? 'ACGT' : '')+wordy).split(''),
// until commas (may) start
...comma_wordy.split(',')
]
}
return not + 'function(' + args.filter(Boolean).join(',') + '){';
}
)
// purchase instead of declare variables
rep(
/^(\s*)\$(\w+)(;|\s*=|\s*\/\/|$)/,
(ind,name,etc) => ind+"var "+name+(etc||';')
)
// < anything that might have moved in above transforms (eg s&vars)
// will need to commit_s() before they will happen not to their replaced position...
if (recursive.length) {
// some patterns want to apply multiple times, to their own output
// eg one line ... and ... and ...
let a_recursion = (recur) => {
commit_s()
rep(...recur)
}
for (let recur of recursive) {
a_recursion(recur)
a_recursion(recur)
}
}
// < about here (below the above) is pasting back in chunks of quoted text that avoid these transforms
timer(bit_slow_ms)
return commit_s()
}