This repository was archived by the owner on Nov 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathentry.js
More file actions
1383 lines (1356 loc) · 39.2 KB
/
Copy pathentry.js
File metadata and controls
1383 lines (1356 loc) · 39.2 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs')
const path = require('path')
const CONFIG = require('!config/mc')
const logger = require('!logger')
const CompilerError = require('!errors/CompilerError')
const UserError = require('!errors/UserError')
const File = require('!io/File')
const { MCFunction, loadFunction, tickFunction, evaluate_str } = require('./io')
const { evaluateCodeWithEnv, bindCodeToEnv } = require('./code-runner')
const { EventEmitter } = require('events')
const io = require('./io')
const consumer = {}
const SRC_DIR = path.resolve(process.cwd() + '/src')
const MC_LANG_EVENTS = new EventEmitter()
const F_LIB = process.argv.find(arg => arg.startsWith('-lib='))
const PROJECT_JSON = require(path.resolve(process.cwd(), '.mcproject', 'PROJECT.json'))
// Validate path for CONFIG.generatedDirectory
if (typeof CONFIG.generatedDirectory == 'string' && CONFIG.generatedDirectory.length > 0) {
if (CONFIG.generatedDirectory.match(/^[\da-z_\-\./]+$/) != null) {
CONFIG.generatedDirectory = CONFIG.generatedDirectory
.replace(/^\/+|\/+$/g, '')
.replace(/^\.\.\/?|\.\.\/|\.\.$/g, '')
} else {
throw new UserError(
`Config.generatedDirectory: Invalid directory path ${CONFIG.generatedDirectory}\nDefaulting to "__generated__".`
)
}
} else {
CONFIG.generateDirectory = '__generated__'
}
let hashes = new Map()
function getNameFromHash(hash, prefix) {
if (hashes.has(hash)) {
return hashes.get(hash)
} else {
hashes.set(hash, prefix + hashes.size)
return hashes.get(hash)
}
}
let id = 0
let env = {}
let namespaceStack = []
let MacroCache = {}
let Macros = {}
let LoadFunction = null
let TickFunction = null
let MacroStorage = {}
let scoreIds = new Map()
function flat(arr, r) {
let res = r || []
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flat(arr[i], res)
} else {
res.push(arr[i])
}
}
return res
}
function getUniqueScoreId(file) {
const ids = flat(Array.from(scoreIds.values()))
for (let i = 0; i < ids.length + 1; i++) {
if (!ids.includes(i)) {
const arr = scoreIds.get(file) || []
arr.push(i)
scoreIds.set(file, arr)
return i
}
}
}
function resetScoreIdsForFile(file) {
scoreIds.delete(file)
}
function getMacro(filepath, dependent) {
if (!(filepath.endsWith('.mcm') || filepath.endsWith('.mcbm'))) {
filepath += '.mcbm'
}
if (fs.existsSync(filepath)) {
if (!MacroCache[filepath]) {
MacroCache[filepath] = {
macros: {},
dependents: [],
filepath,
importedMacros: {},
}
const tokens = tokenize(fs.readFileSync(filepath, 'utf-8')).map(token => {
token.line = filepath + '@' + (token.line + 1)
token.file = filepath
return token
})
while (tokens.length) {
const token = tokens.shift()
if (token.token.startsWith('macro')) {
const [, name] = token.token.split(' ')
validate_next_destructive(tokens, '{')
let match = 1
let macrotokens = []
let _token
do {
_token = tokens.shift()
if (_token.token === '{') {
match++
} else if (_token.token === '}') {
match--
}
if (match) macrotokens.push(_token)
} while (match && tokens.length)
MacroCache[filepath].macros[name] = macrotokens
} else if (token.token.startsWith('import')) {
const target = token.token.substr(7).trim()
MacroCache[filepath].importedMacros = Object.assign(
MacroCache[filepath].importedMacros,
getMacro(
target.startsWith('@/')
? path.resolve(SRC_DIR, target.slice(2))
: path.resolve(path.parse(filepath).dir, target),
filepath
)
)
} else {
throw new CompilerError(`unexpected value '${token.token}'`, token.line)
}
}
}
if (dependent && !MacroCache[filepath].dependents.includes(dependent))
MacroCache[filepath].dependents.push(dependent)
if (F_LIB) {
const f = new File()
f.setPath('__MACRO_METADATA__/' + filepath)
f.setContents(JSON.stringify(MacroCache[filepath].macros))
f.confirm()
}
return MacroCache[filepath].macros
} else {
throw new CompilerError(`macro file not found '${filepath}'`)
}
}
const evaluate = (line, token) => {
try {
return evaluateCodeWithEnv(`return ${line}`, {
...env,
args: token.args,
storage: MacroStorage[token.file || 'mc'],
type: index => token.args[index].type,
})
// return new Function("type", "return " + line).bind(env)((index, type) => token.args[index].type === type);
} catch (e) {
throw new CompilerError(e.message, token.line)
}
}
class Token {
constructor(line, token) {
this.line = line
this.token = token
}
[Symbol.toStringTag]() {
return this.token
}
}
let included_file_list = []
let lib_function_lookup = {}
function includeFileList(list, file) {
while (list.length) {
const item = list.shift()
try {
if (!included_file_list.includes(item)) {
included_file_list.push(item)
if (!item.endsWith('.json')) {
const f = new File()
f.setPath(path.resolve(process.cwd(), item))
f.setContents(lib_function_lookup[item].content)
f.confirm()
} else {
list.push(...lib_function_lookup[item].dependencies)
}
function toFunction(str) {
const [, name, , ...rest] = str.replace('.mcfunction', '').split(/\/|\\/)
return `${name}:${rest.join('/')}`
}
if (item.endsWith('tick.mcfunction')) {
tickFunction.set(file, toFunction(item))
}
if (item.endsWith('load.mcfunction')) {
loadFunction.set(file, toFunction(item))
}
}
} catch (e) {
console.log(item)
}
}
}
function loadLib(json) {
const { remote } = json
let location = remote._loc
const lib = require(path.resolve(location, 'build.json'))
const target_name = json.name.split('/')[0]
const macros = {}
const libRes = {
macros,
}
function loadLibMacro(macro) {
return macro.tokens.map(raw => {
let token = new Token(raw.line, raw.token)
token.file = raw.file
token.dependencies = macro.dependencies
return token
})
}
for (let file in lib) {
const name = (target_name + file.substr(3).replace(/\..+$/, '')).replace(/\\/g, '/')
let current = lib[file]
if (current.functions) {
for (let func in current.functions) {
lib_function_lookup[func] = current.functions[func]
}
}
if (current.macros) {
macros[name] = {}
for (let macro in current.macros) {
macros[name][macro] = loadLibMacro(current.macros[macro])
}
}
if (current.json) {
for (let json of current.json) {
lib_function_lookup[json.name] = json
}
}
}
return {
[target_name]: libRes.macros,
}
}
const libraries = Object.assign({}, ...(PROJECT_JSON.libs.map(loadLib) || []))
const tokenize = code => {
// magical regex of magicalness and awesomness
const lineEndsWithOpeningBracket = /(?:(?:function .+?|block|run|\)|else)\s?({\s*(?:{|with).+?$))|(^{.+?$)|({)$/
let isInMultiLineComment = false
// change multi line commands to single line commands
code = code.replaceAll(/ \\[\t ]*$\r?\n[\t ]*/gm, ' ')
return code.split('\n').reduce((tokens, line, index) => {
line = line.trim()
// if the line is a multi line comment indicator toggle the multi line comment state
if (line.startsWith('###')) isInMultiLineComment = !isInMultiLineComment
// if this is either the start or inside a multiline comment or the line is a comment or empty do not process it further
if (isInMultiLineComment || line[0] === '#' || !line) return tokens
// if the line is an escaped comment add it as is
if (line[0] === '\\' && line[1] == '#') line = line.slice(1)
// if the line starts with a closing block indicator (}) seperate it from the line
if (line[0] === '}') {
tokens.push(new Token(index, '}'))
line = line.slice(1)
}
// if the line ends with an opening block seperator ({) seperate it from the line
let match = String(line).match(lineEndsWithOpeningBracket)
if (match) {
let post = match[1] || match[2] || match[3]
const preBlockValue = line.slice(0, line.length - post.length).trim()
if (preBlockValue) tokens.push(new Token(index, preBlockValue))
tokens.push(new Token(index, post.trim()))
} else if (line) {
tokens.push(new Token(index, line))
}
return tokens
}, [])
}
function validate_next_destructive(tokens, expect) {
const token = tokens.shift()
if (token && token.token != expect) {
throw new CompilerError(`unexpected token '${token.token}' expected '${expect}'`, token.line)
}
}
function list({ getToken, actions, def }) {
const invoker = (file, tokens, ...args) => {
const token = invoker.getToken(tokens)
const action = invoker.actions.find(action => action.match(token))
if (!action) {
return invoker.def(file, tokens, ...args)
} else {
return action.exec(file, tokens, ...args)
}
}
invoker.actions = actions.map((action, index) => {
action.priority = index
return action
})
invoker.def = def
invoker.getToken = getToken
invoker.addAction = (action, priority = invoker.actions.length) => {
action.priority = priority
invoker.actions = [action, ...invoker.actions].sort((a, b) => a.priority - b.priority)
}
return invoker
}
consumer.Namespace = (file, token, tokens) => {
const name = evaluate_str(token.substr('dir '.length))
if (/[^a-z0-9_\.]/.test(name)) {
throw new CompilerError("invalid directory name '" + name + "'", token.line)
}
namespaceStack.push(name.trim())
validate_next_destructive(tokens, '{')
while (tokens[0].token != '}') {
consumer.Entry(file, tokens, true)
}
validate_next_destructive(tokens, '}')
namespaceStack.pop()
}
consumer.EntryOp = list({
getToken: tokenlist => tokenlist[0],
actions: [
{
match: token => token.token.startsWith('import'),
exec(file, tokens) {
const _token = tokens[0]
const { token } = _token
const target = token.substr(7).trim()
if (token.endsWith('.mcm') || token.endsWith('.mcbm')) {
Macros = Object.assign(
Macros,
getMacro(
target.startsWith('@/')
? path.resolve(SRC_DIR, target.slice(2))
: path.resolve(path.parse(file).dir, target),
file
)
)
} else {
const [lib] = target.split('/')
if (lib) {
const library = libraries[lib]
if (!library[target]) {
throw new CompilerError(
`did not find component for ${target} for library ${lib}`,
_token.line
)
}
Macros = Object.assign(Macros, library[target])
} else {
throw new CompilerError(`did not find library ${lib}`, _token.line)
}
}
tokens.shift()
},
},
{
match: ({ token }) => /dir .+/.test(token),
exec(file, tokens) {
consumer.Namespace(file, tokens.shift().token, tokens)
},
},
{
match: ({ token }) => /function .+/.test(token),
exec(file, tokens) {
consumer.Function(file, tokens)
},
},
{
match: ({ token }) => /clock .+/.test(token),
exec(file, tokens) {
const { token } = tokens[0]
const time = token.substr(6)
tokens.shift()
const func = consumer.Block(file, tokens, 'clock', {
prepend: ['schedule function $block ' + time],
})
loadFunction.set(file, func.substr(9))
},
},
{
match: ({ token }) => /^LOOP/.test(token),
exec(file, tokens) {
const _token = tokens.shift()
consumer.Loop(file, _token.token, tokens, true, consumer.Entry)
},
},
{
match: ({ token }) => /^!IF\(/.test(token),
exec(file, tokens) {
const _token = tokens.shift()
const { token } = _token
const condition = token.substr(4, token.length - 5)
validate_next_destructive(tokens, '{')
if (evaluate(condition, _token)) {
while (tokens[0].token != '}') {
consumer.Entry(file, tokens, true)
}
validate_next_destructive(tokens, '}')
} else {
let count = 1
while (count && tokens.length) {
let item = tokens.shift().token
if (item === '{') count++
if (item === '}') count--
}
}
},
},
{
match: ({ token }) => /^!.+/.test(token),
exec(file, tokens) {
const _token = tokens[0]
const { token } = _token
const condition = token.substr(1)
tokens.shift()
validate_next_destructive(tokens, '{')
if (evaluate(condition, _token)) {
while (tokens[0].token != '}') {
consumer.Entry(file, tokens, true)
}
validate_next_destructive(tokens, '}')
} else {
let count = 1
while (count && tokens.length) {
let item = tokens.shift().token
if (item === '{') count++
if (item === '}') count--
}
}
},
},
{
match: ({ token }) => token.startsWith('<%%'),
exec(file, tokens, func) {
const _token = tokens.shift()
const { token } = _token
let code = ''
let next = null
if (token.endsWith('%%>')) {
code = token.substring(3, token.length - 3)
} else {
do {
next = tokens.shift().token
if (next != '%%>') code += '\n' + next
} while (next && next != '%%>')
}
try {
MacroStorage[_token.file || 'mc'] = MacroStorage[_token.file || 'mc'] || new Map()
evaluateCodeWithEnv(code, {
...env,
meta: {
file,
},
emit: (command, target = 'load') => {
if (target === 'load') LoadFunction.addCommand(String(command))
if (target === 'tick') TickFunction.addCommand(String(command))
},
load(fp, mode) {
return fs.readFileSync(path.resolve(path.parse(file).dir, fp), mode || 'utf8')
},
storage: MacroStorage[_token.file || 'mc'],
})
} catch (e) {
throw new CompilerError('JS: ' + e.message, token.line)
}
},
},
],
def: (file, tokens) => {
const token = tokens.shift()
throw new CompilerError(
`unexpected token '${token.token}' before ${
tokens[0]
? tokens[0].token.length > 10
? tokens[0].token.substr(0, 10) + '...'
: tokens[0].token
: 'EOF'
}`,
token.line
)
},
})
consumer.Entry = (file, tokens, once) => {
if (once) {
consumer.EntryOp(file, tokens)
} else {
while (tokens[0]) {
consumer.EntryOp(file, tokens)
}
}
}
consumer.Function = (file, tokens, opts = {}) => {
const definition = tokens.shift()
let name = definition.token.substr(9)
name = evaluate_str(name)
if (/[^a-z0-9_\.]/.test(name)) {
throw new CompilerError("invalid function name '" + name + "'", definition.line)
}
const func = new MCFunction(null, null, name)
func.namespace = namespaceStack[0]
func.setPath(namespaceStack.slice(1).concat(name).join('/'))
validate_next_destructive(tokens, '{')
while (tokens[0] && tokens[0].token != '}') {
consumer.Generic(file, tokens, func, func, func)
}
validate_next_destructive(tokens, '}')
if (opts.append) {
for (let command of opts.append) {
func.addCommand(command)
}
}
func.confirm(file)
return func
}
consumer.Generic = list({
getToken: list => list[0],
actions: [
{
match: ({ token }) => token === 'load',
exec(file, tokens) {
tokens.shift()
const contents = consumer.Block(file, tokens, 'load', { dummy: true }, null, null)
for (let i = 0; i < contents.functions.length; i++) {
LoadFunction.addCommand(contents.functions[i])
}
},
},
{
match: ({ token }) => token === 'tick',
exec(file, tokens) {
tokens.shift()
const contents = consumer.Block(file, tokens, 'tick', { dummy: true }, null, null)
for (let i = 0; i < contents.functions.length; i++) {
TickFunction.addCommand(contents.functions[i])
}
},
},
{
match: ({ token }) => token.startsWith('<%%'),
exec(file, tokens, func) {
const _token = tokens.shift()
const { token } = _token
let code = ''
let next = null
if (token.endsWith('%%>')) {
code = token.substring(3, token.length - 3)
} else {
do {
next = tokens.shift().token
if (next != '%%>') code += '\n' + next
} while (next && next != '%%>')
}
try {
MacroStorage[_token.file || 'mc'] = MacroStorage[_token.file || 'mc'] || new Map()
evaluateCodeWithEnv(code, {
...env,
meta: {
file,
func,
},
emit: (command, target = 'this') => {
if (target === 'load' || target === true) LoadFunction.addCommand(String(command))
if (target === 'tick') TickFunction.addCommand(String(command))
if (target === 'this') func.addCommand(String(command))
},
load(fp, mode) {
return fs.readFileSync(path.resolve(path.parse(file).dir, fp), mode || 'utf8')
},
args: _token.args,
storage: MacroStorage[_token.file || 'mc'],
type: index => _token.args[index].type,
})
} catch (e) {
throw new CompilerError('JS: ' + e.message, token.line)
}
},
},
{
match: ({ token }) => token.startsWith('warn '),
exec(file, tokens) {
const { token } = tokens.shift()
logger.warn(evaluate_str(token.substr(5).trim()))
},
},
{
match: ({ token }) => token.startsWith('error '),
exec(file, tokens) {
const _token = tokens.shift()
const { token } = _token
throw new UserError(token.substr(5).trim(), _token.line)
},
},
{
match: ({ token }) => token.startsWith('macro'),
exec(file, tokens) {
const _token = tokens.shift()
const { token } = _token
const [, name, ...args] = token.split(' ')
handlemacro(file, _token, name, args, tokens)
},
},
{
match: ({ token }) => /^execute\s*\(/.test(token),
exec(file, tokens, func, parent, functionalparent) {
let { token } = tokens.shift()
let condition = token.substring(token.indexOf('(') + 1, token.length - 1)
func.addCommand(`scoreboard players set #execute ${CONFIG.internalScoreboard} 0`)
func.addCommand(
`execute ${condition} run ${consumer.Block(
file,
tokens,
'conditional',
{
append: [`scoreboard players set #execute ${CONFIG.internalScoreboard} 1`],
},
parent,
functionalparent
)}`
)
while (/^else execute\s*\(/.test(tokens[0].token)) {
token = tokens.shift().token
condition = token.substring(token.indexOf('(') + 1, token.length - 1)
func.addCommand(
`execute if score #execute ${
CONFIG.internalScoreboard
} matches 0 ${condition} run ${consumer.Block(
file,
tokens,
'conditional',
{
append: [`scoreboard players set #execute ${CONFIG.internalScoreboard} 1`],
},
parent,
functionalparent
)}`
)
}
if (/^else/.test(tokens[0].token)) {
tokens.shift()
func.addCommand(
`execute if score #execute ${CONFIG.internalScoreboard} matches 0 run ${consumer.Block(
file,
tokens,
'conditional',
{},
parent,
functionalparent
)}`
)
}
},
},
{
match: ({ token }) => /^!?IF\(/.test(token),
exec(file, tokens, func) {
const _token = tokens.shift()
const { token } = _token
const condition = token.substr(4, token.length - 5)
validate_next_destructive(tokens, '{')
if (evaluate(condition, _token)) {
while (tokens[0].token != '}') {
consumer.Generic(file, tokens, func)
}
validate_next_destructive(tokens, '}')
} else {
let count = 1
while (count && tokens.length) {
let item = tokens.shift().token
if (item === '{') count++
if (item === '}') count--
}
}
},
},
{
match: ({ token }) => /^!.+/.test(token),
exec(file, tokens, func) {
const _token = tokens.shift()
const { token } = _token
const condition = token.substr(1)
validate_next_destructive(tokens, '{')
if (evaluate(condition, _token)) {
while (tokens[0].token != '}') {
consumer.Generic(file, tokens, func)
}
validate_next_destructive(tokens, '}')
} else {
let count = 1
while (count && tokens.length) {
let item = tokens.shift().token
if (item === '{') count++
if (item === '}') count--
}
}
},
},
{
match: ({ token }) => /^block|^{/.test(token),
exec(file, tokens, func, parent) {
if (tokens[0].token === 'block') tokens.shift()
func.addCommand(consumer.Block(file, tokens, 'block', {}, parent, null))
},
},
{
match: ({ token }) => token.startsWith('execute') && /(?<=\brun\b)/g.test(token),
exec(file, tokens, func, parent, functionalparent) {
const _token = tokens.shift()
const { token } = _token
const match = token.matchAll(/(?<=\brun\b)/g)
let last_run = [...match].pop()
const command = token.substr(last_run.index).trim()
const execute = token.substr(0, last_run.index).trim()
let useAltParent = true
let isCommand = true
if (command) {
if (command === '{') isCommand = false
useAltParent = false
let lastInLine = _token
for (let i = 0; i < tokens.length; i++) {
if (tokens[i].line === lastInLine.line) {
lastInLine = tokens[i]
} else {
break
}
}
const temp = []
let count = 1
if (lastInLine && lastInLine.token.startsWith('{')) {
let tok = tokens.shift()
let last_line = tok.line
temp.push(tok)
while ((tokens.length && count) || tok.line == tokens[0].line) {
if (tokens[0].token === '{') count++
if (tokens[0].token === '}') count--
tok = tokens.shift()
temp.push(tok)
}
}
let copy = copy_token(_token, _token.args)
tokens.unshift(...temp, copy)
copy.token = '}'
copy = copy_token(_token, _token.args)
tokens.unshift(copy)
copy.token = command
copy = copy_token(_token, _token.args)
tokens.unshift(copy)
copy.token = '{'
}
const innerFunc = consumer.Block(
file,
tokens,
'execute',
{
dummy: true,
},
useAltParent ? parent : func,
useAltParent ? functionalparent : func
)
if (innerFunc.functions.length > 1) {
innerFunc.confirm(file)
func.addCommand(execute + ' ' + innerFunc.toString())
} else {
if (innerFunc.functions.length == 0) {
const { line } = tokens.shift()
throw new CompilerError(`Empty run block`, line - 1)
}
if (innerFunc.functions[0]?.indexOf('$block') != -1 && !isCommand) {
innerFunc.confirm(file)
func.addCommand(execute + ' ' + innerFunc.toString())
} else {
func.addCommand(execute + ' ' + innerFunc.functions[0])
}
}
},
},
{
match: ({ token }) => /^LOOP/.test(token),
exec(file, tokens, func) {
const { token } = tokens.shift()
consumer.Loop(file, token, tokens, func, consumer.Generic, null, null)
},
},
{
match: ({ token }) => /until\s*\(/.test(token),
exec(file, tokens, func, parent, functionalparent) {
const { token } = tokens.shift()
const args = token.substr(6, token.length - 7)
const cond = args.substr(0, args.lastIndexOf(',')).trim()
const time = args.substr(args.lastIndexOf(',') + 1).trim()
const _id = getUniqueScoreId(file)
const call = consumer.Block(
file,
tokens,
'until',
{
prepend: [`scoreboard players set #until_${_id} ${CONFIG.internalScoreboard} 1`],
},
parent,
null
)
const untilFunc = new MCFunction(func, func, 'until')
const name =
CONFIG.generatedDirectory + '/until/' + (id.until = (id.until == undefined ? -1 : id.until) + 1)
untilFunc.namespace = namespaceStack[0]
untilFunc.setPath(namespaceStack.slice(1).concat(name).join('/'))
untilFunc.addCommand(`scoreboard players set #until_${_id} ${CONFIG.internalScoreboard} 0`)
untilFunc.addCommand(`execute ${cond} run ${call}`)
untilFunc.addCommand(
`execute if score #until_${_id} ${CONFIG.internalScoreboard} matches 0 run schedule function $block ${time}`
)
untilFunc.confirm(file)
func.addCommand(`function ${untilFunc.getReference()}`)
},
},
{
match: ({ token }) => /^async while/.test(token),
exec(file, tokens, func, parent) {
let { token } = tokens.shift()
const args = token.substr(12, token.length - 13)
const cond = args.substr(0, args.lastIndexOf(',')).trim()
const time = args.substr(args.lastIndexOf(',') + 1).trim()
const whileFunc = new MCFunction(parent, func, 'while')
const _id = getUniqueScoreId(file)
const name =
CONFIG.generatedDirectory + '/while/' + (id.while = (id.while == undefined ? -1 : id.while) + 1)
whileFunc.namespace = namespaceStack[0]
whileFunc.setPath(namespaceStack.slice(1).concat(name).join('/'))
const whileAction = consumer.Block(
file,
tokens,
'while',
{
append: [
`scoreboard players set #WHILE_${_id} ${CONFIG.internalScoreboard} 1`,
`schedule function ${whileFunc.getReference()} ${time}`,
],
},
parent,
func
)
whileFunc.addCommand(`scoreboard players set #WHILE_${_id} ${CONFIG.internalScoreboard} 0`)
whileFunc.addCommand(`execute ${cond} run ${whileAction}`)
if (/^finally$/.test(tokens[0].token)) {
token = tokens.shift().token
const whileFinally = consumer.Block(file, tokens, 'while', {}, whileFunc, func)
whileFunc.addCommand(
`execute if score #WHILE_${_id} ${CONFIG.internalScoreboard} matches 0 run ${whileFinally}`
)
}
whileFunc.confirm(file)
func.addCommand(`function ${whileFunc.getReference()}`)
},
},
{
match: ({ token }) => /^while/.test(token),
exec(file, tokens, func, parent) {
let { token } = tokens.shift()
const args = token.substr(6, token.length - 7)
const cond = args.trim()
const whileFunc = new MCFunction(parent, func)
const name =
CONFIG.generatedDirectory + '/while/' + (id.while = (id.while == undefined ? -1 : id.while) + 1)
const _id = getUniqueScoreId(file)
whileFunc.namespace = namespaceStack[0]
whileFunc.setPath(namespaceStack.slice(1).concat(name).join('/'))
const whileAction = consumer.Block(
file,
tokens,
'while',
{
append: [
`scoreboard players set #WHILE_${_id} ${CONFIG.internalScoreboard} 1`,
`function ${whileFunc.getReference()}`,
],
},
parent,
func
)
whileFunc.addCommand(`scoreboard players set #WHILE_${_id} ${CONFIG.internalScoreboard} 0`)
whileFunc.addCommand(`execute ${cond} run ${whileAction}`)
if (/^finally$/.test(tokens[0].token)) {
token = tokens.shift().token
const whileFinally = consumer.Block(file, tokens, 'while', {}, whileFunc, func)
whileFunc.addCommand(
`execute if score #WHILE_${_id} ${CONFIG.internalScoreboard} matches 0 run ${whileFinally}`
)
}
whileFunc.confirm(file)
func.addCommand(`function ${whileFunc.getReference()}`)
},
},
{
match: ({ token }) => /^schedule\s?((\d|\.)+(d|t|s)|<%.+)\s?(append|replace){0,1}$/.test(token),
exec(file, tokens, func, parent, functionalparent) {
const { token } = tokens.shift()
const inner_func = consumer.Block(file, tokens, 'schedule', {}, parent, functionalparent)
const [, time, type] = evaluate_str(token).split(/\s+/)
func.addCommand(`schedule ${inner_func} ${time} ${type}`.trim())
},
},
{
match: ({ token }) => token === 'sequence',
exec(file, tokens, func, parent) {
tokens.shift()
const contents = consumer.Block(file, tokens, 'sequence', { dummy: true }, null, null)
const timeToTicks = time => {
let val = +time.substr(0, time.length - 1)
let type = time[time.length - 1]
switch (type) {
case 's':
val *= 20
break
case 'd':
val *= 24000
break
}
return val
}
const commands = {}
let time = 0
for (let command of contents.functions) {
if (command.startsWith('delay')) {
let delay = timeToTicks(command.substr(6).trim())
time += delay
} else if (command.startsWith('setdelay')) {
let delay = timeToTicks(command.substr(9).trim())
time = delay
} else {
commands[time] = commands[time] || []
commands[time].push(command)
}
}
for (let time in commands) {
if (time == 0) {
for (const command of commands[time]) func.addCommand(command)
} else {
const subfunc = new MCFunction(func, parent)
const name =
CONFIG.generatedDirectory +
'/sequence/' +
(id.sequence = (id.sequence == undefined ? -1 : id.sequence) + 1)
subfunc.namespace = namespaceStack[0]
subfunc.setPath(namespaceStack.slice(1).concat(name).join('/'))
for (const command of commands[time]) subfunc.addCommand(command)
func.addCommand(`schedule ${subfunc.toString()} ${time}t replace`)
subfunc.confirm()
}
}
},
},
{
match: ({ token }) => token === '(',
exec(file, tokens, func) {
tokens.shift()
let items = ''
let next = tokens.shift()
while (next.token != ')') {
items += next.token + ' '
next = tokens.shift()
}
func.addCommand(items.trim())
},
},
],
def(file, tokens, func, parent, functionalparent) {
const _token = tokens.shift()
const { token } = _token
const [name, ...args] = token.split(' ')
let _Macros = Macros
if (MacroCache[_token.file]) _Macros = MacroCache[_token.file].importedMacros
if (!_Macros[name] && MacroCache[_token.file]) _Macros = MacroCache[_token.file].macros
if (_Macros[name] && !_token.args) {
handlemacro(file, _token, name, args, tokens)
} else if (token.startsWith('execute')) {
const local_token = token.replace(/ run execute/g, '') //nope.
const startOfCommand = local_token.indexOf(' run')
const command = local_token.substr(startOfCommand + 5)
const [name] = command.split(' ')
if ((_Macros[name] || name === 'macro') && !_token.args) {
let item = copy_token(_token, _token.args)
item.token = '}'
tokens.unshift(item)
item = copy_token(_token, _token.args)
item.token = command
tokens.unshift(item)
item = copy_token(_token, _token.args)
item.token = '{'
tokens.unshift(item)
item = copy_token(_token, _token.args)
item.token = local_token.substr(0, startOfCommand + 4)
tokens.unshift(item)
} else {
func.addCommand(token)
}
} else {