-
Notifications
You must be signed in to change notification settings - Fork 4
/
extension.js
1478 lines (1256 loc) · 66.1 KB
/
extension.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
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 vscode = require("vscode");
//import { Buffer } from 'node:buffer';
//const { ky } = require('ky-universal');
console.log(`Hello World!`);
var bugout = vscode.window.createOutputChannel("Greyscript Debugger");
//var bugout = { appendLine: function() {}}
var CompData;
var TypeData;
var ArgData;
var ReturnData;
var Examples;
var HoverData;
var Encryption;
var Nightly;
var CompTypes = {default:2};
// Deprecate CompTypes. For now I'm just going to give them all the same value (default).
// In the future, it should determine it's value automagically depending on other variables.
function ReloadGrammarFromFile() {
CompData = require("./computedgrammar/CompletionData.json")
TypeData = require("./computedgrammar/TypeData.json")
ArgData = require("./computedgrammar/ArgData.json")
ReturnData = require("./computedgrammar/ReturnData.json")
Examples = require("./computedgrammar/Examples.json")
//CompTypes = require("./grammar/CompletionTypes.json") // Constant 20 Function 2 Property 9 Method 1 Variable 5 Interface 7
CompTypes = {default:2};
HoverData = require("./computedgrammar/HoverData.json");
Encryption = require("./computedgrammar/Encryption.json");
Nightly = require("./computedgrammar/Nightly.json")
};
ReloadGrammarFromFile();
// Try to pull the above grammar from Greydocs.
// This means I don't have to update for each grammar change!
async function UpdateGreyDocs() {
bugout.appendLine("Updating from GD")
let PullFromGreyDocs = async (path) => {
bugout.appendLine(`Pull ${path}`)
try {
let req = await fetch(`https://raw.githubusercontent.com/WyattSL/greydocs/main/${path}`);
if (req.status != 200) bugout.appendLine(`Pull ${path} bad status, ${req.status} - proceeding!`);
let res = await req.json();
if (path.includes("night")) {
bugout.appendLine(`Nightly PFGD PreRet`)
bugout.appendLine(JSON.stringify(res));
}
//bugout.appendLine(`${path} --- OUTPUT: ${JSON.stringify(res)}`);
if (!res || res == {} || res == []) bugout.appendLine(`Pull ${path} bad res ${res} - proceeding!`)
return res;
} catch (err) {
bugout.appendLine(`PullFromGreyDocs ${path}: ${err}`);
return null;
}
}
let GD_CompData = await PullFromGreyDocs(`_data/functions.json`);
if (GD_CompData) CompData = GD_CompData;
let GD_TypeData = await PullFromGreyDocs(`_data/types.json`);
if (GD_TypeData) TypeData = GD_TypeData;
let GD_ArgData = await PullFromGreyDocs(`_data/arguments.json`);
if (GD_ArgData) ArgData = GD_ArgData;
let GD_ReturnData = await PullFromGreyDocs(`_data/returns.json`);
if (GD_ReturnData) ReturnData = GD_ReturnData;
let GD_Examples = await PullFromGreyDocs(`_data/examples.json`);
if (GD_Examples) Examples = GD_Examples;
let GD_HoverData = await PullFromGreyDocs(`_data/descriptions.json`);
if (GD_HoverData) HoverData = GD_HoverData;
let GD_Encryption = await PullFromGreyDocs(`_data/encryption.json`);
if (GD_Encryption) Encryption = GD_Encryption;
let GD_Nightly = await PullFromGreyDocs(`_data/nightly.json`);
if (GD_Nightly) Nightly = GD_Nightly;
/*
bugout.appendLine(`PFGD Nightly:`)
bugout.appendLine(`${JSON.stringify(PullFromGreyDocs(`_data/nightly.json`))}`)
bugout.appendLine(`GD_Nightly:`);
bugout.appendLine(`${JSON.stringify(Nightly)}`)
bugout.appendLine(`Final Nightly After GD:`)
bugout.appendLine(`${JSON.stringify(Nightly)}`)
*/
};
var enumCompTypeText = {
1: "method",
2: "function",
5: "variable",
7: "interface",
9: "property",
20: "constant",
}
async function GetDocumentText(document, range) {
//bugout.appendLine(`await GetDocumentText!`);
let t = document.getText(range);
return await HandleImports(t, document)
}
var FileCache = {};
async function HandleImports(t, document) {
t = `${t}`;
let reg = /import_code\("(.+)"\)/g
//bugout.appendLine(`await HandleImports`,t,reg)
//bugout.appendLine(typeof(t))
let ms = t.matchAll(reg);
//let ms = [];
//bugout.appendLine(`IMPORT IN`);
//bugout.appendLine(t);
//bugout.appendLine(`MATCHES`)
//bugout.appendLine(ms);
for (let m of ms) {
//bugout.appendLine(`MATCH ${m}`)
let path = m[1].split("/").pop();
let curPath = document.uri;
let pathUrl = vscode.Uri.joinPath(curPath, `../${path}`);
let ftext;
if (FileCache[pathUrl] && FileCache[pathUrl].time >= Date.now() - 2500) {
ftext = FileCache[pathUrl].text;
} else {
let fdata = await vscode.workspace.fs.readFile(pathUrl);
//let fbuf = Buffer.from(fdata);
//ftext = fbuf.toString();
ftext = new TextDecoder().decode(fdata);
FileCache[pathUrl] = { time: Date.now(), text: ftext };
}
t = t.replace(m[0], ftext);
}
//bugout.appendLine(`FINAL OUT`);
//bugout.appendLine(t);
return t;
}
const AnnotationExpression = /(?<=^\s*\/\/\s*)@(param|author|example|return|deprecated|readonly|description)(?=\s+.*$)/gm;
// test
/**
* @param {vscode.TextDocument} document The document to pull text from.
* @param {number} line The line to pull text from.
* @returns {FancyParse} The parsed JSDoc.
*/
function JsDocParse(document, line) {
try {
bugout.appendLine(`JsDocParse ${line} ${line-30} ${line-30 >= 0 ? line-30 : 0}`)
let range = new vscode.Range(line, 0, line-30 >= 0 ? line-30 : 0, 0);
bugout.appendLine(`${range.start.line} ${range.end.line}`)
let text = document.getText(range);
let comments = [];
for (let l of text.split("\n").reverse()) {
if (l == "" && comments.length == 0) continue;
if (l.trim().startsWith("//")) { comments.push(l.replace(/\s*\/\/\s*/, ``))
} else { break }
}
bugout.appendLine(`Comments: ${comments.length}`);
if (comments.length <= 0) return null;
let FancyParse = {description:``,params:{},return:null,examples:[],author:[],deprecated:false,default:null,readonly:false};
let IsInExample = false;
let ExStore = ``;
for (let line of comments.reverse()) {
if (IsInExample) {
if (!line.startsWith(`@`)) {
ExStore += `\n` + line;
continue;
} else {
FancyParse.examples.push(ExStore);
ExStore = ``;
IsInExample = false;
}
}
if (line.startsWith(`@description`) || !line.startsWith(`@`)) {
if (FancyParse.description != ``) FancyParse.description += `\n`;
FancyParse.description += line.replace(`@description`, ``).trim();
} else if (line.startsWith(`@param`)) {
let dat = line.replace(`@param`, ``).trim();
let name = dat.split(` `)[0];
let type = dat.includes("{") ? dat.split(`{`)[1].split(`}`)[0] : null;
let desc = dat.includes("{") ? dat.split(`{`)[1].split(`}`)[1].trim() : dat.split(` `).slice(1).join(` `);
FancyParse.params[name.replace(/\[|\]/g,``)] = {type:type.replace(/(\(|\))/g,``).split(`|`),description:desc,optional:name.includes(`[`)};
} else if (line.startsWith(`@return`) || line.startsWith(`@returns`)) {
let dat = line.replace(/@returns?/g, ``).trim();
let type = dat.includes("{") ? dat.split(`{`)[1].split(`}`)[0] : null;
let desc = dat.includes("{") ? dat.split(`{`)[1].split(`}`)[1].trim() : dat.split(` `).slice(1).join(` `);
FancyParse.return = {type:type.replace(/(\(|\))/g,``).split(`|`),description:desc};
} else if (line.startsWith(`@author`)) {
let dat = line.replace(`@author`, ``);
FancyParse.author.push(dat);
} else if (line.startsWith(`@example`)) {
ExStore = line.replace(`@example`,``).trim();
IsInExample = true;
} else if (line.startsWith(`@readonly`)) {
FancyParse.readonly = true
} else if (line.startsWith(`@deprecated`)) {
FancyParse.deprecated = true
}
}
if (IsInExample) FancyParse.examples.push(ExStore);
bugout.appendLine(`JsDocParse ${JSON.stringify(FancyParse)}`)
return FancyParse;
} catch(err) {
bugout.appendLine(`JS Doc Parse failure: ${err}`)
return {description: `Could not parse JSDoc information. Is it malformed?`,params:{},return:null,examples:[],author:[],deprecated:false,default:null,readonly:false};
}
}
function activate(context) {
let ARG = vscode.workspace.getConfiguration('greyscript').get('remoteGrammar');
if (ARG) UpdateGreyDocs();
let hoverD = vscode.languages.registerHoverProvider('greyscript', {
async provideHover(document, position, token) {
if (!vscode.workspace.getConfiguration("greyscript").get("hoverdocs")) return;
let range = document.getWordRangeAtPosition(position)
if (!range) return;
let word = document.getText(range)
let options = { "General": CompData["General"] };
// If there is a . in front of the text check what the previous item accesses
if (range && range.start.character - 2 >= 0 && document.getText(new vscode.Range(new vscode.Position(range.start.line, range.start.character - 1), new vscode.Position(range.start.line, range.start.character))) == ".") {
bugout.appendLine(`Hovering on a property, range ${range} | ${word}`);
let res = getOptionsBasedOfPriorCommand(document, range);
if (res) options = res;
}
bugout.appendLine(`options ${options.toString()}`)
let output = { "key": null, "cmd": null }
for (key in options) {
output.cmd = options[key].find(cmd => cmd == word);
if (output.cmd) {
output.key = key;
break;
}
}
bugout.appendLine(`determine ${output} (${output.cmd}, ${output.key})`)
if (output.key) {
return new vscode.Hover(getHoverData(output.key, output.cmd));
}
else {
// Variable hover
var hoverText = new vscode.MarkdownString("", true);
// Get Text
//let text = document.getText()
let text = await GetDocumentText(document);
let linesTillCurLine = text.split("\n").splice(0, range.start.line)
// Check if in function and maybe variable is parameter
for (line of linesTillCurLine.reverse()) {
if (line.includes("end function")) break;
if (line.match(/\w+(\s|)=(\s|)function/) && linesTillCurLine.reverse().slice(linesTillCurLine.indexOf(line)).every(l => !l.includes("end function"))) {
params = line.match(/(?<=\()(.*?)(?=\))/)[0].split(",").map(p => p.trim());
for (p of params) {
optionalParam = p.match(/\w+(\s|)=(\s|)/);
if (optionalParam) {
let name = optionalParam[0].replace(/(\s|)=(\s|)/, "");
if (name == word) {
hoverText.appendCodeblock("(parameter) " + processFunctionParameter(p));
return new vscode.Hover(hoverText);
}
}
else if (p == word) {
hoverText.appendCodeblock("(parameter) " + processFunctionParameter(p));
return new vscode.Hover(hoverText);
}
}
}
}
lines = [];
let re = new RegExp("\\b" + word + "(\\s|)=")
i = 0;
// Get all lines that interact with the variable prior to the line
for (line of text.split("\n")) {
if (i > range.start.line) break;
if (line && line.match(re)) lines.push(line);
i++;
}
// Get the assigned value
let assignment = lines[lines.length - 1];
if (!assignment || !assignment.match(re)) return;
let curline = text.slice(0,text.indexOf(assignment)).split(`\n`).length -1;
let match = assignment.match(re)[0];
assignment = assignment.substring(assignment.indexOf(match) + match.length).trim().replace(";", "");
assignment = assignment.split(".")
assignment = assignment[assignment.length - 1];
let FP = null;
if (!assignment.includes("function")) FP = JsDocParse(document, curline)
let VarHover = (FP) => {
if (FP.description) hoverText.appendText(FP.description+`\n`);
if (FP.deprecated) hoverText.appendMarkdown(`*@deprecated* \n`);
if (FP.readonly) hoverText.appendMarkdown(`*@readonly* \n`);
if (FP.author) for (let a of FP.author) hoverText.appendMarkdown(`*@author* ${a} \\`);
if (FP.examples) for (let e of FP.examples) hoverText.appendCodeblock(e, `greyscript`);
return new vscode.Hover(hoverText);
};
// If its a string type return the string hover
if (assignment.startsWith("\"")) {
hoverText.appendCodeblock("(variable) " + word + ": String")
if (FP) return VarHover(FP);
return new vscode.Hover(hoverText);
}
// If its a list type return the list hover
if (assignment.startsWith("[")) {
hoverText.appendCodeblock("(variable) " + word + ": List")
if (FP) return VarHover(FP);
return new vscode.Hover(hoverText);
}
// If its a map type return the map hover
if (assignment.startsWith("{")) {
hoverText.appendCodeblock("(variable) " + word + ": Map")
if (FP) return VarHover(FP);
return new vscode.Hover(hoverText);
}
if (!assignment.startsWith(`function`)) {
let t = assignment.split(".").pop();
//bugout.appendLine(1+":"+t);
t = t.split(" ")[0].split("(")[0];
//bugout.appendLine(2+":"+t);
let rets = [];
for (let tyk in ReturnData) {
let ty = ReturnData[tyk];
for (let k in ty) {
if (k == t) {
for (let i of ty[k]) {
let tp = i.subType ? `${i.type}[${i.subType}]` : i.type
if (!rets.includes(tp)) rets.push(tp);
}
}
}
}
if (rets == []) rets = ["any"]
hoverText.appendCodeblock(`(variable) ${word}: ${rets.join("|")}`);
if (FP) return VarHover(FP);
return new vscode.Hover(hoverText);
}
// If its a function type return the function hover
let FancyParse = null
if (assignment.startsWith("function")) {
let description = null;
//if(linesTillCurLine[linesTillCurLine.indexOf(lines[lines.length - 1]) + 1].startsWith("//")){
// description = linesTillCurLine[linesTillCurLine.indexOf(lines[lines.length - 1]) + 1].substring(2).trim();
//let preline = linesTillCurLine[linesTillCurLine.indexOf(lines[lines.length - 1]) + 1]
//let thisline = document.getText(new vscode.Range(new vscode.Position(position.line, 0), new vscode.Position(position.line + 1, 0))).replace(`\n`, ``)
//let postline = document.getText(new vscode.Range(new vscode.Position(position.line + 1, 0), new vscode.Position(position.line + 2, 0))).replace(`\n`, ``)
let preline = document.getText(new vscode.Range(curline-1,0,curline,0)).replace(`\n`,``);
let thisline = document.getText(new vscode.Range(curline,0,curline+1,0)).replace(`\n`,``);
let postline = document.getText(new vscode.Range(curline+1,0,curline+2,0)).replace(`\n`,``);
//bugout.appendLine(preline + `\n` + thisline + `\n` + postline)
//bugout.appendLine(new vscode.Position(position.line, 0) + `\n` + new vscode.Position(position.line + 1, 0) + `\n` + new vscode.Range(new vscode.Position(position.line, 0), new vscode.Position(position.line + 1, 0)))
if (preline.includes("//")) description = preline.replace(`//`, ``);
if (thisline.includes("//")) description = thisline.split(`//`)[1];
if (postline.includes("//")) description = postline.replace(`//`, ``);
if (preline.includes("//")) {
let UseFancyParser = false;
//let FancyParsingIs = [`@param`, `@return`, `@description`, `@example`, `@author`, `@deprecated`, `@readonly`]
for (let i = 1; i <= 10; i++) {
let ltcl = linesTillCurLine[linesTillCurLine.indexOf(lines[lines.length - 1]) + i]
if (ltcl && ltcl.includes("//")) {
let v = ltcl.replace(`//`, ``).trim();
/*
for (let fp of FancyParsingIs) {
if (v.includes(fp)) {
UseFancyParser = true;
break
}
}
*/
if (AnnotationExpression.test(`// ${v}`)) { bugout.appendLine(`AE PASS`); UseFancyParser = true; break; }
if (description != v) description += `\n`+v;
} else break;
};
if (UseFancyParser) {
description = ``;
FancyParse = JsDocParse(document, curline);
}
}
if (!description) description = ``;
if (FancyParse) {
let params = assignment.match(/(?<=\()(.*?)(?=\))/)[0].split(`,`);
let plist = ``;
for (let p of params) {
p=p.trim();
let pd = FancyParse.params[p] ? FancyParse.params[p] : {type:[`any`],description:``,optional:false};
plist += `${p}${pd.optional ? '?' : ''}: ${pd.type.join("|")}, `;
};
plist=plist.trim();
if (plist.endsWith(`,`)) plist = plist.slice(0,-1);
hoverText.appendCodeblock(`function ${word}(${plist}) : ${FancyParse.return && FancyParse.return.type ? FancyParse.return.type.join("|") : 'any'}`, `greyscript`);
if (FancyParse.description) description = FancyParse.description + `\n` + description;
if (description && description != ``) { hoverText.appendText(description); description = `` };
let revpar = Object.keys(FancyParse.params);
//revpar.reverse();
for (let p of revpar) {
hoverText.appendMarkdown(`*@param* \`${p}\` — ${FancyParse.params[p].description} \n`)
}
if (FancyParse.return) hoverText.appendMarkdown(` \n*@return* \`${FancyParse.return.type.join(" | ")}\` — ${FancyParse.return.description} \n`)
for (let a of FancyParse.author) {
hoverText.appendMarkdown(`*@author* ${a} \n`);
}
if (FancyParse.examples) {
for (let e of FancyParse.examples) {
hoverText.appendCodeblock(e, `greyscript`);
}
}
if (FancyParse.deprecated) hoverText.appendMarkdown(`*@deprecated* \n`);
} else hoverText.appendCodeblock("(function) " + word + "(" + assignment.match(/(?<=\()(.*?)(?=\))/)[0] + ")", `greyscript`)
if (word.includes("gk")) description += `\ngk258 is my hero!`;
if (description && description != ``) hoverText.appendText(description.trim());
return new vscode.Hover(hoverText);
}
}
}
})
if (vscode.workspace.getConfiguration("greyscript").get("hoverdocs")) context.subscriptions.push(hoverD)
context.subscriptions.push(vscode.languages.registerDeclarationProvider('greyscript', {
provideDeclaration(document, position, token) {
locations = [];
let range = document.getWordRangeAtPosition(position);
let word = document.getText(range);
let re = RegExp("\\b.*" + word + "?\\s*=", 'g');
vscode.workspace.textDocuments.forEach(async document => {
let filename = document.fileName;
if (filename.endsWith(".git")) {
return;
}
let text = document.getText()
//let text = await GetDocumentText(document);
let matches = text.matchAll(re);
let match = matches.next();
while (!match.done) {
let index = match.value.index;
let nt = text.slice(0, index);
let lines = nt.split(new RegExp("\n", "g")).length;
let Pos = new vscode.Position(lines - 1, word.length);
locations.push(new vscode.Location(document.uri, Pos));
match = matches.next();
}
});
return locations
}
}));
/*
let foldD = vscode.languages.registerFoldingRangeProvider('greyscript', {
provideFoldingRanges(document, foldContext, token) {
bugout.appendLine(`Request To Provide Folding Ranges`);
let Text = document.getText();
let kind = vscode.FoldingRangeKind.Region;
var List = [];
let Exp = new RegExp(`( = |=) function`, `g`);
let Matches = Text.matchAll(Exp);
bugout.appendLine(`Folding Matches`);
bugout.appendLine(Matches);
var i;
for (i of Matches) {
let index = i.index;
bugout.appendLine(`I: ${index}`);
let stext = Text.slice(0,index);
let text = Text.slice(index,Text.length);
bugout.appendLine(`T: ${text}`);
let Exp = new RegExp("end function");
let M = text.match(Exp)
bugout.appendLine(`M: ${M}`)
if (!M) continue;
M = M.index+index;
bugout.appendLine(`M: ${M}`);
let start = stext.split("\n").length-1;
let etext = Text.slice(0, M);
let end = etext.split("\n").length-1;
let F = new vscode.FoldingRange(start, end, kind);
List.push(F);
};
bugout.appendLine(`Folding Ranges`)
bugout.appendLine(List);
return List;
}
})
context.subscriptions.push(foldD);
*/
let getHoverData = (type, cmd, asMarkdown = true) => {
// Create markdownString
let str = new vscode.MarkdownString("", true);
// Get type of cmd
let cmdType = CompTypes[cmd] || CompTypes["default"];
// Get type text, example: Shell.
typeText = "";
if (type != "General") typeText = type + ".";
// Combine base data together
let docs = { "title": "(" + enumCompTypeText[cmdType] + ") " + typeText + cmd, "description": "" };
// Add arguments if its a function/method
if (cmdType == 2 || cmdType == 1) {
docs.title += "(" + (ArgData[type][cmd] || []).map(d => d.name + (d.optional ? "?" : "") + ": " + d.type + (d.type == "Map" || d.type == "List" ? `[${d.subType}]` : "")).join(", ") + ")";
}
// Add result
docs.title += ": " + (ReturnData[type][cmd] || []).map(d => d.type + (d.type == "Map" || d.type == "List" ? `[${d.subType}]` : "")).join("|");
// Add info/hover text
docs.description = HoverData[type][cmd] || "";
// Apply encryption text to hover text if available
if (Encryption.includes(`${type}.${cmd}`)) docs.description += "\n\n\**This function cannot be used in encryption.*";
// Apply nightly text to hover text if available
if (Nightly.includes(`${type}.${cmd}`)) docs.description += "\n\n\**This function is either introduced or changed in the nightly build of the game. These functions are subject to change or removal at any time.";
// Add examples
let codeExamples = Examples[type] ? Examples[type][cmd] || [] : [];
// Return normal text
if (!asMarkdown) return docs.title + "\n\n\n" + docs.description.replace(/<[^>]*>?/gm, '') + "\n\n" + codeExamples.join("\n\n\n");
// Append markdown string areas
str.appendCodeblock(docs.title);
str.appendMarkdown("---\n" + docs.description);
if (codeExamples.length > 0) {
str.appendMarkdown("\n### Examples\n---");
str.appendCodeblock(codeExamples.join("\n\n"));
}
// Return markdown string
return str;
}
let getOptionsBasedOfPriorCommand = (document, range) => {
//bugout.appendLine("Checking item before .");
// Get Target if there was a delimiter before starting character
//bugout.appendLine(`gOBOPC: ${range}, ${range.start.line}:${range.start.character}`)
let targetRange = document.getWordRangeAtPosition(new vscode.Position(range.start.line, range.start.character - 2));
if (!targetRange) targetRange = document.getWordRangeAtPosition(new vscode.Position(range.start.line, range.start.character - 3));
if (!targetRange) targetRange = document.getWordRangeAtPosition(new vscode.Position(range.start.line, range.start.character - 4));
//bugout.appendLine(`gOBOPC tR ${targetRange}`);
if (!targetRange) return []; // No target, return empty array
let targetWord = document.getText(targetRange);
//bugout.appendLine(targetWord)
// Find type of target
// Check if target is command
let prevCmd = null;
for (type in CompData) {
for (cmd of CompData[type]) {
if (cmd == targetWord) {
prevCmd = { "type": type, "cmd": cmd };
break;
}
}
if (prevCmd) break;
}
//bugout.appendLine(prevCmd);
// Get return data from command
if (prevCmd) {
//bugout.appendLine("prevcmd!")
let returnValues = ReturnData[prevCmd.type][prevCmd.cmd];
let options = {};
// Get options based of return value
for (returnValue of returnValues) {
if (!CompData[returnValue.type]) continue;
options[returnValue.type] = CompData[returnValue.type];
}
//bugout.appendLine("done prevcmd!")
return Object.keys(options).length > 0 ? options : undefined;
}
else {
//bugout.appendLine("no prevcmd!")
// Check variable assignment if its not a command
let text = document.getText()
lines = [];
let re = new RegExp("\\b" + targetWord + "(\\s|)=")
i = 0;
// Get all lines that interact with the variable prior to the line
for (line of text.split("\n")) {
if (i > targetRange.start.line) break;
if (line.match(re)) lines.push(line);
i++;
}
// Get the assigned value
let assignment = lines[lines.length - 1];
if (!assignment) return CompData;
let matches = assignment.match(re);
if (!matches) return CompData;
let match = matches[0];
assignment = assignment.substring(assignment.indexOf(match) + match.length).trim().replace(";", "");
if (assignment.includes(".")) {
assignment = assignment.split(".");
assignment = assignment[assignment.length - 1];
}
if (assignment.includes("+")) {
assignment = assignment.split("+");
assignment = assignment[assignment.length - 1];
}
assignment = assignment.trim();
// If its a string type return the string options
if (assignment.startsWith("\"")) return { "String": CompData["String"] };
// If its a list type return the list options
if (assignment.startsWith("[")) return { "List": CompData["List"] };
// If its a map type return the list options
if (assignment.startsWith("{")) return { "Map": CompData["Map"] };
// Check if value is command
for (type in CompData) {
for (cmd of CompData[type]) {
if (cmd == assignment) {
prevCmd = { "type": type, "cmd": cmd };
break;
}
}
if (prevCmd) break;
}
// Set options based off command
if (prevCmd) {
let returnValues = ReturnData[prevCmd.type][prevCmd.cmd];
options = {};
// Get options based of return value
for (returnValue of returnValues) {
if (!CompData[returnValue.type]) continue;
options[returnValue.type] = CompData[returnValue.type];
}
return Object.keys(options).length > 0 ? options : undefined;
}
else {
bugout.appendLine("Greyscript: Target is unknown returning all CompData.")
return CompData;
}
}
}
let compD = vscode.languages.registerCompletionItemProvider('greyscript', {
async provideCompletionItems(document, position, token, ccontext) {
bugout.appendLine(`Get Completion Options`)
if (!vscode.workspace.getConfiguration("greyscript").get("autocomplete")) return;
let out = [];
// Set default options (THIS IS ALSO THE FALLBACK)
let options = { "General": CompData["General"] };
// Get typed word
let range = document.getWordRangeAtPosition(position);
if (!range) {
for (key in options) {
for (c of options[key]) {
//bugout.appendLine("Processing result: " + c);
// Get type of completion item
let type = CompTypes[c] || CompTypes["default"];
// Create completion item
let t = new vscode.CompletionItem(c, type)
// Add hover data to completion item
t.documentation = getHoverData(key, c);
t.commitCharacters = [".", ";"]
// Push completion item to result array
out.push(t);
}
}
return new vscode.CompletionList(out, true);
}
let word = document.getText(range);
if (!word) return;
//bugout.appendLine(word);
let variableOptions = [];
// If there is a . in front of the text check what the previous item accesses
if (range && range.start.character - 2 >= 0 && document.getText(new vscode.Range(new vscode.Position(range.start.line, range.start.character - 1), new vscode.Position(range.start.line, range.start.character))) == ".") {
let res = getOptionsBasedOfPriorCommand(document, range);
if (res) options = res;
}
else {
// Get All user defined variables
//let linesTillLine = document.getText(new vscode.Range(new vscode.Position(0, 0), range.start))
let linesTillLine = await GetDocumentText(document, new vscode.Range(new vscode.Position(0, 0), range.start));
matches = linesTillLine.matchAll(/\b(\w+(\s|)=|end function)/g);
let inFunction = false;
let functionVars = [];
if (matches) {
for (match of Array.from(matches).reverse()) {
//bugout.appendLine(`MATCHED, ${match}, ${match[0]}`)
let fullMatch = match[0];
variableName = fullMatch.replace(/(\s|)=/, "");
if (variableOptions.every(m => m.name !== variableName)) {
if (fullMatch == "end function") {
inFunction = true;
functionVars = [];
continue;
}
let assignment = linesTillLine.substring(match.index, linesTillLine.indexOf("\n", match.index));
assignment = assignment.substring(assignment.indexOf("=") + 1).trim();
//bugout.appendLine(`ASSIGNMENT: ${assignment}`)
if (assignment.startsWith("function")) {
//bugout.appendLine(`Found function ${variableName}`)
inFunction = false;
try {
params = assignment.match(/(?<=\()(.*?)(?=\))/)[0].split(",").map(p => p.trim());
for (p of params) {
//bugout.appendLine(`PARSE PARAM ${p}`)
optionalParam = p.match(/\w+(\s|)=(\s|)/);
if (optionalParam) {
let name = optionalParam[0].replace(/(\s|)=(\s|)/, "");
functionVars.push({ "name": name, "type": 5 });
}
else functionVars.push({ "name": p, "type": 5 });
}
} catch (err) {
bugout.appendLine(`Failed to parse function params: ${err}`)
}
}
let variable = { "name": variableName, "type": (assignment.startsWith("function") ? 2 : 5) }
if (inFunction) functionVars.push(variable);
else variableOptions.push(variable);
//bugout.appendLine(`POST MATCH ${match[0]}`)
}
}
variableOptions = variableOptions.concat(functionVars);
}
}
//bugout.appendLine(`VOPT`)
//bugout.appendLine(variableOptions);
let output = {};
// Get autocompletion of type and filter
for (key in options) {
let keyOutput = options[key].filter(cmd => cmd.includes(word));
if (keyOutput.length > 0) output[key] = keyOutput;
}
let variablesOutput = [];
// Get autocompletion of variableNames
for (variable of variableOptions) {
if (variable.name.includes(word)) variablesOutput.push(variable);
}
//bugout.appendLine(output);
// Instantiate result array
// Instantiate sort text index
//var a = 0;
// Go through filtered results
for (key in output) {
for (c of output[key]) {
//bugout.appendLine("Processing result: " + c);
// Get type of completion item
let type = CompTypes[c] || CompTypes["default"];
// Create completion item
let t = new vscode.CompletionItem(c, type)
// Add hover data to completion item
t.documentation = getHoverData(key, c);
t.commitCharacters = [".", ";"]
// Push completion item to result array
out.push(t);
// Increment sort text index
//a++
}
}
// Go through filtered variables
for (variable of variablesOutput) {
out.push(new vscode.CompletionItem(variable.name, variable.type));
}
//bugout.appendLine("AutoCompletion result:");
//bugout.appendLine(out);
// Return completion items
return new vscode.CompletionList(out, true);
}
});
function processFunctionParameter(p) {
if (p.length == 0) return "";
// Parse the user defined function parameters
optionalParam = p.match(/\b\w+(\s|)=(\s|)/);
if (optionalParam) {
let value = p.substring(optionalParam[0].length);
let name = optionalParam[0].replace(/(\s|)=(\s|)/, "");
if (value == "true" || value == "false") return name + ": Bool";
else if (!isNaN(value)) return name + ": Number";
else if (value.startsWith("\"")) return name + ": String";
else if (value.startsWith("[")) return name + ": List";
else if (value.startsWith("{")) return name + ": Map";
else return name + ": any";
}
else return p.trim() + ": any"
}
if (vscode.workspace.getConfiguration("greyscript").get("autocomplete")) {
context.subscriptions.push(compD)
context.subscriptions.push(vscode.languages.registerSignatureHelpProvider("greyscript", {
async provideSignatureHelp(document, position, token, ctx) {
// Check if current line is not a function creation
let re = RegExp("(\\s|)=(\\s|)function");
let curLine = document.lineAt(position.line);
let textTillCharacter = curLine.text.slice(0, position.character);
if ((ctx.triggerCharacter == "(" && curLine.text.match(re)) || textTillCharacter.lastIndexOf("(") < 1) return;
if (textTillCharacter.split("(").length === textTillCharacter.split(")").length) return;
// Get the function being called
let range = document.getWordRangeAtPosition(new vscode.Position(position.line, curLine.text.lastIndexOf("(") - 1));
let word = await GetDocumentText(document, range);
// Create default signature help
let t = new vscode.SignatureHelp();
if (curLine.text.match(/(?<=\()(.*?)(?=\))/)) t.activeParameter = curLine.text.match(/(?<=\()(.*?)(?=\))/)[0].split(",").length - 1;
t.signatures = [];
t.activeSignature = 0;
// Get all the possible signatures from comp data
for (key in CompData) {
if (CompData[key].includes(word)) {
let cmdType = CompTypes[word] || CompTypes["default"];
if (cmdType != 2 && cmdType != 1) continue;
args = (ArgData[key][word] || []).map(d => d.name + (d.optional ? "?" : "") + ": " + d.type + (d.type == "Map" || d.type == "List" ? `[${d.subType}]` : "")).join(", ")
results = ": " + (ReturnData[key][word] || []).map(d => d.type + (d.type == "Map" || d.type == "List" ? `[${d.subType}]` : "")).join(" or ")
let info = new vscode.SignatureInformation(key + "." + word + "(" + args + ")" + results);
info.parameters = [];
for (param of args.split(",")) {
let p = new vscode.ParameterInformation(param.trim(), "");
if (param.trim().length > 0) info.parameters.push(p);
}
t.signatures.push(info);
}
}
// Get all lines till this line
let text = await GetDocumentText(document)
let linesTillLine = text.split("\n").splice(0, range.start.line)
re = RegExp("\\b" + word + "(\\s|)=(\\s|)function");
// Get last defined user function using this word
let func = null;
let desc = null;
for (line of linesTillLine.reverse()) {
matches = line.match(re);
if (matches) {
func = line;
if (linesTillLine[linesTillLine.indexOf(line) + 1].startsWith("//")) desc = linesTillLine[linesTillLine.indexOf(line) + 1].substring(2).trim();
break;
}
}
// If no user defined function is found return the current signatures
if (!func) return t;
// Parse the signature information
let params = func.match(/(?<=\()(.*?)(?=\))/)[0];
let info = new vscode.SignatureInformation(word + "(" + params.split(",").map(p => processFunctionParameter(p)).join(", ") + "): any");
info.parameters = [];
if (desc) info.documentation = desc;
// Go through all parameters and register them
for (param of params.split(",")) {
let p = param.trim();
let processed = processFunctionParameter(p)
let pInfo = new vscode.ParameterInformation(processed);
if (p.length > 0) info.parameters.push(pInfo);
}
// Push the user defined function as a signature
t.signatures.push(info);
// Return all found signatures
return t;
}
}, [",", "("]))
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
a: result[4] ? parseInt(result[4], 16) : 255,
} : null;
}
function rgbToHex(r, g, b, a) {
r = (r * 255).toString(16);
g = (g * 255).toString(16);
b = (b * 255).toString(16);
a = (a * 255).toString(16);
if (r.length == 1)
r = "0" + r;
if (g.length == 1)
g = "0" + g;
if (b.length == 1)
b = "0" + b;
if (a.length == 1)
a = "0"+a;
return "#" + r + g + b + a;
}
// Returns an array of vscode Ranges for any matching text in the document.
function RegExpToRanges(document, exp, group = 0, postfunc = null) {
//bugout.appendLine(`RETR 1 ${exp} (${group}) [${postfunc}]`)
let out = [];
let text = document.getText();
//bugout.appendLine(`RETR 1.5 DocLen ${text.length}`)
exp.global = true;
let iter = text.matchAll(exp);
//bugout.appendLine(`RETR 2: ${iter}`)
for (let m of iter) {
let textbf = text.slice(0, m.index);
let textaf = text.slice(0, m.index + m[0].length);
let textbfs = textbf.split("\n");
let textafs = textaf.split("\n");
let startline = textbfs.length;
let endline = textafs.length;
//let startchar = m.index - textbf.length