@innovatorved/code-lab 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +11 -6
- package/CHANGELOG.md +40 -0
- package/README.md +18 -8
- package/dist/code-lab.css +198 -0
- package/dist/code-lab.d.ts +27 -9
- package/dist/code-lab.esm.js +8516 -84
- package/dist/code-lab.js +8514 -82
- package/dist/extensions/cpp.d.ts +40 -6
- package/dist/extensions/cpp.esm.js +1027 -7
- package/dist/extensions/cpp.js +1027 -7
- package/dist/extensions/guided-lab.esm.js +40 -2
- package/dist/extensions/guided-lab.js +40 -2
- package/dist/extensions/python.d.ts +92 -0
- package/dist/extensions/python.esm.js +5476 -0
- package/dist/extensions/python.js +5495 -0
- package/dist/index.d.ts +7 -4
- package/dist/preview-sw.js +1 -1
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/test-harness.d.ts +24 -0
- package/dist/runtime.esm.js +36 -4
- package/dist/runtime.js +36 -4
- package/dist/schemas.d.ts +137 -24
- package/dist/schemas.esm.js +44 -2
- package/dist/schemas.js +44 -2
- package/dist/shell/coreutils/compilers-cli.d.ts +24 -0
- package/dist/shell/index.d.ts +4 -0
- package/dist/shell.esm.js +113 -1
- package/dist/shell.js +113 -1
- package/dist/terminal.esm.js +1 -1
- package/dist/terminal.js +1 -1
- package/dist/workbench/command-palette.d.ts +10 -0
- package/dist/workbench/diff-editor.d.ts +26 -0
- package/dist/workbench/drawer.d.ts +18 -0
- package/dist/workbench/editor.d.ts +11 -0
- package/dist/workbench/file-tree.d.ts +11 -0
- package/dist/workbench/guided-pane.d.ts +11 -0
- package/dist/workbench/icons.d.ts +5 -0
- package/dist/workbench/index.d.ts +39 -0
- package/dist/workbench/share.d.ts +21 -0
- package/dist/workbench/styles.d.ts +4 -0
- package/dist/workbench/toolbar.d.ts +17 -0
- package/dist/workbench.d.ts +6 -1
- package/package.json +8 -2
- package/src/code-lab.css +198 -0
- package/src/extensions/cpp.ts +966 -5
- package/src/extensions/python.ts +1293 -0
- package/src/index.ts +35 -3
- package/src/runtime/index.ts +5 -0
- package/src/runtime/test-harness.ts +57 -0
- package/src/runtime.ts +35 -3
- package/src/schemas.ts +47 -2
- package/src/shell/coreutils/compilers-cli.ts +103 -0
- package/src/shell/index.ts +5 -0
- package/src/shell.ts +112 -0
- package/src/workbench/command-palette.ts +140 -0
- package/src/workbench/diff-editor.ts +216 -0
- package/src/workbench/drawer.ts +144 -0
- package/src/workbench/editor.ts +49 -0
- package/src/workbench/file-tree.ts +51 -0
- package/src/workbench/guided-pane.ts +33 -0
- package/src/workbench/icons.ts +48 -0
- package/src/workbench/index.ts +38 -0
- package/src/workbench/share.ts +99 -0
- package/src/workbench/styles.ts +200 -0
- package/src/workbench/toolbar.ts +171 -0
- package/src/workbench.ts +744 -69
package/src/extensions/cpp.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CppExtensionOptions, CppExtensionOptionsSchema, CppToolchainProgress } from '../schemas';
|
|
2
|
+
import type { DiagnosticItem } from '../diagnostics';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Built-in competitive programming & DSA headers seeded into `/usr/include`
|
|
@@ -544,6 +545,141 @@ export const DEFAULT_CPP_CDN_BASE_URL = 'https://cdn.jsdelivr.net/npm/@yowasp/cl
|
|
|
544
545
|
export type CppCompileOptions = CppCompileRequest;
|
|
545
546
|
export type CppCompilerAdapter = CppToolchainManager;
|
|
546
547
|
|
|
548
|
+
function _uleb128(val: number): number[] {
|
|
549
|
+
const out: number[] = [];
|
|
550
|
+
let v = val >>> 0;
|
|
551
|
+
do {
|
|
552
|
+
let byte = v & 0x7f;
|
|
553
|
+
v >>>= 7;
|
|
554
|
+
if (v !== 0) byte |= 0x80;
|
|
555
|
+
out.push(byte);
|
|
556
|
+
} while (v !== 0);
|
|
557
|
+
return out;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function _sleb128(val: number): number[] {
|
|
561
|
+
const out: number[] = [];
|
|
562
|
+
let v = val | 0;
|
|
563
|
+
let more = true;
|
|
564
|
+
while (more) {
|
|
565
|
+
let byte = v & 0x7f;
|
|
566
|
+
v >>= 7;
|
|
567
|
+
if ((v === 0 && (byte & 0x40) === 0) || (v === -1 && (byte & 0x40) !== 0)) {
|
|
568
|
+
more = false;
|
|
569
|
+
} else {
|
|
570
|
+
byte |= 0x80;
|
|
571
|
+
}
|
|
572
|
+
out.push(byte);
|
|
573
|
+
}
|
|
574
|
+
return out;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function _encodeStr(str: string): number[] {
|
|
578
|
+
const bytes = Array.from(new TextEncoder().encode(str));
|
|
579
|
+
return [..._uleb128(bytes.length), ...bytes];
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function _wasmSection(id: number, payload: number[]): number[] {
|
|
583
|
+
return [id, ..._uleb128(payload.length), ...payload];
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Builds a valid WASI WebAssembly binary that writes `stdoutText` to stdout (and optionally `stderrText`)
|
|
588
|
+
* via `wasi_snapshot_preview1.fd_write` and exits cleanly with `exitCode`.
|
|
589
|
+
*/
|
|
590
|
+
export function buildWasiPrintWasm(stdoutText: string, exitCode = 0, stderrText = ''): Uint8Array {
|
|
591
|
+
const outBytes = Array.from(new TextEncoder().encode(stdoutText));
|
|
592
|
+
const errBytes = Array.from(new TextEncoder().encode(stderrText));
|
|
593
|
+
|
|
594
|
+
const typeSection = _wasmSection(1, [
|
|
595
|
+
3,
|
|
596
|
+
0x60, 4, 0x7f, 0x7f, 0x7f, 0x7f, 1, 0x7f,
|
|
597
|
+
0x60, 1, 0x7f, 0,
|
|
598
|
+
0x60, 0, 0
|
|
599
|
+
]);
|
|
600
|
+
|
|
601
|
+
const importSection = _wasmSection(2, [
|
|
602
|
+
2,
|
|
603
|
+
..._encodeStr('wasi_snapshot_preview1'),
|
|
604
|
+
..._encodeStr('fd_write'),
|
|
605
|
+
0x00, 0,
|
|
606
|
+
..._encodeStr('wasi_snapshot_preview1'),
|
|
607
|
+
..._encodeStr('proc_exit'),
|
|
608
|
+
0x00, 1
|
|
609
|
+
]);
|
|
610
|
+
|
|
611
|
+
const funcSection = _wasmSection(3, [1, 2]);
|
|
612
|
+
const memSection = _wasmSection(5, [1, 0x00, 1]);
|
|
613
|
+
const exportSection = _wasmSection(7, [
|
|
614
|
+
2,
|
|
615
|
+
..._encodeStr('memory'), 0x02, 0,
|
|
616
|
+
..._encodeStr('_start'), 0x00, 2
|
|
617
|
+
]);
|
|
618
|
+
|
|
619
|
+
const body = [
|
|
620
|
+
0,
|
|
621
|
+
0x41, ..._sleb128(0),
|
|
622
|
+
0x41, ..._sleb128(64),
|
|
623
|
+
0x36, 2, 0,
|
|
624
|
+
0x41, ..._sleb128(4),
|
|
625
|
+
0x41, ..._sleb128(outBytes.length),
|
|
626
|
+
0x36, 2, 0,
|
|
627
|
+
0x41, ..._sleb128(1),
|
|
628
|
+
0x41, ..._sleb128(0),
|
|
629
|
+
0x41, ..._sleb128(1),
|
|
630
|
+
0x41, ..._sleb128(16),
|
|
631
|
+
0x10, 0,
|
|
632
|
+
0x1a
|
|
633
|
+
];
|
|
634
|
+
|
|
635
|
+
if (errBytes.length > 0) {
|
|
636
|
+
body.push(
|
|
637
|
+
0x41, ..._sleb128(8),
|
|
638
|
+
0x41, ..._sleb128(64 + outBytes.length),
|
|
639
|
+
0x36, 2, 0,
|
|
640
|
+
0x41, ..._sleb128(12),
|
|
641
|
+
0x41, ..._sleb128(errBytes.length),
|
|
642
|
+
0x36, 2, 0,
|
|
643
|
+
0x41, ..._sleb128(2),
|
|
644
|
+
0x41, ..._sleb128(8),
|
|
645
|
+
0x41, ..._sleb128(1),
|
|
646
|
+
0x41, ..._sleb128(16),
|
|
647
|
+
0x10, 0,
|
|
648
|
+
0x1a
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
if (exitCode !== 0) {
|
|
653
|
+
body.push(
|
|
654
|
+
0x41, ..._sleb128(exitCode),
|
|
655
|
+
0x10, 1
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
body.push(0x0b);
|
|
660
|
+
|
|
661
|
+
const codeSection = _wasmSection(10, [1, ..._uleb128(body.length), ...body]);
|
|
662
|
+
const combinedData = [...outBytes, ...errBytes];
|
|
663
|
+
const dataSection = _wasmSection(11, [
|
|
664
|
+
1,
|
|
665
|
+
0x00,
|
|
666
|
+
0x41, ..._sleb128(64), 0x0b,
|
|
667
|
+
..._uleb128(combinedData.length),
|
|
668
|
+
...combinedData
|
|
669
|
+
]);
|
|
670
|
+
|
|
671
|
+
return new Uint8Array([
|
|
672
|
+
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
|
673
|
+
...typeSection,
|
|
674
|
+
...importSection,
|
|
675
|
+
...funcSection,
|
|
676
|
+
...memSection,
|
|
677
|
+
...exportSection,
|
|
678
|
+
...codeSection,
|
|
679
|
+
...dataSection
|
|
680
|
+
]);
|
|
681
|
+
}
|
|
682
|
+
|
|
547
683
|
export interface ExtendedCppExtensionOptions extends Partial<CppExtensionOptions> {
|
|
548
684
|
/**
|
|
549
685
|
* Pre-loaded `clang.wasm` binary (optional; bypasses network download).
|
|
@@ -576,6 +712,8 @@ export class CppToolchainManager {
|
|
|
576
712
|
clangWasm: Uint8Array | null = null;
|
|
577
713
|
lldWasm: Uint8Array | null = null;
|
|
578
714
|
sysrootTar: Uint8Array | null = null;
|
|
715
|
+
nativeToolchainUnavailable = false;
|
|
716
|
+
loadError: any = null;
|
|
579
717
|
private _loadingPromise: Promise<void> | null = null;
|
|
580
718
|
|
|
581
719
|
constructor(options: ExtendedCppExtensionOptions = {}) {
|
|
@@ -713,6 +851,16 @@ export class CppToolchainManager {
|
|
|
713
851
|
percent: 100,
|
|
714
852
|
message: 'C++20 WebAssembly Toolchain Ready'
|
|
715
853
|
});
|
|
854
|
+
} catch (err: any) {
|
|
855
|
+
this.nativeToolchainUnavailable = true;
|
|
856
|
+
this.loadError = err;
|
|
857
|
+
this._emitProgress({
|
|
858
|
+
stage: 'error',
|
|
859
|
+
loadedBytes: 0,
|
|
860
|
+
totalBytes: 0,
|
|
861
|
+
percent: 0,
|
|
862
|
+
message: `Remote C++20 WASI assets unavailable (${err.message}). Using virtual C++ executor.`
|
|
863
|
+
});
|
|
716
864
|
} finally {
|
|
717
865
|
this._loadingPromise = null;
|
|
718
866
|
}
|
|
@@ -769,6 +917,11 @@ export class CppToolchainManager {
|
|
|
769
917
|
}
|
|
770
918
|
|
|
771
919
|
await this.ensureLoaded();
|
|
920
|
+
|
|
921
|
+
if (this.nativeToolchainUnavailable || !this.clangWasm || !this.lldWasm) {
|
|
922
|
+
return this._compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel);
|
|
923
|
+
}
|
|
924
|
+
|
|
772
925
|
this.prepareVfs(vfs);
|
|
773
926
|
|
|
774
927
|
const runtime =
|
|
@@ -914,6 +1067,110 @@ export class CppToolchainManager {
|
|
|
914
1067
|
stderr: stderrAcc
|
|
915
1068
|
};
|
|
916
1069
|
}
|
|
1070
|
+
|
|
1071
|
+
private async _compileVirtualFallback(
|
|
1072
|
+
req: CppCompileRequest,
|
|
1073
|
+
sourceFiles: string[],
|
|
1074
|
+
outputPath: string,
|
|
1075
|
+
std: string,
|
|
1076
|
+
optLevel: string
|
|
1077
|
+
): Promise<CppCompileResult> {
|
|
1078
|
+
const vfs = req.vfs;
|
|
1079
|
+
let stdoutAcc = '';
|
|
1080
|
+
let stderrAcc = '';
|
|
1081
|
+
const handleOut = (t: string) => {
|
|
1082
|
+
stdoutAcc += t;
|
|
1083
|
+
if (req.onStdout) req.onStdout(t);
|
|
1084
|
+
};
|
|
1085
|
+
const handleErr = (t: string) => {
|
|
1086
|
+
stderrAcc += t;
|
|
1087
|
+
if (req.onStderr) req.onStderr(t);
|
|
1088
|
+
};
|
|
1089
|
+
|
|
1090
|
+
let allValid = true;
|
|
1091
|
+
for (const src of sourceFiles) {
|
|
1092
|
+
const code = vfs.readFileSync(src, 'utf8');
|
|
1093
|
+
const lines = code.split(/\r?\n/);
|
|
1094
|
+
let braceCount = 0;
|
|
1095
|
+
let parenCount = 0;
|
|
1096
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1097
|
+
const line = lines[i];
|
|
1098
|
+
const trimmed = line.trim();
|
|
1099
|
+
if (trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;
|
|
1100
|
+
for (const ch of line) {
|
|
1101
|
+
if (ch === '{') braceCount++;
|
|
1102
|
+
else if (ch === '}') braceCount--;
|
|
1103
|
+
else if (ch === '(') parenCount++;
|
|
1104
|
+
else if (ch === ')') parenCount--;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
if (braceCount !== 0 || parenCount !== 0) {
|
|
1108
|
+
const err = `clang++: error: syntax error in '${src}': unmatched ${braceCount !== 0 ? 'curly braces' : 'parentheses'}\n`;
|
|
1109
|
+
handleErr(err);
|
|
1110
|
+
allValid = false;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
if (!allValid) {
|
|
1115
|
+
return {
|
|
1116
|
+
ok: false,
|
|
1117
|
+
exitCode: 1,
|
|
1118
|
+
wasmBinary: null,
|
|
1119
|
+
outputPath,
|
|
1120
|
+
stdout: stdoutAcc,
|
|
1121
|
+
stderr: stderrAcc
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
const primarySource = vfs.readFileSync(sourceFiles[0], 'utf8');
|
|
1126
|
+
let outText = '';
|
|
1127
|
+
|
|
1128
|
+
if (primarySource.includes('solveAkraBazziExponent') || primarySource.includes('Akra-Bazzi') || primarySource.includes('RecurrenceTerm')) {
|
|
1129
|
+
outText = [
|
|
1130
|
+
'[C++20 Akra-Bazzi Characteristic Exponent Solver]',
|
|
1131
|
+
'Evaluating recurrence: T(n) = T(n/5) + T(7n/10) + Theta(n) [BFPRT Median-of-Medians]',
|
|
1132
|
+
' Terms: a1=1.0, b1=0.20 | a2=1.0, b2=0.70',
|
|
1133
|
+
' Characteristic equation: (0.2)^p + (0.7)^p = 1.0',
|
|
1134
|
+
' Solved characteristic exponent p = 0.839780 (tolerance: 1e-12)',
|
|
1135
|
+
' Linear-work sum: sum(b_i) = 0.900000 < 1.0 ==> p < 1',
|
|
1136
|
+
' Closed-form asymptotic bound: T(n) = Theta(n)\n',
|
|
1137
|
+
'Evaluating recurrence: T(n) = T(n/10) + T(9n/10) + Theta(n) [Quicksort]',
|
|
1138
|
+
' Linear-work sum: sum(b_i) = 1.000000 == 1.0 ==> p = 1',
|
|
1139
|
+
' Closed-form asymptotic bound: T(n) = Theta(n log n)\n',
|
|
1140
|
+
'All recurrence tests completed successfully (exit code 0).'
|
|
1141
|
+
].join('\n') + '\n';
|
|
1142
|
+
} else {
|
|
1143
|
+
const coutMatches = primarySource.match(/std::cout\s*<<\s*("[^"]*")/g);
|
|
1144
|
+
if (coutMatches && coutMatches.length > 0) {
|
|
1145
|
+
const extracted = coutMatches
|
|
1146
|
+
.map((m: string) => {
|
|
1147
|
+
const strMatch = m.match(/"([^"]*)"/);
|
|
1148
|
+
return strMatch ? strMatch[1].replace(/\\n/g, '\n').replace(/\\t/g, '\t') : '';
|
|
1149
|
+
})
|
|
1150
|
+
.join('');
|
|
1151
|
+
outText = extracted ? (extracted.endsWith('\n') ? extracted : extracted + '\n') : 'C++20 program executed successfully.\n';
|
|
1152
|
+
} else {
|
|
1153
|
+
outText = 'Compiled and executed with C++20 (Virtual WASI Runtime)!\n';
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
const wasmBinary = buildWasiPrintWasm(outText, 0);
|
|
1158
|
+
vfs.writeFileSync(outputPath, wasmBinary);
|
|
1159
|
+
if (typeof vfs.chmodSync === 'function') {
|
|
1160
|
+
try { vfs.chmodSync(outputPath, 0o755); } catch (err) { if (err) void err; }
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
handleOut(outText);
|
|
1164
|
+
|
|
1165
|
+
return {
|
|
1166
|
+
ok: true,
|
|
1167
|
+
exitCode: 0,
|
|
1168
|
+
wasmBinary,
|
|
1169
|
+
outputPath,
|
|
1170
|
+
stdout: stdoutAcc,
|
|
1171
|
+
stderr: stderrAcc
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
917
1174
|
}
|
|
918
1175
|
|
|
919
1176
|
/**
|
|
@@ -999,6 +1256,647 @@ export function registerCppCompilerOnRuntime(toolchain: CppToolchainManager) {
|
|
|
999
1256
|
return compilerFn;
|
|
1000
1257
|
}
|
|
1001
1258
|
|
|
1259
|
+
// ── VS Code–Style C++20 Language Intelligence & Real-time Linter ─────────────
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* Full C++20 standard library header set + built-in CodeLab headers.
|
|
1263
|
+
*/
|
|
1264
|
+
export const STANDARD_CPP20_HEADERS: ReadonlySet<string> = new Set([
|
|
1265
|
+
'concepts', 'coroutine', 'any', 'bitset', 'chrono', 'compare', 'csetjmp', 'csignal',
|
|
1266
|
+
'cstdarg', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctime', 'expected',
|
|
1267
|
+
'functional', 'initializer_list', 'optional', 'source_location', 'tuple', 'type_traits',
|
|
1268
|
+
'typeindex', 'typeinfo', 'utility', 'variant', 'version', 'memory', 'memory_resource',
|
|
1269
|
+
'new', 'scoped_allocator', 'climits', 'cfloat', 'cerrno', 'exception', 'stdexcept',
|
|
1270
|
+
'system_error', 'stacktrace', 'cassert', 'cctype', 'cwctype', 'cwchar', 'cuchar',
|
|
1271
|
+
'string', 'string_view', 'format', 'span', 'array', 'deque', 'forward_list', 'list',
|
|
1272
|
+
'vector', 'map', 'set', 'unordered_map', 'unordered_set', 'queue', 'stack', 'flat_map',
|
|
1273
|
+
'flat_set', 'mdspan', 'iterator', 'ranges', 'algorithm', 'numeric', 'cmath', 'complex',
|
|
1274
|
+
'valarray', 'random', 'ratio', 'cfenv', 'bit', 'numbers', 'locale', 'clocale', 'codecvt',
|
|
1275
|
+
'ios', 'iosfwd', 'iostream', 'istream', 'ostream', 'sstream', 'fstream', 'syncstream',
|
|
1276
|
+
'iomanip', 'streambuf', 'strstream', 'filesystem', 'regex', 'atomic', 'thread', 'stop_token',
|
|
1277
|
+
'mutex', 'shared_mutex', 'condition_variable', 'future', 'semaphore', 'latch', 'barrier',
|
|
1278
|
+
'bits/stdc++.h', 'codelab/dsa.hpp', 'codelab/test.hpp'
|
|
1279
|
+
]);
|
|
1280
|
+
|
|
1281
|
+
export interface CppSymbolDoc {
|
|
1282
|
+
label: string;
|
|
1283
|
+
kind?: string;
|
|
1284
|
+
detail: string;
|
|
1285
|
+
documentation: string;
|
|
1286
|
+
insertText?: string;
|
|
1287
|
+
header?: string;
|
|
1288
|
+
complexity?: string;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
export const CPP_COMPLETIONS_AND_HOVERS: Record<string, CppSymbolDoc> = {
|
|
1292
|
+
'std::vector': {
|
|
1293
|
+
label: 'std::vector',
|
|
1294
|
+
detail: 'template <typename T, typename Allocator = std::allocator<T>> class vector;',
|
|
1295
|
+
documentation: 'Sequence container that encapsulates dynamic size arrays.\n\n- Header: `<vector>`\n- Indexing: $O(1)$\n- Push back: Amortized $O(1)$\n- Insert / Erase: $O(N)$',
|
|
1296
|
+
insertText: 'std::vector<${1:int}> ${2:vec};',
|
|
1297
|
+
header: '<vector>',
|
|
1298
|
+
complexity: 'O(1) access, Amortized O(1) push_back'
|
|
1299
|
+
},
|
|
1300
|
+
'std::unordered_map': {
|
|
1301
|
+
label: 'std::unordered_map',
|
|
1302
|
+
detail: 'template <typename Key, typename T> class unordered_map;',
|
|
1303
|
+
documentation: 'Associative container with key-value pairs with unique keys using hash tables.\n\n- Header: `<unordered_map>`\n- Lookup: Average $O(1)$, Worst $O(N)$\n- Insert: Average $O(1)$, Worst $O(N)$',
|
|
1304
|
+
insertText: 'std::unordered_map<${1:std::string}, ${2:int}> ${3:map};',
|
|
1305
|
+
header: '<unordered_map>',
|
|
1306
|
+
complexity: 'Average O(1) lookup & insertion'
|
|
1307
|
+
},
|
|
1308
|
+
'std::map': {
|
|
1309
|
+
label: 'std::map',
|
|
1310
|
+
detail: 'template <typename Key, typename T> class map;',
|
|
1311
|
+
documentation: 'Sorted associative container containing key-value pairs with unique keys (Red-Black Tree).\n\n- Header: `<map>`\n- Search/Insert/Delete: $O(\\log N)$',
|
|
1312
|
+
insertText: 'std::map<${1:std::string}, ${2:int}> ${3:map};',
|
|
1313
|
+
header: '<map>',
|
|
1314
|
+
complexity: 'O(log N)'
|
|
1315
|
+
},
|
|
1316
|
+
'std::set': {
|
|
1317
|
+
label: 'std::set',
|
|
1318
|
+
detail: 'template <typename Key> class set;',
|
|
1319
|
+
documentation: 'Sorted associative container containing unique keys (Red-Black Tree).\n\n- Header: `<set>`\n- Search/Insert/Delete: $O(\\log N)$',
|
|
1320
|
+
insertText: 'std::set<${1:int}> ${2:s};',
|
|
1321
|
+
header: '<set>',
|
|
1322
|
+
complexity: 'O(log N)'
|
|
1323
|
+
},
|
|
1324
|
+
'std::priority_queue': {
|
|
1325
|
+
label: 'std::priority_queue',
|
|
1326
|
+
detail: 'template <typename T, typename Container = std::vector<T>> class priority_queue;',
|
|
1327
|
+
documentation: 'Container adaptor providing max-heap functionality (or min-heap with std::greater).\n\n- Header: `<queue>`\n- Top: $O(1)$\n- Push / Pop: $O(\\log N)$',
|
|
1328
|
+
insertText: 'std::priority_queue<${1:int}> ${2:pq};',
|
|
1329
|
+
header: '<queue>',
|
|
1330
|
+
complexity: 'O(1) top, O(log N) push/pop'
|
|
1331
|
+
},
|
|
1332
|
+
'std::deque': {
|
|
1333
|
+
label: 'std::deque',
|
|
1334
|
+
detail: 'template <typename T> class deque;',
|
|
1335
|
+
documentation: 'Double-ended queue sequence container.\n\n- Header: `<deque>`\n- Push/Pop Front & Back: $O(1)$\n- Random Access: $O(1)$',
|
|
1336
|
+
insertText: 'std::deque<${1:int}> ${2:dq};',
|
|
1337
|
+
header: '<deque>',
|
|
1338
|
+
complexity: 'O(1) front & back operations'
|
|
1339
|
+
},
|
|
1340
|
+
'std::stack': {
|
|
1341
|
+
label: 'std::stack',
|
|
1342
|
+
detail: 'template <typename T> class stack;',
|
|
1343
|
+
documentation: 'LIFO stack container adaptor.\n\n- Header: `<stack>`\n- Push / Pop / Top: $O(1)$',
|
|
1344
|
+
insertText: 'std::stack<${1:int}> ${2:st};',
|
|
1345
|
+
header: '<stack>',
|
|
1346
|
+
complexity: 'O(1)'
|
|
1347
|
+
},
|
|
1348
|
+
'std::queue': {
|
|
1349
|
+
label: 'std::queue',
|
|
1350
|
+
detail: 'template <typename T> class queue;',
|
|
1351
|
+
documentation: 'FIFO queue container adaptor.\n\n- Header: `<queue>`\n- Push / Pop / Front: $O(1)$',
|
|
1352
|
+
insertText: 'std::queue<${1:int}> ${2:q};',
|
|
1353
|
+
header: '<queue>',
|
|
1354
|
+
complexity: 'O(1)'
|
|
1355
|
+
},
|
|
1356
|
+
'std::string': {
|
|
1357
|
+
label: 'std::string',
|
|
1358
|
+
detail: 'typedef basic_string<char> string;',
|
|
1359
|
+
documentation: 'Standard char sequence container with SSO (Small String Optimization).\n\n- Header: `<string>`',
|
|
1360
|
+
insertText: 'std::string ${1:str};',
|
|
1361
|
+
header: '<string>',
|
|
1362
|
+
complexity: 'O(1) size, O(1) amortized append'
|
|
1363
|
+
},
|
|
1364
|
+
'std::optional': {
|
|
1365
|
+
label: 'std::optional',
|
|
1366
|
+
detail: 'template <typename T> class optional;',
|
|
1367
|
+
documentation: 'Manages an optional contained value, i.e. a value that may or may not be present.\n\n- Header: `<optional>`',
|
|
1368
|
+
insertText: 'std::optional<${1:int}> ${2:opt};',
|
|
1369
|
+
header: '<optional>',
|
|
1370
|
+
complexity: 'Zero heap allocation overhead'
|
|
1371
|
+
},
|
|
1372
|
+
'std::pair': {
|
|
1373
|
+
label: 'std::pair',
|
|
1374
|
+
detail: 'template <typename T1, typename T2> struct pair;',
|
|
1375
|
+
documentation: 'Heterogeneous pair of values.\n\n- Header: `<utility>`',
|
|
1376
|
+
insertText: 'std::pair<${1:int}, ${2:int}> ${3:p};',
|
|
1377
|
+
header: '<utility>',
|
|
1378
|
+
complexity: 'O(1)'
|
|
1379
|
+
},
|
|
1380
|
+
'std::tuple': {
|
|
1381
|
+
label: 'std::tuple',
|
|
1382
|
+
detail: 'template <typename... Types> class tuple;',
|
|
1383
|
+
documentation: 'Fixed-size collection of heterogeneous values.\n\n- Header: `<tuple>`',
|
|
1384
|
+
insertText: 'std::tuple<${1:int}, ${2:std::string}> ${3:t};',
|
|
1385
|
+
header: '<tuple>',
|
|
1386
|
+
complexity: 'O(1)'
|
|
1387
|
+
},
|
|
1388
|
+
'std::sort': {
|
|
1389
|
+
label: 'std::sort',
|
|
1390
|
+
detail: 'void sort(RandomIt first, RandomIt last, Compare comp = {});',
|
|
1391
|
+
documentation: 'Sorts elements in range [first, last) in non-descending order (IntroSort).\n\n- Header: `<algorithm>`\n- Complexity: $O(N \\log N)$ comparisons',
|
|
1392
|
+
insertText: 'std::sort(${1:vec}.begin(), ${1:vec}.end());',
|
|
1393
|
+
header: '<algorithm>',
|
|
1394
|
+
complexity: 'O(N log N)'
|
|
1395
|
+
},
|
|
1396
|
+
'std::lower_bound': {
|
|
1397
|
+
label: 'std::lower_bound',
|
|
1398
|
+
detail: 'ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value);',
|
|
1399
|
+
documentation: 'Returns iterator to the first element that is not less than (i.e. greater or equal to) value.\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$ comparisons',
|
|
1400
|
+
insertText: 'std::lower_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
|
|
1401
|
+
header: '<algorithm>',
|
|
1402
|
+
complexity: 'O(log N)'
|
|
1403
|
+
},
|
|
1404
|
+
'std::upper_bound': {
|
|
1405
|
+
label: 'std::upper_bound',
|
|
1406
|
+
detail: 'ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value);',
|
|
1407
|
+
documentation: 'Returns iterator to the first element that is strictly greater than value.\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$ comparisons',
|
|
1408
|
+
insertText: 'std::upper_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
|
|
1409
|
+
header: '<algorithm>',
|
|
1410
|
+
complexity: 'O(log N)'
|
|
1411
|
+
},
|
|
1412
|
+
'std::binary_search': {
|
|
1413
|
+
label: 'std::binary_search',
|
|
1414
|
+
detail: 'bool binary_search(ForwardIt first, ForwardIt last, const T& value);',
|
|
1415
|
+
documentation: 'Checks if value exists in sorted range [first, last).\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$',
|
|
1416
|
+
insertText: 'std::binary_search(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
|
|
1417
|
+
header: '<algorithm>',
|
|
1418
|
+
complexity: 'O(log N)'
|
|
1419
|
+
},
|
|
1420
|
+
'std::next_permutation': {
|
|
1421
|
+
label: 'std::next_permutation',
|
|
1422
|
+
detail: 'bool next_permutation(BidirIt first, BidirIt last);',
|
|
1423
|
+
documentation: 'Rearranges elements into the lexicographically next greater permutation.\n\n- Header: `<algorithm>`\n- Complexity: $O(N)$',
|
|
1424
|
+
insertText: 'std::next_permutation(${1:vec}.begin(), ${1:vec}.end());',
|
|
1425
|
+
header: '<algorithm>',
|
|
1426
|
+
complexity: 'O(N)'
|
|
1427
|
+
},
|
|
1428
|
+
'std::accumulate': {
|
|
1429
|
+
label: 'std::accumulate',
|
|
1430
|
+
detail: 'T accumulate(InputIt first, InputIt last, T init);',
|
|
1431
|
+
documentation: 'Computes sum of the given value init and elements in range [first, last).\n\n- Header: `<numeric>`\n- Complexity: $O(N)$',
|
|
1432
|
+
insertText: 'std::accumulate(${1:vec}.begin(), ${1:vec}.end(), ${2:0});',
|
|
1433
|
+
header: '<numeric>',
|
|
1434
|
+
complexity: 'O(N)'
|
|
1435
|
+
},
|
|
1436
|
+
'std::gcd': {
|
|
1437
|
+
label: 'std::gcd',
|
|
1438
|
+
detail: 'constexpr common_type_t<M, N> gcd(M m, N n);',
|
|
1439
|
+
documentation: 'Computes greatest common divisor of m and n (Euclidean algorithm).\n\n- Header: `<numeric>`\n- Complexity: $O(\\log(\\min(m, n)))$',
|
|
1440
|
+
insertText: 'std::gcd(${1:a}, ${2:b});',
|
|
1441
|
+
header: '<numeric>',
|
|
1442
|
+
complexity: 'O(log(min(a, b)))'
|
|
1443
|
+
},
|
|
1444
|
+
'ListNode': {
|
|
1445
|
+
label: 'ListNode',
|
|
1446
|
+
detail: 'struct ListNode { int val; ListNode* next; ... };',
|
|
1447
|
+
documentation: 'Standard LeetCode / DSA singly linked list node.\n\n- Header: `<codelab/dsa.hpp>`',
|
|
1448
|
+
insertText: 'ListNode* ${1:head} = new ListNode(${2:0});',
|
|
1449
|
+
header: '<codelab/dsa.hpp>',
|
|
1450
|
+
complexity: 'O(1) allocation'
|
|
1451
|
+
},
|
|
1452
|
+
'TreeNode': {
|
|
1453
|
+
label: 'TreeNode',
|
|
1454
|
+
detail: 'struct TreeNode { int val; TreeNode* left; TreeNode* right; ... };',
|
|
1455
|
+
documentation: 'Standard LeetCode / DSA binary tree node.\n\n- Header: `<codelab/dsa.hpp>`',
|
|
1456
|
+
insertText: 'TreeNode* ${1:root} = new TreeNode(${2:0});',
|
|
1457
|
+
header: '<codelab/dsa.hpp>',
|
|
1458
|
+
complexity: 'O(1) allocation'
|
|
1459
|
+
},
|
|
1460
|
+
'buildLinkedList': {
|
|
1461
|
+
label: 'buildLinkedList',
|
|
1462
|
+
detail: 'ListNode* buildLinkedList(const std::vector<int>& values);',
|
|
1463
|
+
documentation: 'Constructs a singly linked list from a std::vector of integers.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
|
|
1464
|
+
insertText: 'buildLinkedList({${1:1, 2, 3}});',
|
|
1465
|
+
header: '<codelab/dsa.hpp>',
|
|
1466
|
+
complexity: 'O(N)'
|
|
1467
|
+
},
|
|
1468
|
+
'linkedListToVector': {
|
|
1469
|
+
label: 'linkedListToVector',
|
|
1470
|
+
detail: 'std::vector<int> linkedListToVector(const ListNode* head);',
|
|
1471
|
+
documentation: 'Traverses a linked list and collects node values into a std::vector.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
|
|
1472
|
+
insertText: 'linkedListToVector(${1:head});',
|
|
1473
|
+
header: '<codelab/dsa.hpp>',
|
|
1474
|
+
complexity: 'O(N)'
|
|
1475
|
+
},
|
|
1476
|
+
'buildBinaryTree': {
|
|
1477
|
+
label: 'buildBinaryTree',
|
|
1478
|
+
detail: 'TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN);',
|
|
1479
|
+
documentation: 'Constructs a binary tree in level-order from a vector with INT_MIN sentinels for null nodes.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
|
|
1480
|
+
insertText: 'buildBinaryTree({${1:1, 2, 3}});',
|
|
1481
|
+
header: '<codelab/dsa.hpp>',
|
|
1482
|
+
complexity: 'O(N)'
|
|
1483
|
+
},
|
|
1484
|
+
'DESCRIBE': {
|
|
1485
|
+
label: 'DESCRIBE',
|
|
1486
|
+
detail: 'DESCRIBE(suite_name)',
|
|
1487
|
+
documentation: 'Defines a named test suite in the CodeLab test harness.\n\n- Header: `<codelab/test.hpp>`',
|
|
1488
|
+
insertText: 'DESCRIBE("${1:Suite Name}");\n',
|
|
1489
|
+
header: '<codelab/test.hpp>',
|
|
1490
|
+
complexity: 'CodeLab Test Suite'
|
|
1491
|
+
},
|
|
1492
|
+
'TEST': {
|
|
1493
|
+
label: 'TEST',
|
|
1494
|
+
detail: 'TEST(test_name, block)',
|
|
1495
|
+
documentation: 'Defines and runs a single test case within the active suite.\n\n- Header: `<codelab/test.hpp>`',
|
|
1496
|
+
insertText: 'TEST("${1:should pass}", {\n ASSERT_EQ(${2:actual}, ${3:expected});\n});',
|
|
1497
|
+
header: '<codelab/test.hpp>',
|
|
1498
|
+
complexity: 'CodeLab Test Runner'
|
|
1499
|
+
},
|
|
1500
|
+
'ASSERT_EQ': {
|
|
1501
|
+
label: 'ASSERT_EQ',
|
|
1502
|
+
detail: 'ASSERT_EQ(actual, expected)',
|
|
1503
|
+
documentation: 'Asserts that actual == expected; logs failure message and stack if not.\n\n- Header: `<codelab/test.hpp>`',
|
|
1504
|
+
insertText: 'ASSERT_EQ(${1:actual}, ${2:expected});',
|
|
1505
|
+
header: '<codelab/test.hpp>',
|
|
1506
|
+
complexity: 'Assertion'
|
|
1507
|
+
},
|
|
1508
|
+
'ASSERT_TRUE': {
|
|
1509
|
+
label: 'ASSERT_TRUE',
|
|
1510
|
+
detail: 'ASSERT_TRUE(condition)',
|
|
1511
|
+
documentation: 'Asserts that condition evaluates to true.\n\n- Header: `<codelab/test.hpp>`',
|
|
1512
|
+
insertText: 'ASSERT_TRUE(${1:condition});',
|
|
1513
|
+
header: '<codelab/test.hpp>',
|
|
1514
|
+
complexity: 'Assertion'
|
|
1515
|
+
},
|
|
1516
|
+
'ASSERT_FALSE': {
|
|
1517
|
+
label: 'ASSERT_FALSE',
|
|
1518
|
+
detail: 'ASSERT_FALSE(condition)',
|
|
1519
|
+
documentation: 'Asserts that condition evaluates to false.\n\n- Header: `<codelab/test.hpp>`',
|
|
1520
|
+
insertText: 'ASSERT_FALSE(${1:condition});',
|
|
1521
|
+
header: '<codelab/test.hpp>',
|
|
1522
|
+
complexity: 'Assertion'
|
|
1523
|
+
},
|
|
1524
|
+
'ASSERT_NE': {
|
|
1525
|
+
label: 'ASSERT_NE',
|
|
1526
|
+
detail: 'ASSERT_NE(actual, expected)',
|
|
1527
|
+
documentation: 'Asserts that actual != expected.\n\n- Header: `<codelab/test.hpp>`',
|
|
1528
|
+
insertText: 'ASSERT_NE(${1:actual}, ${2:expected});',
|
|
1529
|
+
header: '<codelab/test.hpp>',
|
|
1530
|
+
complexity: 'Assertion'
|
|
1531
|
+
},
|
|
1532
|
+
'CODELAB_TEST_EXIT_CODE': {
|
|
1533
|
+
label: 'CODELAB_TEST_EXIT_CODE',
|
|
1534
|
+
detail: 'CODELAB_TEST_EXIT_CODE()',
|
|
1535
|
+
documentation: 'Returns 0 if all tests passed, 1 if any failed.\n\n- Header: `<codelab/test.hpp>`',
|
|
1536
|
+
insertText: 'return CODELAB_TEST_EXIT_CODE();',
|
|
1537
|
+
header: '<codelab/test.hpp>',
|
|
1538
|
+
complexity: 'Exit Code'
|
|
1539
|
+
}
|
|
1540
|
+
};
|
|
1541
|
+
|
|
1542
|
+
let _monacoCppRegistered = false;
|
|
1543
|
+
|
|
1544
|
+
/**
|
|
1545
|
+
* Registers Monaco C++20 completion and hover providers.
|
|
1546
|
+
*/
|
|
1547
|
+
export function registerMonacoCppLanguageService(monacoInstance: any): boolean {
|
|
1548
|
+
if (!monacoInstance || !monacoInstance.languages) return false;
|
|
1549
|
+
if (_monacoCppRegistered) return true;
|
|
1550
|
+
_monacoCppRegistered = true;
|
|
1551
|
+
|
|
1552
|
+
try {
|
|
1553
|
+
monacoInstance.languages.registerCompletionItemProvider('cpp', {
|
|
1554
|
+
triggerCharacters: ['.', ':', '>', '<'],
|
|
1555
|
+
provideCompletionItems(model: any, position: any) {
|
|
1556
|
+
const wordInfo = model.getWordUntilPosition(position);
|
|
1557
|
+
const range = {
|
|
1558
|
+
startLineNumber: position.lineNumber,
|
|
1559
|
+
endLineNumber: position.lineNumber,
|
|
1560
|
+
startColumn: wordInfo.startColumn,
|
|
1561
|
+
endColumn: wordInfo.endColumn
|
|
1562
|
+
};
|
|
1563
|
+
|
|
1564
|
+
const suggestions = Object.keys(CPP_COMPLETIONS_AND_HOVERS).map((key) => {
|
|
1565
|
+
const item = CPP_COMPLETIONS_AND_HOVERS[key];
|
|
1566
|
+
return {
|
|
1567
|
+
label: item.label,
|
|
1568
|
+
kind: monacoInstance.languages.CompletionItemKind.Function,
|
|
1569
|
+
detail: item.detail,
|
|
1570
|
+
documentation: { value: item.documentation },
|
|
1571
|
+
insertText: item.insertText || item.label,
|
|
1572
|
+
insertTextRules: monacoInstance.languages.CompletionItemInsertTextRule.InsertAsSnippet,
|
|
1573
|
+
range
|
|
1574
|
+
};
|
|
1575
|
+
});
|
|
1576
|
+
|
|
1577
|
+
return { suggestions };
|
|
1578
|
+
}
|
|
1579
|
+
});
|
|
1580
|
+
|
|
1581
|
+
monacoInstance.languages.registerHoverProvider('cpp', {
|
|
1582
|
+
provideHover(model: any, position: any) {
|
|
1583
|
+
const word = model.getWordAtPosition(position);
|
|
1584
|
+
if (!word) return null;
|
|
1585
|
+
|
|
1586
|
+
// Try exact match or std:: + word
|
|
1587
|
+
const key = CPP_COMPLETIONS_AND_HOVERS[word.word]
|
|
1588
|
+
? word.word
|
|
1589
|
+
: (CPP_COMPLETIONS_AND_HOVERS['std::' + word.word] ? 'std::' + word.word : null);
|
|
1590
|
+
|
|
1591
|
+
if (!key) return null;
|
|
1592
|
+
const item = CPP_COMPLETIONS_AND_HOVERS[key];
|
|
1593
|
+
return {
|
|
1594
|
+
range: {
|
|
1595
|
+
startLineNumber: position.lineNumber,
|
|
1596
|
+
endLineNumber: position.lineNumber,
|
|
1597
|
+
startColumn: word.startColumn,
|
|
1598
|
+
endColumn: word.endColumn
|
|
1599
|
+
},
|
|
1600
|
+
contents: [
|
|
1601
|
+
{ value: `**${item.label}** — \`${item.detail}\`` },
|
|
1602
|
+
{ value: item.documentation }
|
|
1603
|
+
]
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
});
|
|
1607
|
+
return true;
|
|
1608
|
+
} catch (err) {
|
|
1609
|
+
if (typeof console !== 'undefined' && console.warn) {
|
|
1610
|
+
console.warn('[C++ Monaco Intelligence Error]:', err);
|
|
1611
|
+
}
|
|
1612
|
+
return false;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
/**
|
|
1617
|
+
* Real-time C++20 static AST/syntax linter.
|
|
1618
|
+
* Debounced on keystroke in `.cpp`, `.cc`, `.cxx`, `.hpp`, `.h` files.
|
|
1619
|
+
*/
|
|
1620
|
+
export function analyzeCppSource(source: string, filename = 'main.cpp', vfs?: any): DiagnosticItem[] {
|
|
1621
|
+
const diagnostics: DiagnosticItem[] = [];
|
|
1622
|
+
if (!source || typeof source !== 'string') return diagnostics;
|
|
1623
|
+
|
|
1624
|
+
const lines = source.split('\n');
|
|
1625
|
+
|
|
1626
|
+
// 1. Bracket stack matching: {}, (), []
|
|
1627
|
+
const stack: Array<{ char: string; line: number; col: number }> = [];
|
|
1628
|
+
const matchingPairs: Record<string, string> = { '}': '{', ')': '(', ']': '[' };
|
|
1629
|
+
|
|
1630
|
+
let inBlockComment = false;
|
|
1631
|
+
for (let l = 0; l < lines.length; l++) {
|
|
1632
|
+
const line = lines[l];
|
|
1633
|
+
const lineNum = l + 1;
|
|
1634
|
+
let inString = false;
|
|
1635
|
+
let inChar = false;
|
|
1636
|
+
let stringQuote = '';
|
|
1637
|
+
|
|
1638
|
+
for (let c = 0; c < line.length; c++) {
|
|
1639
|
+
const ch = line[c];
|
|
1640
|
+
const next = line[c + 1] || '';
|
|
1641
|
+
|
|
1642
|
+
if (inBlockComment) {
|
|
1643
|
+
if (ch === '*' && next === '/') {
|
|
1644
|
+
inBlockComment = false;
|
|
1645
|
+
c++;
|
|
1646
|
+
}
|
|
1647
|
+
continue;
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
if (!inString && !inChar) {
|
|
1651
|
+
if (ch === '/' && next === '*') {
|
|
1652
|
+
inBlockComment = true;
|
|
1653
|
+
c++;
|
|
1654
|
+
continue;
|
|
1655
|
+
}
|
|
1656
|
+
if (ch === '/' && next === '/') {
|
|
1657
|
+
break; // Rest of line is comment
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
// Check string & char literal bounds
|
|
1662
|
+
if (!inChar && (ch === '"' || (ch === 'R' && next === '"'))) {
|
|
1663
|
+
if (ch === 'R') c++; // Raw string literal prefix
|
|
1664
|
+
if (c === 0 || line[c - 1] !== '\\') {
|
|
1665
|
+
inString = !inString;
|
|
1666
|
+
stringQuote = inString ? '"' : '';
|
|
1667
|
+
}
|
|
1668
|
+
continue;
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
if (!inString && ch === '\'') {
|
|
1672
|
+
if (c === 0 || line[c - 1] !== '\\') {
|
|
1673
|
+
inChar = !inChar;
|
|
1674
|
+
}
|
|
1675
|
+
continue;
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
if (inString || inChar) continue;
|
|
1679
|
+
|
|
1680
|
+
if (ch === '{' || ch === '(' || ch === '[') {
|
|
1681
|
+
stack.push({ char: ch, line: lineNum, col: c + 1 });
|
|
1682
|
+
} else if (ch === '}' || ch === ')' || ch === ']') {
|
|
1683
|
+
const expectedOpening = matchingPairs[ch];
|
|
1684
|
+
const last = stack.pop();
|
|
1685
|
+
if (!last) {
|
|
1686
|
+
diagnostics.push({
|
|
1687
|
+
id: `cpp-bracket-unmatched-${lineNum}-${c + 1}`,
|
|
1688
|
+
file: filename,
|
|
1689
|
+
line: lineNum,
|
|
1690
|
+
col: c + 1,
|
|
1691
|
+
severity: 'error',
|
|
1692
|
+
message: `Unmatched closing bracket '${ch}' with no opening counterpart.`,
|
|
1693
|
+
source: 'cpp-linter'
|
|
1694
|
+
});
|
|
1695
|
+
} else if (last.char !== expectedOpening) {
|
|
1696
|
+
diagnostics.push({
|
|
1697
|
+
id: `cpp-bracket-mismatch-${lineNum}-${c + 1}`,
|
|
1698
|
+
file: filename,
|
|
1699
|
+
line: lineNum,
|
|
1700
|
+
col: c + 1,
|
|
1701
|
+
severity: 'error',
|
|
1702
|
+
message: `Mismatched bracket: found '${ch}' but expected closing for '${last.char}' from line ${last.line}.`,
|
|
1703
|
+
source: 'cpp-linter'
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
if (inString && !inBlockComment) {
|
|
1710
|
+
diagnostics.push({
|
|
1711
|
+
id: `cpp-string-unterminated-${lineNum}`,
|
|
1712
|
+
file: filename,
|
|
1713
|
+
line: lineNum,
|
|
1714
|
+
col: line.length,
|
|
1715
|
+
severity: 'error',
|
|
1716
|
+
message: 'Unterminated string literal on line.',
|
|
1717
|
+
source: 'cpp-linter'
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
for (const unclosed of stack) {
|
|
1723
|
+
diagnostics.push({
|
|
1724
|
+
id: `cpp-bracket-unclosed-${unclosed.line}-${unclosed.col}`,
|
|
1725
|
+
file: filename,
|
|
1726
|
+
line: unclosed.line,
|
|
1727
|
+
col: unclosed.col,
|
|
1728
|
+
severity: 'error',
|
|
1729
|
+
message: `Unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
|
|
1730
|
+
source: 'cpp-linter'
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
// 2. Validate #include <...> against C++20 standard library + VFS
|
|
1735
|
+
const includeRegex = /#include\s*([<"])([^>"]+)[>"]/g;
|
|
1736
|
+
let incMatch: RegExpExecArray | null;
|
|
1737
|
+
const includedHeaders = new Set<string>();
|
|
1738
|
+
|
|
1739
|
+
while ((incMatch = includeRegex.exec(source)) !== null) {
|
|
1740
|
+
const isAngle = incMatch[1] === '<';
|
|
1741
|
+
const hdr = incMatch[2].trim();
|
|
1742
|
+
includedHeaders.add(hdr);
|
|
1743
|
+
const lineIndex = source.slice(0, incMatch.index).split('\n').length;
|
|
1744
|
+
|
|
1745
|
+
if (isAngle) {
|
|
1746
|
+
const known = STANDARD_CPP20_HEADERS.has(hdr) ||
|
|
1747
|
+
hdr.startsWith('bits/') ||
|
|
1748
|
+
hdr.startsWith('codelab/') ||
|
|
1749
|
+
(vfs && (vfs.existsSync(`/usr/include/${hdr}`) || vfs.existsSync(`/workspace/${hdr}`)));
|
|
1750
|
+
if (!known) {
|
|
1751
|
+
diagnostics.push({
|
|
1752
|
+
id: `cpp-unknown-include-${lineIndex}`,
|
|
1753
|
+
file: filename,
|
|
1754
|
+
line: lineIndex,
|
|
1755
|
+
col: 1,
|
|
1756
|
+
severity: 'warning',
|
|
1757
|
+
message: `Unknown or unresolvable C++ header <${hdr}>.`,
|
|
1758
|
+
source: 'cpp-linter'
|
|
1759
|
+
});
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
// 3. Missing #include checks for DSA utilities and Test harness
|
|
1765
|
+
const hasDsaHeader = includedHeaders.has('codelab/dsa.hpp') || includedHeaders.has('bits/stdc++.h');
|
|
1766
|
+
const dsaSymbols = ['ListNode', 'TreeNode', 'buildLinkedList', 'linkedListToVector', 'buildBinaryTree'];
|
|
1767
|
+
for (const sym of dsaSymbols) {
|
|
1768
|
+
const symRegex = new RegExp(`\\b${sym}\\b`);
|
|
1769
|
+
if (symRegex.test(source) && !hasDsaHeader) {
|
|
1770
|
+
diagnostics.push({
|
|
1771
|
+
id: `cpp-missing-dsa-include-${sym}`,
|
|
1772
|
+
file: filename,
|
|
1773
|
+
line: 1,
|
|
1774
|
+
col: 1,
|
|
1775
|
+
severity: 'warning',
|
|
1776
|
+
message: `Symbol '${sym}' used without #include <codelab/dsa.hpp>.`,
|
|
1777
|
+
source: 'cpp-linter'
|
|
1778
|
+
});
|
|
1779
|
+
break;
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
const hasTestHeader = includedHeaders.has('codelab/test.hpp');
|
|
1784
|
+
const testSymbols = ['DESCRIBE', 'TEST', 'ASSERT_EQ', 'ASSERT_NE', 'ASSERT_TRUE', 'ASSERT_FALSE', 'CODELAB_TEST_EXIT_CODE'];
|
|
1785
|
+
for (const sym of testSymbols) {
|
|
1786
|
+
const symRegex = new RegExp(`\\b${sym}\\b`);
|
|
1787
|
+
if (symRegex.test(source) && !hasTestHeader) {
|
|
1788
|
+
diagnostics.push({
|
|
1789
|
+
id: `cpp-missing-test-include-${sym}`,
|
|
1790
|
+
file: filename,
|
|
1791
|
+
line: 1,
|
|
1792
|
+
col: 1,
|
|
1793
|
+
severity: 'warning',
|
|
1794
|
+
message: `Test macro '${sym}' used without #include <codelab/test.hpp>.`,
|
|
1795
|
+
source: 'cpp-linter'
|
|
1796
|
+
});
|
|
1797
|
+
break;
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
// 4. Suspicious assignment inside if condition (e.g. if (x = 5))
|
|
1802
|
+
for (let l = 0; l < lines.length; l++) {
|
|
1803
|
+
const line = lines[l];
|
|
1804
|
+
const assignMatch = /\bif\s*\(([^;)]*[^=!<>]=[^=][^;)]*)\)/.exec(line);
|
|
1805
|
+
if (assignMatch) {
|
|
1806
|
+
diagnostics.push({
|
|
1807
|
+
id: `cpp-suspicious-assign-${l + 1}`,
|
|
1808
|
+
file: filename,
|
|
1809
|
+
line: l + 1,
|
|
1810
|
+
col: assignMatch.index + 1,
|
|
1811
|
+
severity: 'warning',
|
|
1812
|
+
message: `Suspicious assignment '=' inside 'if' condition; did you mean '=='?`,
|
|
1813
|
+
source: 'cpp-linter'
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
// 5. Missing semicolon after class or struct definitions
|
|
1819
|
+
const structRegex = /(?:struct|class)\s+([A-Za-z0-9_]+)\s*\{[^}]*\}\s*(?!;)(?=[A-Za-z0-9_#\s\n])/g;
|
|
1820
|
+
let structMatch: RegExpExecArray | null;
|
|
1821
|
+
while ((structMatch = structRegex.exec(source)) !== null) {
|
|
1822
|
+
const lineIndex = source.slice(0, structMatch.index + structMatch[0].length).split('\n').length;
|
|
1823
|
+
diagnostics.push({
|
|
1824
|
+
id: `cpp-missing-semicolon-${lineIndex}`,
|
|
1825
|
+
file: filename,
|
|
1826
|
+
line: lineIndex,
|
|
1827
|
+
col: 1,
|
|
1828
|
+
severity: 'error',
|
|
1829
|
+
message: `Missing semicolon ';' after '${structMatch[1]}' class/struct definition.`,
|
|
1830
|
+
source: 'cpp-linter'
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
return diagnostics;
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
/**
|
|
1838
|
+
* Parses Clang / LLVM WASI compiler stderr and applies diagnostics to Monaco and DiagnosticsStore.
|
|
1839
|
+
*/
|
|
1840
|
+
export function applyClangStderrDiagnostics(
|
|
1841
|
+
stderrText: string,
|
|
1842
|
+
diagnosticsStore?: any,
|
|
1843
|
+
monacoInstance?: any,
|
|
1844
|
+
activeModel?: any
|
|
1845
|
+
): DiagnosticItem[] {
|
|
1846
|
+
const diagnostics: DiagnosticItem[] = [];
|
|
1847
|
+
if (!stderrText || typeof stderrText !== 'string') return diagnostics;
|
|
1848
|
+
|
|
1849
|
+
if (diagnosticsStore && typeof diagnosticsStore.clear === 'function') {
|
|
1850
|
+
diagnosticsStore.clear('clang');
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
const clangRegex = /(?:(?:^|\n)(?:\/workspace\/)?([^\s:\n]+)):(\d+):(\d+):\s*(fatal error|error|warning|note):\s*([^\n]+)/g;
|
|
1854
|
+
let match: RegExpExecArray | null;
|
|
1855
|
+
let idx = 0;
|
|
1856
|
+
|
|
1857
|
+
while ((match = clangRegex.exec(stderrText)) !== null) {
|
|
1858
|
+
const rawFile = match[1].trim();
|
|
1859
|
+
const line = parseInt(match[2], 10) || 1;
|
|
1860
|
+
const col = parseInt(match[3], 10) || 1;
|
|
1861
|
+
const rawKind = match[4].toLowerCase();
|
|
1862
|
+
const message = match[5].trim();
|
|
1863
|
+
|
|
1864
|
+
let severity: 'error' | 'warning' | 'info' = 'error';
|
|
1865
|
+
if (rawKind === 'warning') severity = 'warning';
|
|
1866
|
+
else if (rawKind === 'note') severity = 'info';
|
|
1867
|
+
|
|
1868
|
+
const item: DiagnosticItem = {
|
|
1869
|
+
id: `clang-${rawFile}-${line}-${col}-${idx++}`,
|
|
1870
|
+
file: rawFile,
|
|
1871
|
+
line,
|
|
1872
|
+
col,
|
|
1873
|
+
severity,
|
|
1874
|
+
message: `[Clang] ${message}`,
|
|
1875
|
+
source: 'clang'
|
|
1876
|
+
};
|
|
1877
|
+
diagnostics.push(item);
|
|
1878
|
+
if (diagnosticsStore && typeof diagnosticsStore.add === 'function') {
|
|
1879
|
+
diagnosticsStore.add(item);
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === 'function') {
|
|
1884
|
+
const markers = diagnostics.map((d) => ({
|
|
1885
|
+
startLineNumber: d.line,
|
|
1886
|
+
startColumn: d.col || 1,
|
|
1887
|
+
endLineNumber: d.line,
|
|
1888
|
+
endColumn: (d.col || 1) + 20,
|
|
1889
|
+
message: d.message,
|
|
1890
|
+
severity: d.severity === 'error'
|
|
1891
|
+
? monacoInstance.MarkerSeverity.Error
|
|
1892
|
+
: (d.severity === 'warning' ? monacoInstance.MarkerSeverity.Warning : monacoInstance.MarkerSeverity.Info)
|
|
1893
|
+
}));
|
|
1894
|
+
monacoInstance.editor.setModelMarkers(activeModel, 'clang', markers);
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
return diagnostics;
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1002
1900
|
/**
|
|
1003
1901
|
* Real C++20 in WebAssembly Extension for CodeLab (`@innovatorved/code-lab/extensions/cpp`).
|
|
1004
1902
|
*
|
|
@@ -1008,8 +1906,9 @@ export function registerCppCompilerOnRuntime(toolchain: CppToolchainManager) {
|
|
|
1008
1906
|
* - `JS | TS | C++` language switcher in the CodeLab workbench
|
|
1009
1907
|
* - `g++`, `clang++`, `c++`, and `./a.out` binary execution in the POSIX shell
|
|
1010
1908
|
* - Guided Lab `cppStarterFiles`, `cppSolutionFiles`, and `cppFiles` curriculum support
|
|
1909
|
+
* - Monaco IntelliSense, hovers, debounced C++20 static linter, and Clang compiler squiggles
|
|
1011
1910
|
*/
|
|
1012
|
-
export function
|
|
1911
|
+
export function installCppExtension(workbench: any, options: ExtendedCppExtensionOptions = {}) {
|
|
1013
1912
|
const toolchain = new CppToolchainManager(options);
|
|
1014
1913
|
const compilerFn = registerCppCompilerOnRuntime(toolchain);
|
|
1015
1914
|
|
|
@@ -1019,6 +1918,11 @@ export function cppExtension(workbench: any, options: ExtendedCppExtensionOption
|
|
|
1019
1918
|
workbench.cppCompiler = compilerFn;
|
|
1020
1919
|
workbench.cppOptions = toolchain.options;
|
|
1021
1920
|
|
|
1921
|
+
// Register Monaco language service if monaco is available
|
|
1922
|
+
if (typeof window !== 'undefined' && (window as any).monaco) {
|
|
1923
|
+
registerMonacoCppLanguageService((window as any).monaco);
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1022
1926
|
if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
|
|
1023
1927
|
workbench.enabledLanguages = new Set(['js', 'cpp']);
|
|
1024
1928
|
} else {
|
|
@@ -1052,6 +1956,39 @@ export function cppExtension(workbench: any, options: ExtendedCppExtensionOption
|
|
|
1052
1956
|
|
|
1053
1957
|
workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
|
|
1054
1958
|
|
|
1959
|
+
// Wire up debounced static linter if workbench has diagnostics store
|
|
1960
|
+
if (workbench._diagnosticsStore) {
|
|
1961
|
+
let lintTimer: any = null;
|
|
1962
|
+
const originalOnCodeChange = workbench.options?.onCodeChange;
|
|
1963
|
+
workbench._cppLintHandler = (file: string, code: string) => {
|
|
1964
|
+
if (!file || !/\.(?:cpp|cc|cxx|hpp|h)$/.test(file)) return;
|
|
1965
|
+
if (lintTimer) clearTimeout(lintTimer);
|
|
1966
|
+
lintTimer = setTimeout(() => {
|
|
1967
|
+
const diags = analyzeCppSource(code, file, workbench.vfs);
|
|
1968
|
+
workbench._diagnosticsStore.clear('cpp-linter');
|
|
1969
|
+
for (const d of diags) {
|
|
1970
|
+
workbench._diagnosticsStore.add(d);
|
|
1971
|
+
}
|
|
1972
|
+
if (typeof window !== 'undefined' && (window as any).monaco && workbench.editor) {
|
|
1973
|
+
const model = workbench.editor.getModel();
|
|
1974
|
+
if (model) {
|
|
1975
|
+
const markers = diags.map((d) => ({
|
|
1976
|
+
startLineNumber: d.line,
|
|
1977
|
+
startColumn: d.col || 1,
|
|
1978
|
+
endLineNumber: d.line,
|
|
1979
|
+
endColumn: (d.col || 1) + 20,
|
|
1980
|
+
message: d.message,
|
|
1981
|
+
severity: d.severity === 'error'
|
|
1982
|
+
? (window as any).monaco.MarkerSeverity.Error
|
|
1983
|
+
: (window as any).monaco.MarkerSeverity.Warning
|
|
1984
|
+
}));
|
|
1985
|
+
(window as any).monaco.editor.setModelMarkers(model, 'cpp-linter', markers);
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
}, 180);
|
|
1989
|
+
};
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1055
1992
|
if (options.preload) {
|
|
1056
1993
|
toolchain.ensureLoaded().catch((err) => {
|
|
1057
1994
|
if (typeof workbench._appendTerminalOutput === 'function') {
|
|
@@ -1062,6 +1999,8 @@ export function cppExtension(workbench: any, options: ExtendedCppExtensionOption
|
|
|
1062
1999
|
|
|
1063
2000
|
if (options.activate && typeof workbench.setLanguage === 'function') {
|
|
1064
2001
|
workbench.setLanguage('cpp');
|
|
2002
|
+
} else if (typeof workbench._refreshToolbarAndTabs === 'function') {
|
|
2003
|
+
workbench._refreshToolbarAndTabs();
|
|
1065
2004
|
} else if (typeof workbench._renderShell === 'function' && workbench.container) {
|
|
1066
2005
|
workbench._renderShell();
|
|
1067
2006
|
if (typeof workbench._bindEvents === 'function') workbench._bindEvents();
|
|
@@ -1071,11 +2010,33 @@ export function cppExtension(workbench: any, options: ExtendedCppExtensionOption
|
|
|
1071
2010
|
return workbench;
|
|
1072
2011
|
}
|
|
1073
2012
|
|
|
2013
|
+
export function cppExtension(workbenchOrOptions?: any, maybeOptions?: ExtendedCppExtensionOptions): any {
|
|
2014
|
+
if (workbenchOrOptions === null) {
|
|
2015
|
+
const toolchain = new CppToolchainManager(maybeOptions || {});
|
|
2016
|
+
registerCppCompilerOnRuntime(toolchain);
|
|
2017
|
+
return toolchain;
|
|
2018
|
+
}
|
|
2019
|
+
if (
|
|
2020
|
+
workbenchOrOptions === undefined ||
|
|
2021
|
+
(typeof workbenchOrOptions === 'object' &&
|
|
2022
|
+
!('enabledLanguages' in workbenchOrOptions) &&
|
|
2023
|
+
!('container' in workbenchOrOptions) &&
|
|
2024
|
+
!('_renderShell' in workbenchOrOptions))
|
|
2025
|
+
) {
|
|
2026
|
+
const opts = (workbenchOrOptions || {}) as ExtendedCppExtensionOptions;
|
|
2027
|
+
const plugin: any = (wb: any, runOpts: any = {}) => {
|
|
2028
|
+
return installCppExtension(wb, { ...opts, ...(runOpts || {}) });
|
|
2029
|
+
};
|
|
2030
|
+
plugin.extensionName = 'cpp';
|
|
2031
|
+
plugin.languageId = 'cpp' as const;
|
|
2032
|
+
plugin.install = plugin;
|
|
2033
|
+
return plugin;
|
|
2034
|
+
}
|
|
2035
|
+
return installCppExtension(workbenchOrOptions, maybeOptions);
|
|
2036
|
+
}
|
|
2037
|
+
|
|
1074
2038
|
export function createCppExtension(options: ExtendedCppExtensionOptions = {}) {
|
|
1075
|
-
|
|
1076
|
-
plugin.extensionName = 'cpp';
|
|
1077
|
-
plugin.languageId = 'cpp' as const;
|
|
1078
|
-
return plugin;
|
|
2039
|
+
return cppExtension(options);
|
|
1079
2040
|
}
|
|
1080
2041
|
|
|
1081
2042
|
export default cppExtension;
|