-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
1184 lines (1010 loc) · 42.9 KB
/
extension.js
File metadata and controls
1184 lines (1010 loc) · 42.9 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 vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const IDENT_PATTERN = '[A-Za-z_][A-Za-z0-9_]*';
const TYPE_PATTERN = `${IDENT_PATTERN}(?:\\s*<[^>]+>)?(?:\\s*\\[[^\\]]*\\])*\\s*&?`;
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// =========================================================
// Coi Formatter
// =========================================================
class CoiFormatter {
constructor() {
this.indentSize = 4;
this.useSpaces = true;
// Block-level HTML elements that should be on their own lines
this.blockElements = new Set([
'div', 'p', 'section', 'article', 'header', 'footer', 'nav', 'main', 'aside',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'form', 'fieldset',
'blockquote', 'pre', 'canvas', 'video', 'audio', 'figure', 'figcaption'
]);
}
format(text, options = {}) {
this.indentSize = options.tabSize || 4;
this.useSpaces = options.insertSpaces !== false;
const lines = text.split('\n');
const formattedLines = [];
let indentLevel = 0;
let inViewBlock = false;
let inStyleBlock = false;
let styleBlockBraceCount = 0;
let cssIndentLevel = 0;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
let trimmed = line.trim();
// Skip empty lines but preserve them
if (trimmed === '') {
formattedLines.push('');
continue;
}
// Handle style blocks (CSS formatting with proper indentation)
if (inStyleBlock) {
// Count braces in this line
const openBraces = (trimmed.match(/\{/g) || []).length;
const closeBraces = (trimmed.match(/\}/g) || []).length;
// Decrease indent if line starts with closing brace
if (trimmed.startsWith('}')) {
cssIndentLevel = Math.max(0, cssIndentLevel - 1);
}
styleBlockBraceCount += openBraces - closeBraces;
if (styleBlockBraceCount <= 0) {
// End of style block
inStyleBlock = false;
indentLevel = Math.max(0, indentLevel - 1);
formattedLines.push(this.indent(indentLevel) + trimmed);
styleBlockBraceCount = 0;
cssIndentLevel = 0;
} else {
// Inside style block - apply CSS indentation
formattedLines.push(this.indent(indentLevel + cssIndentLevel) + trimmed);
// Increase indent if line ends with opening brace
if (trimmed.endsWith('{')) {
cssIndentLevel++;
}
}
continue;
}
// Check for style block start
if (/^style\s*(global)?\s*\{/.test(trimmed)) {
formattedLines.push(this.indent(indentLevel) + this.formatStyleDeclaration(trimmed));
inStyleBlock = true;
styleBlockBraceCount = 1;
indentLevel++;
continue;
}
// Check for view block start
if (/^view\s*\{/.test(trimmed)) {
formattedLines.push(this.indent(indentLevel) + trimmed);
inViewBlock = true;
indentLevel++;
continue;
}
// Handle end of view block
if (inViewBlock && trimmed === '}') {
inViewBlock = false;
indentLevel = Math.max(0, indentLevel - 1);
formattedLines.push(this.indent(indentLevel) + trimmed);
continue;
}
// Handle HTML/view block indentation
if (inViewBlock && trimmed.startsWith('<')) {
// Break up nested block elements onto separate lines
const expandedLines = this.expandBlockElements(trimmed);
for (const expandedLine of expandedLines) {
const expTrimmed = expandedLine.trim();
if (!expTrimmed) continue;
// Decrease indent for closing tags BEFORE outputting
if (expTrimmed.startsWith('</')) {
indentLevel = Math.max(0, indentLevel - 1);
formattedLines.push(this.indent(indentLevel) + expTrimmed);
} else {
// Output the line
formattedLines.push(this.indent(indentLevel) + expTrimmed);
// Increase indent for opening block tags (not self-closing)
const netIndent = this.calculateNetIndent(expTrimmed);
indentLevel += netIndent;
indentLevel = Math.max(0, indentLevel);
}
}
continue;
}
// Handle regular code (non-style, non-view)
// Determine if we should decrease indent before this line
const startsWithClose = /^[\}\]]/.test(trimmed);
if (startsWithClose && indentLevel > 0) {
indentLevel--;
}
// Format the line
let formattedLine = this.formatLine(trimmed, inViewBlock);
formattedLines.push(this.indent(indentLevel) + formattedLine);
// Determine if we should increase indent after this line
const endsWithOpen = /[\{\[]$/.test(trimmed) && !/\}$/.test(trimmed);
if (endsWithOpen) {
indentLevel++;
}
// Ensure indent level doesn't go negative
indentLevel = Math.max(0, indentLevel);
}
return formattedLines.join('\n');
}
formatLine(line, inView) {
// Don't format comments
if (line.startsWith('//')) {
return line;
}
// Format component declaration
if (line.startsWith('component ')) {
return this.formatComponentDeclaration(line);
}
// Format function declaration
if (line.startsWith('def ')) {
return this.formatFunctionDeclaration(line);
}
// Don't try to format lines in view blocks (HTML-like content)
if (inView && (line.startsWith('<') || line.includes('{') || line.includes('}'))) {
return line;
}
// Format variable declarations
if (new RegExp(`^(?:pub\\s+)?(?:mut\\s+)?${TYPE_PATTERN}\\s+${IDENT_PATTERN}\\b`).test(line)) {
return this.formatVariableDeclaration(line);
}
// Format operators with proper spacing
line = this.formatOperators(line);
return line;
}
formatComponentDeclaration(line) {
// component Name(params) {
return line
.replace(/component\s+/, 'component ')
.replace(/\(\s*/g, '(')
.replace(/\s*\)/g, ')')
.replace(/\s*,\s*/g, ', ')
.replace(/\s*\{\s*$/, ' {');
}
formatFunctionDeclaration(line) {
// def name(params) : returnType {
return line
.replace(/def\s+/, 'def ')
.replace(/\(\s*/g, '(')
.replace(/\s*\)/g, ')')
.replace(/\s*,\s*/g, ', ')
.replace(/\s*:\s*/g, ' : ')
.replace(/\s*\{\s*$/, ' {');
}
formatVariableDeclaration(line) {
// pub mut Type name = value;
return line
.replace(/pub\s+/, 'pub ')
.replace(/mut\s+/, 'mut ')
.replace(/\s*=\s*/g, ' = ')
.replace(/\s*;\s*$/, ';');
}
formatStyleDeclaration(line) {
return line
.replace(/style\s*(global)?\s*\{/, (m, global) => global ? 'style global {' : 'style {');
}
formatOperators(line) {
// Don't format inside strings or braces (could be expressions)
const protectedList = [];
let protectedIndex = 0;
// Protect strings
line = line.replace(/"[^"]*"/g, (match) => {
protectedList.push(match);
return `__PROTECTED_${protectedIndex++}__`;
});
// Protect expressions in braces
line = line.replace(/\{[^}]*\}/g, (match) => {
protectedList.push(match);
return `__PROTECTED_${protectedIndex++}__`;
});
// Format operators
line = line
// Move assignment operator := (keep together)
.replace(/\s*:=\s*/g, ' := ')
// Comparison operators
.replace(/\s*==\s*/g, ' == ')
.replace(/\s*!=\s*/g, ' != ')
.replace(/\s*<=\s*/g, ' <= ')
.replace(/\s*>=\s*/g, ' >= ')
// Logical operators
.replace(/\s*&&\s*/g, ' && ')
.replace(/\s*\|\|\s*/g, ' || ')
// Shift operators (before single < or >)
.replace(/\s*<<=/g, ' <<= ')
.replace(/\s*>>=/g, ' >>= ')
.replace(/\s*<</g, ' << ')
.replace(/\s*>>/g, ' >> ')
// Bitwise compound assignment
.replace(/\s*&=\s*/g, ' &= ')
.replace(/\s*\|=\s*/g, ' |= ')
.replace(/\s*\^=\s*/g, ' ^= ')
// Assignment operators (but not :=)
.replace(/\s*\+=\s*/g, ' += ')
.replace(/\s*-=\s*/g, ' -= ')
.replace(/\s*\*=\s*/g, ' *= ')
.replace(/\s*\/=\s*/g, ' /= ')
// Bitwise operators (with spaces around binary use)
.replace(/\s*\|\s*/g, ' | ')
.replace(/\s*\^\s*/g, ' ^ ')
// Simple assignment (but not == or != or := or &= etc.)
.replace(/([^=!<>+\-*/:&|^])\s*=\s*([^=])/g, '$1 = $2');
// Restore protected sections
protectedList.forEach((str, i) => {
line = line.replace(`__PROTECTED_${i}__`, str);
});
return line;
}
indent(level) {
const char = this.useSpaces ? ' ' : '\t';
const size = this.useSpaces ? this.indentSize : 1;
return char.repeat(level * size);
}
calculateNetIndent(line) {
// Count opening and closing tags on this line
const selfClosingCount = (line.match(/<[^>]+\/>/g) || []).length;
const openingCount = (line.match(/<[a-zA-Z][^>]*>/g) || []).length;
const closingCount = (line.match(/<\/[^>]+>/g) || []).length;
// Net change in indent (opening tags that aren't self-closing, minus closing tags)
return (openingCount - selfClosingCount) - closingCount;
}
isBlockElement(tagName) {
return this.blockElements.has(tagName.toLowerCase());
}
expandBlockElements(line) {
// Check if line has nested block elements that should be split
// Pattern: <footer><p>content</p></footer> -> split block elements to separate lines
const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9-]*)[^>]*>/g;
const tags = [];
let match;
while ((match = tagRegex.exec(line)) !== null) {
const fullTag = match[0];
const tagName = match[1];
const isClosing = fullTag.startsWith('</');
const isSelfClosing = fullTag.endsWith('/>');
tags.push({
tag: fullTag,
name: tagName,
isClosing,
isSelfClosing,
index: match.index,
endIndex: match.index + fullTag.length
});
}
// Only expand if we have multiple BLOCK elements (not inline like <a>, <span>)
const blockTags = tags.filter(t => this.isBlockElement(t.name));
if (blockTags.length <= 1) {
return [line]; // No expansion needed - single block or all inline
}
// Special case: Don't expand if it's just a single block element wrapping content
// e.g. <div class="logo">.coi</div> or <h1>Title</h1>
if (blockTags.length === 2 &&
!blockTags[0].isClosing &&
blockTags[1].isClosing &&
blockTags[0].name === blockTags[1].name) {
return [line];
}
// Split: output block tags on their own lines, keeping inline content together
const result = [];
let pos = 0;
for (let i = 0; i < blockTags.length; i++) {
const tag = blockTags[i];
// Content between last position and this block tag
const contentBefore = line.substring(pos, tag.index).trim();
if (tag.isClosing) {
// For closing block tag: output content first, then the tag
if (contentBefore) {
result.push(contentBefore);
}
result.push(tag.tag);
} else {
// Opening block tag: output content first, then the tag
if (contentBefore) {
result.push(contentBefore);
}
result.push(tag.tag);
}
pos = tag.endIndex;
}
// Any remaining content after the last block tag
const remaining = line.substring(pos).trim();
if (remaining) {
result.push(remaining);
}
return result.length > 0 ? result : [line];
}
}
// =========================================================
// Coi Definition Parser
// =========================================================
class CoiDefinitions {
constructor() {
this.types = new Map(); // type Name { ... }
this.namespaces = new Map(); // namespace Name { ... }
this.components = new Map(); // component Name { ... } from user files
this.defBasePath = null; // Base path for def files (cached)
}
// Parse all .d.coi files from a directory (recursively)
loadFromDirectory(defPath) {
if (!fs.existsSync(defPath)) return;
// Cache the base path for later use
this.defBasePath = defPath;
const loadRecursive = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
loadRecursive(fullPath);
} else if (entry.name.endsWith('.d.coi')) {
const content = fs.readFileSync(fullPath, 'utf8');
// Pass the full absolute path as source
this.parseDefinitionFile(content, fullPath);
}
}
};
loadRecursive(defPath);
}
// Parse a single .d.coi file
parseDefinitionFile(content, sourcePath) {
const lines = content.split('\n');
const typeDefRegex = new RegExp(`^type\\s+def\\s+(${IDENT_PATTERN})(?:\\s*<([^>]+)>)?\\s*\\(([^)]*)\\)\\s*:\\s*(${TYPE_PATTERN})`);
const defRegex = new RegExp(`^def\\s+(${IDENT_PATTERN})(?:\\s*<([^>]+)>)?\\s*\\(([^)]*)\\)\\s*:\\s*(${TYPE_PATTERN})`);
let currentBlock = null; // { kind: 'type'|'namespace', name: string, methods: [] }
let braceDepth = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const trimmed = line.trim();
const lineNumber = i + 1; // 1-based line number
// Skip comments and empty lines
if (trimmed.startsWith('//') || trimmed === '') continue;
// Match type or namespace declaration
const typeMatch = trimmed.match(/^type\s+(\w+)(?:\s+extends\s+(\w+))?\s*\{/);
const nsMatch = trimmed.match(/^namespace\s+(\w+)\s*\{/);
if (typeMatch) {
currentBlock = {
kind: 'type',
name: typeMatch[1],
extends: typeMatch[2] || null,
methods: [],
typeMethods: [], // type def (static)
source: sourcePath, // Full absolute path
line: lineNumber
};
braceDepth = 1;
continue;
}
if (nsMatch) {
currentBlock = {
kind: 'namespace',
name: nsMatch[1],
methods: [],
source: sourcePath, // Full absolute path
line: lineNumber
};
braceDepth = 1;
continue;
}
if (currentBlock) {
// Track braces
braceDepth += (line.match(/\{/g) || []).length;
braceDepth -= (line.match(/\}/g) || []).length;
// Parse method definitions
// type def methodName(...): ReturnType { ... }
const typeDefMatch = trimmed.match(typeDefRegex);
// def methodName(...): ReturnType { ... }
const defMatch = trimmed.match(defRegex);
// // maps to: ns::func
const mapsToMatch = trimmed.match(/\/\/\s*maps to:\s*(\w+)::(\w+)/);
if (typeDefMatch) {
const method = {
name: typeDefMatch[1],
typeParams: this.parseTypeParams(typeDefMatch[2]),
params: this.parseParams(typeDefMatch[3]),
returnType: typeDefMatch[4].trim(),
isTypeMethod: true,
mapsTo: null,
line: lineNumber
};
currentBlock.typeMethods.push(method);
currentBlock._lastMethod = method;
} else if (defMatch) {
const method = {
name: defMatch[1],
typeParams: this.parseTypeParams(defMatch[2]),
params: this.parseParams(defMatch[3]),
returnType: defMatch[4].trim(),
isTypeMethod: false,
mapsTo: null,
line: lineNumber
};
currentBlock.methods.push(method);
currentBlock._lastMethod = method;
} else if (mapsToMatch && currentBlock._lastMethod) {
currentBlock._lastMethod.mapsTo = `${mapsToMatch[1]}::${mapsToMatch[2]}`;
}
// End of block
if (braceDepth === 0) {
delete currentBlock._lastMethod;
if (currentBlock.kind === 'type') {
this.types.set(currentBlock.name, currentBlock);
} else {
this.namespaces.set(currentBlock.name, currentBlock);
}
currentBlock = null;
}
}
}
}
// Parse parameter list: "x: int, y: float" -> [{name: 'x', type: 'int'}, ...]
parseParams(paramStr) {
if (!paramStr.trim()) return [];
return paramStr.split(',').map(p => {
const [name, type] = p.split(':').map(s => s.trim());
return { name, type };
});
}
parseTypeParams(typeParamStr) {
if (!typeParamStr || !typeParamStr.trim()) return [];
return typeParamStr
.split(',')
.map(param => param.trim())
.filter(Boolean);
}
// Parse a user .coi file to extract components
parseUserFile(content) {
const components = new Map();
const lines = content.split('\n');
const methodRegex = new RegExp(`^def\\s+(${IDENT_PATTERN})(?:\\s*<([^>]+)>)?\\s*\\(([^)]*)\\)\\s*:\\s*(${TYPE_PATTERN})`);
const propRegex = new RegExp(`^prop\\s+(mut\\s+)?(${TYPE_PATTERN})\\s+(${IDENT_PATTERN})\\b`);
const stateRegex = new RegExp(`^(mut\\s+)?(${TYPE_PATTERN})\\s+(${IDENT_PATTERN})\\s*=`);
let currentComponent = null;
let braceDepth = 0;
for (const line of lines) {
const trimmed = line.trim();
// component Name {
const compMatch = trimmed.match(/^component\s+(\w+)\s*\{/);
if (compMatch) {
currentComponent = {
name: compMatch[1],
props: [],
state: [],
methods: []
};
braceDepth = 1;
continue;
}
if (currentComponent) {
braceDepth += (line.match(/\{/g) || []).length;
braceDepth -= (line.match(/\}/g) || []).length;
// prop mut? type& name;
const propMatch = trimmed.match(propRegex);
if (propMatch) {
const rawType = propMatch[2].trim();
const reference = rawType.endsWith('&');
currentComponent.props.push({
name: propMatch[3],
type: reference ? rawType.slice(0, -1).trim() : rawType,
mutable: !!propMatch[1],
reference
});
}
// mut? type name = ...;
const stateMatch = trimmed.match(stateRegex);
if (stateMatch && !trimmed.startsWith('prop')) {
currentComponent.state.push({
name: stateMatch[3],
type: stateMatch[2].trim(),
mutable: !!stateMatch[1]
});
}
// def name(...) : type {
const methodMatch = trimmed.match(methodRegex);
if (methodMatch) {
currentComponent.methods.push({
name: methodMatch[1],
typeParams: this.parseTypeParams(methodMatch[2]),
params: this.parseParams(methodMatch[3]),
returnType: methodMatch[4].trim()
});
}
if (braceDepth === 0) {
components.set(currentComponent.name, currentComponent);
currentComponent = null;
}
}
}
return components;
}
}
// =========================================================
// VS Code Extension
// =========================================================
let definitions = new CoiDefinitions();
const formatter = new CoiFormatter();
function activate(context) {
console.log('Coi Language extension activated');
// Load definitions from coi --defs-path or custom path
loadDefinitions(context);
// Register completion provider
const completionProvider = vscode.languages.registerCompletionItemProvider(
'coi',
{
provideCompletionItems(document, position) {
return getCompletions(document, position);
}
},
'.', // Trigger on dot
'<' // Trigger on < for view element tags
);
// Register hover provider
const hoverProvider = vscode.languages.registerHoverProvider('coi', {
provideHover(document, position) {
return getHover(document, position);
}
});
// Register signature help
const signatureProvider = vscode.languages.registerSignatureHelpProvider(
'coi',
{
provideSignatureHelp(document, position) {
return getSignatureHelp(document, position);
}
},
'(', ','
);
// Register definition provider (Ctrl+Click go to definition)
const definitionProvider = vscode.languages.registerDefinitionProvider('coi', {
provideDefinition(document, position) {
return getDefinition(document, position);
}
});
// Register document formatter
const formattingProvider = vscode.languages.registerDocumentFormattingEditProvider('coi', {
provideDocumentFormattingEdits(document) {
const text = document.getText();
const options = {
tabSize: vscode.workspace.getConfiguration('editor').get('tabSize', 4),
insertSpaces: vscode.workspace.getConfiguration('editor').get('insertSpaces', true)
};
const formatted = formatter.format(text, options);
if (formatted === text) {
return [];
}
const fullRange = new vscode.Range(
document.positionAt(0),
document.positionAt(text.length)
);
return [vscode.TextEdit.replace(fullRange, formatted)];
}
});
// Register range formatter
const rangeFormattingProvider = vscode.languages.registerDocumentRangeFormattingEditProvider('coi', {
provideDocumentRangeFormattingEdits(document, range) {
const text = document.getText(range);
const options = {
tabSize: vscode.workspace.getConfiguration('editor').get('tabSize', 4),
insertSpaces: vscode.workspace.getConfiguration('editor').get('insertSpaces', true)
};
const formatted = formatter.format(text, options);
if (formatted === text) {
return [];
}
return [vscode.TextEdit.replace(range, formatted)];
}
});
context.subscriptions.push(
completionProvider,
hoverProvider,
signatureProvider,
definitionProvider,
formattingProvider,
rangeFormattingProvider
);
}
function loadDefinitions(context) {
const config = vscode.workspace.getConfiguration('coi');
let defPath = config.get('definitionsPath');
if (!defPath) {
// Dynamically discover def path using 'coi --defs-path'
try {
const output = execSync('coi --defs-path', { encoding: 'utf8' });
defPath = output.trim();
if (!fs.existsSync(defPath)) {
throw new Error('Returned defs path does not exist: ' + defPath);
}
} catch (err) {
vscode.window.showErrorMessage('Failed to locate Coi definitions directory using \'coi --defs-path\'. Please set \'coi.definitionsPath\' in your settings.');
return;
}
}
definitions = new CoiDefinitions();
definitions.loadFromDirectory(defPath);
console.log(`Loaded ${definitions.types.size} types, ${definitions.namespaces.size} namespaces from ${defPath}`);
}
function getCompletions(document, position) {
const items = [];
const lineText = document.lineAt(position).text;
const textBefore = lineText.substring(0, position.character);
// Check if we're after a dot (method completion)
const dotMatch = textBefore.match(/(\w+)\.\s*(\w*)$/);
if (dotMatch) {
const typeName = dotMatch[1];
const partial = dotMatch[2] || '';
// Check if it's a known type (for type methods like Canvas.createCanvas)
const typeInfo = definitions.types.get(typeName);
if (typeInfo) {
// Add type methods (static)
for (const method of typeInfo.typeMethods || []) {
if (method.name.toLowerCase().startsWith(partial.toLowerCase())) {
const item = new vscode.CompletionItem(method.name, vscode.CompletionItemKind.Method);
item.detail = `${typeName}.${method.name}(${formatParams(method.params)}): ${method.returnType}`;
item.documentation = method.mapsTo ? `Maps to: ${method.mapsTo}` : '';
item.insertText = new vscode.SnippetString(
method.name + '(' + createSnippetParams(method.params) + ')'
);
items.push(item);
}
}
}
// Check if it's a namespace
const nsInfo = definitions.namespaces.get(typeName);
if (nsInfo) {
for (const method of nsInfo.methods) {
if (method.name.toLowerCase().startsWith(partial.toLowerCase())) {
const item = new vscode.CompletionItem(method.name, vscode.CompletionItemKind.Function);
item.detail = `${typeName}.${method.name}(${formatParams(method.params)}): ${method.returnType}`;
item.documentation = method.mapsTo ? `Maps to: ${method.mapsTo}` : '';
item.insertText = new vscode.SnippetString(
method.name + '(' + createSnippetParams(method.params) + ')'
);
items.push(item);
}
}
}
// Check if it's a variable - find its type and show instance methods
const varType = findVariableType(document, position, typeName);
if (varType) {
const typeInfo = definitions.types.get(varType);
if (typeInfo) {
for (const method of typeInfo.methods) {
if (method.name.toLowerCase().startsWith(partial.toLowerCase())) {
const item = new vscode.CompletionItem(method.name, vscode.CompletionItemKind.Method);
item.detail = `${method.name}(${formatParams(method.params)}): ${method.returnType}`;
item.documentation = method.mapsTo ? `Maps to: ${method.mapsTo}` : '';
item.insertText = new vscode.SnippetString(
method.name + '(' + createSnippetParams(method.params) + ')'
);
items.push(item);
}
}
}
}
return items;
}
// Check for view element tag completion
if (textBefore.match(/<(\w*)$/)) {
// Parse current document for components
const userComponents = definitions.parseUserFile(document.getText());
// Add user-defined components
for (const [name, comp] of userComponents) {
const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.Class);
item.detail = `component ${name}`;
const propDesc = comp.props.map(p => `${p.name}: ${p.type}`).join(', ');
item.documentation = propDesc ? `Props: ${propDesc}` : 'No props';
items.push(item);
}
// Add HTML tags
const htmlTags = ['div', 'span', 'p', 'h1', 'h2', 'h3', 'button', 'input', 'a', 'img', 'ul', 'li', 'canvas'];
for (const tag of htmlTags) {
const item = new vscode.CompletionItem(tag, vscode.CompletionItemKind.Property);
item.detail = `HTML <${tag}>`;
items.push(item);
}
return items;
}
// Top-level completions (types, namespaces, keywords)
// Keywords
const keywords = ['component', 'def', 'view', 'style', 'prop', 'mut', 'pub', 'tick', 'init', 'mount', 'if', 'else', 'for', 'while', 'match', 'return', 'yield', 'import', 'app', 'struct', 'in', 'key'];
for (const kw of keywords) {
const item = new vscode.CompletionItem(kw, vscode.CompletionItemKind.Keyword);
items.push(item);
}
// Types
const types = ['int', 'float', 'string', 'bool', 'void'];
for (const t of types) {
const item = new vscode.CompletionItem(t, vscode.CompletionItemKind.TypeParameter);
items.push(item);
}
// Handle types from definitions
for (const [name, info] of definitions.types) {
const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.Class);
item.detail = info.extends ? `type ${name} extends ${info.extends}` : `type ${name}`;
items.push(item);
}
// Namespaces from definitions
for (const [name, info] of definitions.namespaces) {
const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.Module);
item.detail = `namespace ${name}`;
items.push(item);
}
return items;
}
function getHover(document, position) {
const wordRange = document.getWordRangeAtPosition(position);
if (!wordRange) return null;
const word = document.getText(wordRange);
const lineText = document.lineAt(position).text;
// Check if hovering over Type.method
const dotPattern = new RegExp(`(\\w+)\\.${word}\\b`);
const dotMatch = lineText.match(dotPattern);
if (dotMatch) {
const typeName = dotMatch[1];
// Check type methods
const typeInfo = definitions.types.get(typeName);
if (typeInfo) {
// Check type methods (static)
const typeMethod = (typeInfo.typeMethods || []).find(m => m.name === word);
if (typeMethod) {
return new vscode.Hover([
`**${typeName}.${word}** (type method)`,
`\`\`\`coi\ntype def ${word}(${formatParams(typeMethod.params)}): ${typeMethod.returnType}\n\`\`\``,
typeMethod.mapsTo ? `Maps to: \`${typeMethod.mapsTo}\`` : ''
].filter(Boolean));
}
// Check instance methods
const method = typeInfo.methods.find(m => m.name === word);
if (method) {
return new vscode.Hover([
`**${typeName}.${word}** (instance method)`,
`\`\`\`coi\ndef ${word}(${formatParams(method.params)}): ${method.returnType}\n\`\`\``,
method.mapsTo ? `Maps to: \`${method.mapsTo}\`` : ''
].filter(Boolean));
}
}
// Check namespace
const nsInfo = definitions.namespaces.get(typeName);
if (nsInfo) {
const method = nsInfo.methods.find(m => m.name === word);
if (method) {
return new vscode.Hover([
`**${typeName}.${word}**`,
`\`\`\`coi\ndef ${word}(${formatParams(method.params)}): ${method.returnType}\n\`\`\``,
method.mapsTo ? `Maps to: \`${method.mapsTo}\`` : ''
].filter(Boolean));
}
}
}
// Check if hovering over a type name
const typeInfo = definitions.types.get(word);
if (typeInfo) {
const methodCount = (typeInfo.typeMethods || []).length + typeInfo.methods.length;
return new vscode.Hover([
`**type ${word}**` + (typeInfo.extends ? ` extends ${typeInfo.extends}` : ''),
`${methodCount} methods`,
`Source: ${typeInfo.source}`
]);
}
// Check if hovering over a namespace
const nsInfo = definitions.namespaces.get(word);
if (nsInfo) {
return new vscode.Hover([
`**namespace ${word}**`,
`${nsInfo.methods.length} functions`,
`Source: ${nsInfo.source}`
]);
}
return null;
}
function getDefinition(document, position) {
const wordRange = document.getWordRangeAtPosition(position);
if (!wordRange) return null;
const word = document.getText(wordRange);
const lineText = document.lineAt(position).text;
// Check if it's Type.method or var.method
const dotPattern = new RegExp(`(\\w+)\\.${word}\\s*\\(`);
const dotMatch = lineText.match(dotPattern);
if (dotMatch) {
const typeName = dotMatch[1];
// Check type methods
const typeInfo = definitions.types.get(typeName);
if (typeInfo) {
const typeMethod = (typeInfo.typeMethods || []).find(m => m.name === word);
if (typeMethod && typeInfo.source) {
return createDefinitionLocation(typeInfo.source, typeMethod.line);
}
const method = typeInfo.methods.find(m => m.name === word);
if (method && typeInfo.source) {
return createDefinitionLocation(typeInfo.source, method.line);
}
}
// Check namespace
const nsInfo = definitions.namespaces.get(typeName);
if (nsInfo) {
const method = nsInfo.methods.find(m => m.name === word);
if (method && nsInfo.source) {
return createDefinitionLocation(nsInfo.source, method.line);
}
}
// Check by variable type
const varType = findVariableType(document, position, typeName);
if (varType) {
const varTypeInfo = definitions.types.get(varType);
if (varTypeInfo) {
const method = varTypeInfo.methods.find(m => m.name === word);
if (method && varTypeInfo.source) {
return createDefinitionLocation(varTypeInfo.source, method.line);
}
}
}
}
// Check if it's a type name directly
const typeInfo = definitions.types.get(word);
if (typeInfo && typeInfo.source) {
return createDefinitionLocation(typeInfo.source, typeInfo.line);
}
// Check if it's a namespace
const nsInfo = definitions.namespaces.get(word);
if (nsInfo && nsInfo.source) {
return createDefinitionLocation(nsInfo.source, nsInfo.line);
}
// Check if it's a component reference (PascalCase word)
if (/^[A-Z][A-Za-z0-9_]*$/.test(word)) {
const componentLocation = findComponentDefinition(word);
if (componentLocation) {
return componentLocation;
}
}
return null;
}
// Find component definition in workspace .coi files