@innovatorved/code-lab 0.1.13 → 0.3.0

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.
Files changed (80) hide show
  1. package/ARCHITECTURE.md +12 -7
  2. package/CHANGELOG.md +134 -0
  3. package/README.md +59 -9
  4. package/dist/code-lab.css +198 -0
  5. package/dist/code-lab.d.ts +37 -7
  6. package/dist/code-lab.esm.js +20444 -1278
  7. package/dist/code-lab.js +20439 -1276
  8. package/dist/extensions/cpp.d.ts +145 -0
  9. package/dist/extensions/cpp.esm.js +5932 -0
  10. package/dist/extensions/cpp.js +5951 -0
  11. package/dist/extensions/guided-lab.esm.js +86 -6
  12. package/dist/extensions/guided-lab.js +87 -6
  13. package/dist/extensions/javascript.d.ts +24 -0
  14. package/dist/extensions/javascript.esm.js +36 -0
  15. package/dist/extensions/javascript.js +59 -0
  16. package/dist/extensions/python.d.ts +92 -0
  17. package/dist/extensions/python.esm.js +5476 -0
  18. package/dist/extensions/python.js +5495 -0
  19. package/dist/extensions/typescript.d.ts +36 -0
  20. package/dist/extensions/typescript.esm.js +55 -0
  21. package/dist/extensions/typescript.js +78 -0
  22. package/dist/index.d.ts +9 -3
  23. package/dist/preview-sw.js +1 -1
  24. package/dist/runtime/index.d.ts +4 -0
  25. package/dist/runtime/module-loader.d.ts +11 -0
  26. package/dist/runtime/test-harness.d.ts +24 -0
  27. package/dist/runtime/vfs.d.ts +31 -0
  28. package/dist/runtime/wasi-host.d.ts +33 -0
  29. package/dist/runtime.d.ts +6 -0
  30. package/dist/runtime.esm.js +920 -15
  31. package/dist/runtime.js +914 -15
  32. package/dist/schemas.d.ts +237 -25
  33. package/dist/schemas.esm.js +85 -6
  34. package/dist/schemas.js +85 -6
  35. package/dist/shell/coreutils/compilers-cli.d.ts +24 -0
  36. package/dist/shell/index.d.ts +4 -0
  37. package/dist/shell/lexer-parser.d.ts +26 -0
  38. package/dist/shell.esm.js +289 -4
  39. package/dist/shell.js +289 -4
  40. package/dist/terminal.esm.js +1 -1
  41. package/dist/terminal.js +1 -1
  42. package/dist/workbench/command-palette.d.ts +10 -0
  43. package/dist/workbench/diff-editor.d.ts +26 -0
  44. package/dist/workbench/drawer.d.ts +18 -0
  45. package/dist/workbench/editor.d.ts +11 -0
  46. package/dist/workbench/file-tree.d.ts +11 -0
  47. package/dist/workbench/guided-pane.d.ts +11 -0
  48. package/dist/workbench/icons.d.ts +5 -0
  49. package/dist/workbench/index.d.ts +39 -0
  50. package/dist/workbench/share.d.ts +21 -0
  51. package/dist/workbench/styles.d.ts +4 -0
  52. package/dist/workbench/toolbar.d.ts +17 -0
  53. package/dist/workbench.d.ts +6 -1
  54. package/package.json +33 -3
  55. package/src/code-lab.css +198 -0
  56. package/src/extensions/cpp.ts +1786 -0
  57. package/src/extensions/guided-lab.ts +10 -0
  58. package/src/extensions/javascript.ts +54 -0
  59. package/src/extensions/python.ts +1293 -0
  60. package/src/extensions/typescript.ts +85 -0
  61. package/src/index.ts +66 -3
  62. package/src/runtime/index.ts +5 -0
  63. package/src/runtime/test-harness.ts +57 -0
  64. package/src/runtime.ts +915 -14
  65. package/src/schemas.ts +94 -7
  66. package/src/shell/coreutils/compilers-cli.ts +103 -0
  67. package/src/shell/index.ts +5 -0
  68. package/src/shell.ts +288 -3
  69. package/src/workbench/command-palette.ts +140 -0
  70. package/src/workbench/diff-editor.ts +216 -0
  71. package/src/workbench/drawer.ts +148 -0
  72. package/src/workbench/editor.ts +49 -0
  73. package/src/workbench/file-tree.ts +51 -0
  74. package/src/workbench/guided-pane.ts +33 -0
  75. package/src/workbench/icons.ts +48 -0
  76. package/src/workbench/index.ts +38 -0
  77. package/src/workbench/share.ts +99 -0
  78. package/src/workbench/styles.ts +200 -0
  79. package/src/workbench/toolbar.ts +171 -0
  80. package/src/workbench.ts +1016 -78
@@ -0,0 +1,1786 @@
1
+ import { CppExtensionOptions, CppExtensionOptionsSchema, CppToolchainProgress } from '../schemas';
2
+ import type { DiagnosticItem } from '../diagnostics';
3
+
4
+ /**
5
+ * Built-in competitive programming & DSA headers seeded into `/usr/include`
6
+ * inside the VirtualFS alongside the WASI sysroot.
7
+ */
8
+ export const BUILTIN_CPP_HEADERS: Record<string, string> = {
9
+ '/usr/include/bits/stdc++.h': `// CodeLab <bits/stdc++.h> — Competitive Programming & DSA Umbrella Header
10
+ #pragma once
11
+ #include <iostream>
12
+ #include <iomanip>
13
+ #include <sstream>
14
+ #include <fstream>
15
+ #include <string>
16
+ #include <string_view>
17
+ #include <vector>
18
+ #include <deque>
19
+ #include <list>
20
+ #include <forward_list>
21
+ #include <array>
22
+ #include <set>
23
+ #include <unordered_set>
24
+ #include <map>
25
+ #include <unordered_map>
26
+ #include <stack>
27
+ #include <queue>
28
+ #include <bitset>
29
+ #include <algorithm>
30
+ #include <numeric>
31
+ #include <iterator>
32
+ #include <functional>
33
+ #include <utility>
34
+ #include <tuple>
35
+ #include <optional>
36
+ #include <variant>
37
+ #include <any>
38
+ #include <memory>
39
+ #include <cmath>
40
+ #include <cstdlib>
41
+ #include <cstdio>
42
+ #include <cstring>
43
+ #include <climits>
44
+ #include <cfloat>
45
+ #include <cstdint>
46
+ #include <cassert>
47
+ #include <chrono>
48
+ #include <random>
49
+ #include <complex>
50
+ #include <exception>
51
+ #include <stdexcept>
52
+ #include <type_traits>
53
+ #include <limits>
54
+ `,
55
+
56
+ '/usr/include/codelab/dsa.hpp': `// CodeLab <codelab/dsa.hpp> — Data Structures & Algorithms Utilities
57
+ #pragma once
58
+ #include <iostream>
59
+ #include <vector>
60
+ #include <queue>
61
+ #include <string>
62
+ #include <sstream>
63
+ #include <climits>
64
+
65
+ namespace codelab {
66
+
67
+ struct ListNode {
68
+ int val;
69
+ ListNode* next;
70
+ ListNode() : val(0), next(nullptr) {}
71
+ explicit ListNode(int x) : val(x), next(nullptr) {}
72
+ ListNode(int x, ListNode* n) : val(x), next(n) {}
73
+ };
74
+
75
+ struct TreeNode {
76
+ int val;
77
+ TreeNode* left;
78
+ TreeNode* right;
79
+ TreeNode() : val(0), left(nullptr), right(nullptr) {}
80
+ explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
81
+ TreeNode(int x, TreeNode* l, TreeNode* r) : val(x), left(l), right(r) {}
82
+ };
83
+
84
+ inline ListNode* buildLinkedList(const std::vector<int>& values) {
85
+ ListNode dummy(0);
86
+ ListNode* tail = &dummy;
87
+ for (int v : values) {
88
+ tail->next = new ListNode(v);
89
+ tail = tail->next;
90
+ }
91
+ return dummy.next;
92
+ }
93
+
94
+ inline std::vector<int> linkedListToVector(const ListNode* head) {
95
+ std::vector<int> out;
96
+ while (head != nullptr) {
97
+ out.push_back(head->val);
98
+ head = head->next;
99
+ }
100
+ return out;
101
+ }
102
+
103
+ inline TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN) {
104
+ if (values.empty() || values[0] == nullSentinel) return nullptr;
105
+ TreeNode* root = new TreeNode(values[0]);
106
+ std::queue<TreeNode*> q;
107
+ q.push(root);
108
+ size_t i = 1;
109
+ while (!q.empty() && i < values.size()) {
110
+ TreeNode* curr = q.front();
111
+ q.pop();
112
+ if (i < values.size() && values[i] != nullSentinel) {
113
+ curr->left = new TreeNode(values[i]);
114
+ q.push(curr->left);
115
+ }
116
+ i++;
117
+ if (i < values.size() && values[i] != nullSentinel) {
118
+ curr->right = new TreeNode(values[i]);
119
+ q.push(curr->right);
120
+ }
121
+ i++;
122
+ }
123
+ return root;
124
+ }
125
+
126
+ template <typename T>
127
+ inline std::string vectorToString(const std::vector<T>& vec) {
128
+ std::ostringstream oss;
129
+ oss << "[";
130
+ for (size_t i = 0; i < vec.size(); ++i) {
131
+ if (i > 0) oss << ", ";
132
+ oss << vec[i];
133
+ }
134
+ oss << "]";
135
+ return oss.str();
136
+ }
137
+
138
+ template <typename T>
139
+ inline void printVector(const std::vector<T>& vec) {
140
+ std::cout << vectorToString(vec) << "\\n";
141
+ }
142
+
143
+ } // namespace codelab
144
+
145
+ using codelab::ListNode;
146
+ using codelab::TreeNode;
147
+ using codelab::buildLinkedList;
148
+ using codelab::linkedListToVector;
149
+ using codelab::buildBinaryTree;
150
+ using codelab::vectorToString;
151
+ using codelab::printVector;
152
+ `,
153
+
154
+ '/usr/include/codelab/test.hpp': `// CodeLab <codelab/test.hpp> — Zero-Overhead C++ Test Runner for CodeLab Test Suite & Guided Lab
155
+ #pragma once
156
+ #include <iostream>
157
+ #include <sstream>
158
+ #include <string>
159
+ #include <vector>
160
+ #include <functional>
161
+ #include <chrono>
162
+ #include <stdexcept>
163
+
164
+ namespace codelab {
165
+ namespace testing {
166
+
167
+ struct AssertionFailure : public std::exception {
168
+ std::string message;
169
+ std::string actual;
170
+ std::string expected;
171
+ std::string op;
172
+ AssertionFailure(std::string m, std::string a = "", std::string e = "", std::string o = "")
173
+ : message(std::move(m)), actual(std::move(a)), expected(std::move(e)), op(std::move(o)) {}
174
+ const char* what() const noexcept override { return message.c_str(); }
175
+ };
176
+
177
+ inline std::string escapeJson(const std::string& s) {
178
+ std::ostringstream o;
179
+ for (char c : s) {
180
+ switch (c) {
181
+ case '"': o << "\\\\\\""; break;
182
+ case '\\\\': o << "\\\\\\\\"; break;
183
+ case '\\b': o << "\\\\b"; break;
184
+ case '\\f': o << "\\\\f"; break;
185
+ case '\\n': o << "\\\\n"; break;
186
+ case '\\r': o << "\\\\r"; break;
187
+ case '\\t': o << "\\\\t"; break;
188
+ default: o << c; break;
189
+ }
190
+ }
191
+ return o.str();
192
+ }
193
+
194
+ template <typename T>
195
+ inline std::string formatVal(const T& val) {
196
+ std::ostringstream oss;
197
+ oss << val;
198
+ return oss.str();
199
+ }
200
+
201
+ template <typename T>
202
+ inline std::string formatVal(const std::vector<T>& vec) {
203
+ std::ostringstream oss;
204
+ oss << "[";
205
+ for (size_t i = 0; i < vec.size(); ++i) {
206
+ if (i > 0) oss << ", ";
207
+ oss << formatVal(vec[i]);
208
+ }
209
+ oss << "]";
210
+ return oss.str();
211
+ }
212
+
213
+ inline std::vector<std::string>& currentSuiteStack() {
214
+ static std::vector<std::string> stack;
215
+ return stack;
216
+ }
217
+
218
+ inline int& failedCount() {
219
+ static int count = 0;
220
+ return count;
221
+ }
222
+
223
+ inline void runTest(const std::string& name, const std::function<void()>& fn) {
224
+ std::string fullName = name;
225
+ const auto& stack = currentSuiteStack();
226
+ if (!stack.empty()) {
227
+ std::ostringstream oss;
228
+ for (const auto& s : stack) oss << s << " > ";
229
+ oss << name;
230
+ fullName = oss.str();
231
+ }
232
+ auto t0 = std::chrono::steady_clock::now();
233
+ try {
234
+ fn();
235
+ auto t1 = std::chrono::steady_clock::now();
236
+ double ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
237
+ std::cout << "__CODELAB_TEST__:{\\"name\\":\\"" << escapeJson(fullName)
238
+ << "\\",\\"passed\\":true,\\"durationMs\\":" << ms << "}\\n";
239
+ } catch (const AssertionFailure& af) {
240
+ failedCount()++;
241
+ auto t1 = std::chrono::steady_clock::now();
242
+ double ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
243
+ std::cout << "__CODELAB_TEST__:{\\"name\\":\\"" << escapeJson(fullName)
244
+ << "\\",\\"passed\\":false,\\"durationMs\\":" << ms
245
+ << ",\\"error\\":{\\"message\\":\\"" << escapeJson(af.message)
246
+ << "\\",\\"actual\\":\\"" << escapeJson(af.actual)
247
+ << "\\",\\"expected\\":\\"" << escapeJson(af.expected)
248
+ << "\\",\\"operator\\":\\"" << escapeJson(af.op) << "\\"}}\\n";
249
+ } catch (const std::exception& ex) {
250
+ failedCount()++;
251
+ auto t1 = std::chrono::steady_clock::now();
252
+ double ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
253
+ std::cout << "__CODELAB_TEST__:{\\"name\\":\\"" << escapeJson(fullName)
254
+ << "\\",\\"passed\\":false,\\"durationMs\\":" << ms
255
+ << ",\\"error\\":{\\"message\\":\\"" << escapeJson(ex.what()) << "\\"}}\\n";
256
+ }
257
+ }
258
+
259
+ inline void runSuite(const std::string& suiteName, const std::function<void()>& fn) {
260
+ currentSuiteStack().push_back(suiteName);
261
+ try {
262
+ fn();
263
+ } catch (...) {
264
+ currentSuiteStack().pop_back();
265
+ throw;
266
+ }
267
+ currentSuiteStack().pop_back();
268
+ }
269
+
270
+ template <typename A, typename B>
271
+ inline void assertEq(const A& actual, const B& expected, const char* exprA, const char* exprB, int line) {
272
+ if (!(actual == expected)) {
273
+ std::string aStr = formatVal(actual);
274
+ std::string eStr = formatVal(expected);
275
+ std::ostringstream msg;
276
+ msg << "Line " << line << ": Expected " << exprA << " == " << exprB << " (got " << aStr << ", expected " << eStr << ")";
277
+ throw AssertionFailure(msg.str(), aStr, eStr, "==");
278
+ }
279
+ }
280
+
281
+ template <typename A, typename B>
282
+ inline void assertNe(const A& actual, const B& expected, const char* exprA, const char* exprB, int line) {
283
+ if (!(actual != expected)) {
284
+ std::string aStr = formatVal(actual);
285
+ std::string eStr = formatVal(expected);
286
+ std::ostringstream msg;
287
+ msg << "Line " << line << ": Expected " << exprA << " != " << exprB << " (both were " << aStr << ")";
288
+ throw AssertionFailure(msg.str(), aStr, eStr, "!=");
289
+ }
290
+ }
291
+
292
+ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
293
+ if (cond != expected) {
294
+ std::ostringstream msg;
295
+ msg << "Line " << line << ": Expected " << expr << " to be " << (expected ? "true" : "false");
296
+ throw AssertionFailure(msg.str(), cond ? "true" : "false", expected ? "true" : "false", "bool");
297
+ }
298
+ }
299
+
300
+ } // namespace testing
301
+ } // namespace codelab
302
+
303
+ #define DESCRIBE(name, body) ::codelab::testing::runSuite((name), [&]() body)
304
+ #define TEST(name, body) ::codelab::testing::runTest((name), [&]() body)
305
+ #define IT(name, body) ::codelab::testing::runTest((name), [&]() body)
306
+ #define ASSERT_EQ(actual, expected) ::codelab::testing::assertEq((actual), (expected), #actual, #expected, __LINE__)
307
+ #define EXPECT_EQ(actual, expected) ::codelab::testing::assertEq((actual), (expected), #actual, #expected, __LINE__)
308
+ #define ASSERT_NE(actual, expected) ::codelab::testing::assertNe((actual), (expected), #actual, #expected, __LINE__)
309
+ #define ASSERT_TRUE(cond) ::codelab::testing::assertBool(static_cast<bool>(cond), true, #cond, __LINE__)
310
+ #define ASSERT_FALSE(cond) ::codelab::testing::assertBool(static_cast<bool>(cond), false, #cond, __LINE__)
311
+ #define CODELAB_TEST_EXIT_CODE() (::codelab::testing::failedCount() > 0 ? 1 : 0)
312
+ `
313
+ };
314
+
315
+ const IDB_NAME = 'codelab_cpp_toolchain_v1';
316
+ const IDB_STORE = 'assets';
317
+ const memoryAssetCache = new Map<string, Uint8Array>();
318
+
319
+ function openToolchainIdb(): Promise<IDBDatabase | null> {
320
+ if (typeof indexedDB === 'undefined') return Promise.resolve(null);
321
+ return new Promise((resolve) => {
322
+ try {
323
+ const req = indexedDB.open(IDB_NAME, 1);
324
+ req.onupgradeneeded = () => {
325
+ const db = req.result;
326
+ if (!db.objectStoreNames.contains(IDB_STORE)) {
327
+ db.createObjectStore(IDB_STORE);
328
+ }
329
+ };
330
+ req.onsuccess = () => resolve(req.result);
331
+ req.onerror = () => resolve(null);
332
+ } catch (err) {
333
+ if (err) resolve(null);
334
+ }
335
+ });
336
+ }
337
+
338
+ async function getCachedAsset(key: string): Promise<Uint8Array | null> {
339
+ const mem = memoryAssetCache.get(key);
340
+ if (mem) return mem;
341
+ const db = await openToolchainIdb();
342
+ if (!db) return null;
343
+ return new Promise((resolve) => {
344
+ try {
345
+ const tx = db.transaction(IDB_STORE, 'readonly');
346
+ const store = tx.objectStore(IDB_STORE);
347
+ const req = store.get(key);
348
+ req.onsuccess = () => {
349
+ const val = req.result;
350
+ if (val instanceof Uint8Array) {
351
+ memoryAssetCache.set(key, val);
352
+ resolve(val);
353
+ } else if (val instanceof ArrayBuffer) {
354
+ const arr = new Uint8Array(val);
355
+ memoryAssetCache.set(key, arr);
356
+ resolve(arr);
357
+ } else {
358
+ resolve(null);
359
+ }
360
+ };
361
+ req.onerror = () => resolve(null);
362
+ } catch (err) {
363
+ if (err) resolve(null);
364
+ }
365
+ });
366
+ }
367
+
368
+ async function setCachedAsset(key: string, data: Uint8Array): Promise<void> {
369
+ memoryAssetCache.set(key, data);
370
+ const db = await openToolchainIdb();
371
+ if (!db) return;
372
+ return new Promise((resolve) => {
373
+ try {
374
+ const tx = db.transaction(IDB_STORE, 'readwrite');
375
+ const store = tx.objectStore(IDB_STORE);
376
+ store.put(data, key);
377
+ tx.oncomplete = () => resolve();
378
+ tx.onerror = () => resolve();
379
+ } catch (err) {
380
+ if (err) resolve();
381
+ }
382
+ });
383
+ }
384
+
385
+ /**
386
+ * Extracts a POSIX UStar `.tar` archive into a `VirtualFS` instance.
387
+ */
388
+ export function extractTarToVfs(tarBytes: Uint8Array, vfs: any, baseDir = '/'): string[] {
389
+ const extractedPaths: string[] = [];
390
+ const decoder = new TextDecoder('utf-8');
391
+ let offset = 0;
392
+
393
+ const readString = (start: number, length: number): string => {
394
+ let end = start;
395
+ const max = Math.min(tarBytes.length, start + length);
396
+ while (end < max && tarBytes[end] !== 0) end++;
397
+ return decoder.decode(tarBytes.subarray(start, end)).trim();
398
+ };
399
+
400
+ while (offset + 512 <= tarBytes.length) {
401
+ const name = readString(offset, 100);
402
+ if (!name) {
403
+ offset += 512;
404
+ continue;
405
+ }
406
+ const sizeOctal = readString(offset + 124, 12);
407
+ const size = parseInt(sizeOctal || '0', 8) || 0;
408
+ const typeFlag = tarBytes[offset + 156];
409
+ const prefix = readString(offset + 345, 155);
410
+ const fullName = prefix ? `${prefix}/${name}` : name;
411
+ const cleanRel = fullName.replace(/^\.?\/+/, '');
412
+ const targetPath = baseDir === '/' ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, '')}/${cleanRel}`;
413
+
414
+ const dataStart = offset + 512;
415
+ const dataEnd = dataStart + size;
416
+
417
+ if (cleanRel) {
418
+ if (typeFlag === 53 || fullName.endsWith('/')) {
419
+ // Directory ('5')
420
+ if (!vfs.existsSync(targetPath)) {
421
+ vfs.mkdirSync(targetPath, { recursive: true });
422
+ }
423
+ } else if (typeFlag === 0 || typeFlag === 48) {
424
+ // Regular file ('0' or '\0')
425
+ const parentDir = targetPath.slice(0, targetPath.lastIndexOf('/')) || '/';
426
+ if (!vfs.existsSync(parentDir)) {
427
+ vfs.mkdirSync(parentDir, { recursive: true });
428
+ }
429
+ const fileData = tarBytes.slice(dataStart, dataEnd);
430
+ vfs.writeFileSync(targetPath, fileData);
431
+ extractedPaths.push(targetPath);
432
+ }
433
+ }
434
+
435
+ const blocks = Math.ceil(size / 512);
436
+ offset = dataStart + blocks * 512;
437
+ }
438
+
439
+ return extractedPaths;
440
+ }
441
+
442
+ /**
443
+ * Creates a POSIX UStar `.tar` archive from a map of file paths to contents.
444
+ * Useful for packaging custom sysroot headers/libraries or testing TAR extraction.
445
+ */
446
+ export function createTarArchive(files: Record<string, string | Uint8Array>): Uint8Array {
447
+ const encoder = new TextEncoder();
448
+ const chunks: Uint8Array[] = [];
449
+
450
+ for (const [rawPath, content] of Object.entries(files)) {
451
+ const cleanPath = rawPath.replace(/^\/+/, '');
452
+ const data = typeof content === 'string' ? encoder.encode(content) : content;
453
+ const header = new Uint8Array(512);
454
+
455
+ const writeField = (str: string, offset: number, maxLen: number) => {
456
+ const bytes = encoder.encode(str);
457
+ header.set(bytes.subarray(0, Math.min(bytes.length, maxLen)), offset);
458
+ };
459
+
460
+ writeField(cleanPath, 0, 100);
461
+ writeField('0000644\0', 100, 8);
462
+ writeField('0000000\0', 108, 8);
463
+ writeField('0000000\0', 116, 8);
464
+ writeField(data.byteLength.toString(8).padStart(11, '0') + '\0', 124, 12);
465
+ writeField(Math.floor(Date.now() / 1000).toString(8).padStart(11, '0') + '\0', 136, 12);
466
+ // Checksum placeholder (8 spaces)
467
+ for (let i = 148; i < 156; i++) header[i] = 32;
468
+ header[156] = 48; // '0' regular file
469
+ writeField('ustar\0', 257, 6);
470
+ writeField('00', 263, 2);
471
+
472
+ let chksum = 0;
473
+ for (let i = 0; i < 512; i++) chksum += header[i];
474
+ writeField(chksum.toString(8).padStart(6, '0') + '\0 ', 148, 8);
475
+
476
+ chunks.push(header);
477
+ chunks.push(data);
478
+ const remainder = data.byteLength % 512;
479
+ if (remainder !== 0) {
480
+ chunks.push(new Uint8Array(512 - remainder));
481
+ }
482
+ }
483
+
484
+ // Two 512-byte zero blocks mark end-of-archive
485
+ chunks.push(new Uint8Array(1024));
486
+
487
+ const totalLen = chunks.reduce((acc, c) => acc + c.byteLength, 0);
488
+ const out = new Uint8Array(totalLen);
489
+ let pos = 0;
490
+ for (const c of chunks) {
491
+ out.set(c, pos);
492
+ pos += c.byteLength;
493
+ }
494
+ return out;
495
+ }
496
+
497
+ /**
498
+ * Seeds built-in C++ headers (`<bits/stdc++.h>`, `<codelab/dsa.hpp>`, `<codelab/test.hpp>`)
499
+ * and any user-provided extra headers into a VirtualFS instance.
500
+ */
501
+ export function seedCppHeadersIntoVfs(vfs: any, extraHeaders?: Record<string, string>) {
502
+ if (!vfs) return;
503
+ const allHeaders: Record<string, string> = {
504
+ ...BUILTIN_CPP_HEADERS,
505
+ ...(extraHeaders || {})
506
+ };
507
+ for (const [hPath, content] of Object.entries(allHeaders)) {
508
+ const absPath = hPath.startsWith('/') ? hPath : `/usr/include/${hPath}`;
509
+ const dir = absPath.slice(0, absPath.lastIndexOf('/')) || '/';
510
+ if (!vfs.existsSync(dir)) {
511
+ vfs.mkdirSync(dir, { recursive: true });
512
+ }
513
+ vfs.writeFileSync(absPath, content);
514
+ }
515
+ if (!vfs.existsSync('/tmp')) {
516
+ vfs.mkdirSync('/tmp', { recursive: true });
517
+ }
518
+ if (!vfs.existsSync('/usr/lib/wasm32-wasi')) {
519
+ vfs.mkdirSync('/usr/lib/wasm32-wasi', { recursive: true });
520
+ }
521
+ }
522
+
523
+ export interface CppCompileRequest {
524
+ entry?: string;
525
+ sourceFiles?: string[];
526
+ outputPath?: string;
527
+ std?: 'c++17' | 'c++20' | 'c++23';
528
+ optLevel?: '-O0' | '-O1' | '-O2' | '-O3';
529
+ extraFlags?: string[];
530
+ vfs: any;
531
+ onStdout?: (text: string) => void;
532
+ onStderr?: (text: string) => void;
533
+ }
534
+
535
+ export interface CppCompileResult {
536
+ ok: boolean;
537
+ exitCode: number;
538
+ wasmBinary: Uint8Array | null;
539
+ outputPath: string;
540
+ stdout: string;
541
+ stderr: string;
542
+ }
543
+
544
+ export const DEFAULT_CPP_CDN_BASE_URL = 'https://cdn.jsdelivr.net/npm/@yowasp/clang';
545
+ export type CppCompileOptions = CppCompileRequest;
546
+ export type CppCompilerAdapter = CppToolchainManager;
547
+
548
+ export interface ExtendedCppExtensionOptions extends Partial<CppExtensionOptions> {
549
+ /**
550
+ * Pre-loaded `clang.wasm` binary (optional; bypasses network download).
551
+ */
552
+ clangWasm?: Uint8Array;
553
+ /**
554
+ * Pre-loaded `lld.wasm` binary (optional; bypasses network download).
555
+ */
556
+ lldWasm?: Uint8Array;
557
+ /**
558
+ * Pre-loaded `sysroot.tar` archive (optional; bypasses network download).
559
+ */
560
+ sysrootTar?: Uint8Array;
561
+ /**
562
+ * Optional custom compilation hook `(req: CppCompileRequest) => Promise<CppCompileResult>`.
563
+ */
564
+ compilerHook?: (req: CppCompileRequest) => Promise<CppCompileResult>;
565
+ /**
566
+ * Immediately switch the active workbench language to 'cpp'.
567
+ */
568
+ activate?: boolean;
569
+ }
570
+
571
+ /**
572
+ * Manages downloading, IndexedDB caching (`codelab_cpp_toolchain_v1`), sysroot extraction,
573
+ * and 2-stage WASI Clang + LLD compilation (`clang.wasm` -> `lld.wasm` -> `.wasm` binary).
574
+ */
575
+ export class CppToolchainManager {
576
+ options: CppExtensionOptions & ExtendedCppExtensionOptions;
577
+ clangWasm: Uint8Array | null = null;
578
+ lldWasm: Uint8Array | null = null;
579
+ sysrootTar: Uint8Array | null = null;
580
+ private _loadingPromise: Promise<void> | null = null;
581
+
582
+ constructor(options: ExtendedCppExtensionOptions = {}) {
583
+ const parsed = CppExtensionOptionsSchema.parse(options);
584
+ this.options = { ...parsed, ...options };
585
+ if (options.clangWasm) this.clangWasm = options.clangWasm;
586
+ if (options.lldWasm) this.lldWasm = options.lldWasm;
587
+ if (options.sysrootTar) this.sysrootTar = options.sysrootTar;
588
+ }
589
+
590
+ private _emitProgress(progress: CppToolchainProgress) {
591
+ if (typeof this.options.onProgress === 'function') {
592
+ this.options.onProgress(progress);
593
+ }
594
+ }
595
+
596
+ private async _fetchAssetWithProgress(
597
+ url: string,
598
+ cacheKey: string,
599
+ label: string
600
+ ): Promise<Uint8Array> {
601
+ if (this.options.cacheInIndexedDB !== false) {
602
+ const cached = await getCachedAsset(cacheKey);
603
+ if (cached) {
604
+ this._emitProgress({
605
+ stage: 'caching',
606
+ loadedBytes: cached.byteLength,
607
+ totalBytes: cached.byteLength,
608
+ percent: 100,
609
+ message: `Loaded ${label} from IndexedDB cache`
610
+ });
611
+ return cached;
612
+ }
613
+ }
614
+
615
+ if (typeof fetch !== 'function') {
616
+ throw new Error(`Cannot download ${label}: global fetch is unavailable.`);
617
+ }
618
+
619
+ const res = await fetch(url);
620
+ if (!res.ok) {
621
+ throw new Error(`Failed to download ${label} from ${url} (HTTP ${res.status})`);
622
+ }
623
+
624
+ const totalBytes = Number(res.headers.get('content-length') || 0) || 12 * 1024 * 1024;
625
+ let data: Uint8Array;
626
+
627
+ if (res.body && typeof res.body.getReader === 'function') {
628
+ const reader = res.body.getReader();
629
+ const chunks: Uint8Array[] = [];
630
+ let loadedBytes = 0;
631
+
632
+ while (true) {
633
+ const { done, value } = await reader.read();
634
+ if (done) break;
635
+ if (value) {
636
+ chunks.push(value);
637
+ loadedBytes += value.byteLength;
638
+ const percent = Math.min(99, Math.round((loadedBytes / Math.max(totalBytes, loadedBytes)) * 100));
639
+ this._emitProgress({
640
+ stage: 'downloading',
641
+ loadedBytes,
642
+ totalBytes: Math.max(totalBytes, loadedBytes),
643
+ percent,
644
+ message: `Downloading ${label} (${(loadedBytes / (1024 * 1024)).toFixed(1)} MB)...`
645
+ });
646
+ }
647
+ }
648
+
649
+ data = new Uint8Array(loadedBytes);
650
+ let offset = 0;
651
+ for (const chunk of chunks) {
652
+ data.set(chunk, offset);
653
+ offset += chunk.byteLength;
654
+ }
655
+ } else {
656
+ const buf = await res.arrayBuffer();
657
+ data = new Uint8Array(buf);
658
+ }
659
+
660
+ if (this.options.cacheInIndexedDB !== false) {
661
+ await setCachedAsset(cacheKey, data);
662
+ }
663
+
664
+ return data;
665
+ }
666
+
667
+ async ensureLoaded(): Promise<void> {
668
+ if (this.clangWasm && this.lldWasm && this.sysrootTar) {
669
+ return;
670
+ }
671
+ if (this._loadingPromise) {
672
+ return this._loadingPromise;
673
+ }
674
+
675
+ this._loadingPromise = (async () => {
676
+ try {
677
+ const base = (this.options.toolchainUrl || 'https://cdn.jsdelivr.net/npm/@yowasp/clang').replace(/\/+$/, '');
678
+ const clangUrl = this.options.clangUrl || `${base}/clang.wasm`;
679
+ const lldUrl = this.options.lldUrl || `${base}/lld.wasm`;
680
+ const sysrootUrl = this.options.sysrootUrl || `${base}/sysroot.tar`;
681
+
682
+ if (!this.sysrootTar) {
683
+ this.sysrootTar = await this._fetchAssetWithProgress(
684
+ sysrootUrl,
685
+ `sysroot:${sysrootUrl}`,
686
+ 'WASI C++20 Sysroot (libc + libc++)'
687
+ );
688
+ }
689
+ if (!this.clangWasm) {
690
+ this.clangWasm = await this._fetchAssetWithProgress(
691
+ clangUrl,
692
+ `clang:${clangUrl}`,
693
+ 'Clang C++20 WebAssembly Compiler (clang.wasm)'
694
+ );
695
+ }
696
+ if (!this.lldWasm) {
697
+ this.lldWasm = await this._fetchAssetWithProgress(
698
+ lldUrl,
699
+ `lld:${lldUrl}`,
700
+ 'LLD WebAssembly Linker (lld.wasm)'
701
+ );
702
+ }
703
+
704
+ this._emitProgress({
705
+ stage: 'ready',
706
+ loadedBytes:
707
+ (this.clangWasm?.byteLength || 0) +
708
+ (this.lldWasm?.byteLength || 0) +
709
+ (this.sysrootTar?.byteLength || 0),
710
+ totalBytes:
711
+ (this.clangWasm?.byteLength || 0) +
712
+ (this.lldWasm?.byteLength || 0) +
713
+ (this.sysrootTar?.byteLength || 0),
714
+ percent: 100,
715
+ message: 'C++20 WebAssembly Toolchain Ready'
716
+ });
717
+ } finally {
718
+ this._loadingPromise = null;
719
+ }
720
+ })();
721
+
722
+ return this._loadingPromise;
723
+ }
724
+
725
+ prepareVfs(vfs: any): void {
726
+ if (!vfs) return;
727
+ if (this.sysrootTar && !vfs.existsSync('/usr/include/.sysroot_extracted')) {
728
+ extractTarToVfs(this.sysrootTar, vfs, '/');
729
+ if (!vfs.existsSync('/usr/include')) {
730
+ vfs.mkdirSync('/usr/include', { recursive: true });
731
+ }
732
+ vfs.writeFileSync('/usr/include/.sysroot_extracted', '1');
733
+ }
734
+ seedCppHeadersIntoVfs(vfs, this.options.extraHeaders);
735
+ }
736
+
737
+ async compile(req: CppCompileRequest): Promise<CppCompileResult> {
738
+ const vfs = req.vfs;
739
+ const outputPath = req.outputPath || '/workspace/a.out';
740
+ const std = req.std || this.options.std || 'c++20';
741
+ const optLevel = req.optLevel || this.options.optLevel || '-O2';
742
+
743
+ const rawSources =
744
+ req.sourceFiles && req.sourceFiles.length > 0
745
+ ? req.sourceFiles
746
+ : req.entry
747
+ ? [req.entry]
748
+ : ['/workspace/src/main.cpp'];
749
+
750
+ const sourceFiles = rawSources.map((s) => (s.startsWith('/') ? s : `/workspace/${s.replace(/^\/+/, '')}`));
751
+
752
+ for (const src of sourceFiles) {
753
+ if (!vfs.existsSync(src)) {
754
+ const msg = `clang++: error: no such file or directory: '${src}'\n`;
755
+ if (req.onStderr) req.onStderr(msg);
756
+ return { ok: false, exitCode: 1, wasmBinary: null, outputPath, stdout: '', stderr: msg };
757
+ }
758
+ }
759
+
760
+ seedCppHeadersIntoVfs(vfs, this.options.extraHeaders);
761
+
762
+ if (typeof this.options.compilerHook === 'function') {
763
+ return this.options.compilerHook({
764
+ ...req,
765
+ sourceFiles,
766
+ outputPath,
767
+ std,
768
+ optLevel
769
+ });
770
+ }
771
+
772
+ await this.ensureLoaded();
773
+ this.prepareVfs(vfs);
774
+
775
+ const runtime =
776
+ (typeof globalThis !== 'undefined' && (globalThis as any).CodeLabRuntime) ||
777
+ (typeof window !== 'undefined' && (window as any).CodeLabRuntime);
778
+
779
+ if (!runtime || typeof runtime.executeWasiModule !== 'function') {
780
+ throw new Error('CodeLabRuntime.executeWasiModule is unavailable.');
781
+ }
782
+
783
+ let stdoutAcc = '';
784
+ let stderrAcc = '';
785
+ const handleOut = (t: string) => {
786
+ stdoutAcc += t;
787
+ if (req.onStdout) req.onStdout(t);
788
+ };
789
+ const handleErr = (t: string) => {
790
+ stderrAcc += t;
791
+ if (req.onStderr) req.onStderr(t);
792
+ };
793
+
794
+ this._emitProgress({
795
+ stage: 'compiling',
796
+ loadedBytes: 100,
797
+ totalBytes: 100,
798
+ percent: 100,
799
+ message: `Compiling ${sourceFiles.map((s) => s.split('/').pop()).join(', ')} with Clang (${std}, ${optLevel})...`
800
+ });
801
+
802
+ const objectFiles: string[] = [];
803
+ for (let i = 0; i < sourceFiles.length; i++) {
804
+ const srcPath = sourceFiles[i];
805
+ const objPath = `/tmp/obj_${i}.o`;
806
+ objectFiles.push(objPath);
807
+
808
+ const clangArgs = [
809
+ 'clang++',
810
+ '-cc1',
811
+ '-triple',
812
+ 'wasm32-unknown-wasi',
813
+ '-emit-obj',
814
+ `-std=${std}`,
815
+ optLevel,
816
+ '-isysroot',
817
+ '/usr',
818
+ '-internal-isystem',
819
+ '/usr/include/c++/v1',
820
+ '-internal-isystem',
821
+ '/usr/include',
822
+ '-I',
823
+ '/usr/include',
824
+ '-I',
825
+ '/workspace',
826
+ '-I',
827
+ '/workspace/src',
828
+ ...(req.extraFlags || []),
829
+ '-o',
830
+ objPath,
831
+ srcPath
832
+ ];
833
+
834
+ const compileStep = await runtime.executeWasiModule(this.clangWasm, {
835
+ vfs,
836
+ args: clangArgs,
837
+ env: { PATH: '/usr/bin:/bin', TMPDIR: '/tmp' },
838
+ onStdout: handleOut,
839
+ onStderr: handleErr
840
+ });
841
+
842
+ if (compileStep.exitCode !== 0) {
843
+ return {
844
+ ok: false,
845
+ exitCode: compileStep.exitCode,
846
+ wasmBinary: null,
847
+ outputPath,
848
+ stdout: stdoutAcc,
849
+ stderr: stderrAcc
850
+ };
851
+ }
852
+ }
853
+
854
+ this._emitProgress({
855
+ stage: 'linking',
856
+ loadedBytes: 100,
857
+ totalBytes: 100,
858
+ percent: 100,
859
+ message: `Linking ${outputPath.split('/').pop()} with wasm-ld...`
860
+ });
861
+
862
+ const crt1Path = '/usr/lib/wasm32-wasi/crt1.o';
863
+ const hasCrt1 = vfs.existsSync(crt1Path);
864
+ const lldArgs = [
865
+ 'wasm-ld',
866
+ '--no-threads',
867
+ '--export-dynamic',
868
+ '-L/usr/lib/wasm32-wasi',
869
+ ...(hasCrt1 ? [crt1Path] : []),
870
+ ...objectFiles,
871
+ '-lc++',
872
+ '-lc++abi',
873
+ '-lc',
874
+ '-o',
875
+ outputPath
876
+ ];
877
+
878
+ const linkStep = await runtime.executeWasiModule(this.lldWasm, {
879
+ vfs,
880
+ args: lldArgs,
881
+ env: { PATH: '/usr/bin:/bin', TMPDIR: '/tmp' },
882
+ onStdout: handleOut,
883
+ onStderr: handleErr
884
+ });
885
+
886
+ if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
887
+ return {
888
+ ok: false,
889
+ exitCode: linkStep.exitCode || 1,
890
+ wasmBinary: null,
891
+ outputPath,
892
+ stdout: stdoutAcc,
893
+ stderr: stderrAcc || 'wasm-ld: error: failed to produce output binary\n'
894
+ };
895
+ }
896
+
897
+ const wasmBuf = vfs.readFileSync(outputPath);
898
+ const wasmBinary =
899
+ wasmBuf instanceof Uint8Array ? new Uint8Array(wasmBuf.buffer, wasmBuf.byteOffset, wasmBuf.byteLength) : new Uint8Array(wasmBuf);
900
+
901
+ this._emitProgress({
902
+ stage: 'ready',
903
+ loadedBytes: 100,
904
+ totalBytes: 100,
905
+ percent: 100,
906
+ message: 'C++20 WebAssembly Toolchain Ready'
907
+ });
908
+
909
+ return {
910
+ ok: true,
911
+ exitCode: 0,
912
+ wasmBinary,
913
+ outputPath,
914
+ stdout: stdoutAcc,
915
+ stderr: stderrAcc
916
+ };
917
+ }
918
+ }
919
+
920
+ /**
921
+ * Parses POSIX shell arguments for `g++` / `clang++` / `c++` commands.
922
+ */
923
+ export function parseCppCompilerFlags(args: string[], cwd = '/workspace') {
924
+ const sourceFiles: string[] = [];
925
+ const extraFlags: string[] = [];
926
+ let outputPath = `${cwd.replace(/\/+$/, '')}/a.out`;
927
+ let std: 'c++17' | 'c++20' | 'c++23' | undefined;
928
+ let optLevel: '-O0' | '-O1' | '-O2' | '-O3' | undefined;
929
+ let showVersion = false;
930
+ let showHelp = false;
931
+
932
+ for (let i = 0; i < args.length; i++) {
933
+ const arg = args[i];
934
+ if (arg === '--version' || arg === '-v') {
935
+ showVersion = true;
936
+ } else if (arg === '--help' || arg === '-h') {
937
+ showHelp = true;
938
+ } else if (arg === '-o' && i + 1 < args.length) {
939
+ const next = args[++i];
940
+ outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
941
+ } else if (arg.startsWith('-o') && arg.length > 2) {
942
+ const next = arg.slice(2);
943
+ outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
944
+ } else if (arg.startsWith('-std=')) {
945
+ const val = arg.slice(5);
946
+ if (val === 'c++17' || val === 'c++20' || val === 'c++23') {
947
+ std = val;
948
+ } else if (val === 'c++2a' || val === 'gnu++20') {
949
+ std = 'c++20';
950
+ } else if (val === 'c++2b' || val === 'gnu++23') {
951
+ std = 'c++23';
952
+ } else if (val === 'gnu++17') {
953
+ std = 'c++17';
954
+ }
955
+ } else if (arg === '-O0' || arg === '-O1' || arg === '-O2' || arg === '-O3') {
956
+ optLevel = arg;
957
+ } else if (arg.startsWith('-I') || arg.startsWith('-D') || arg.startsWith('-W')) {
958
+ extraFlags.push(arg);
959
+ } else if (!arg.startsWith('-')) {
960
+ const resolved = arg.startsWith('/') ? arg : `${cwd.replace(/\/+$/, '')}/${arg.replace(/^\.\//, '')}`;
961
+ sourceFiles.push(resolved);
962
+ }
963
+ }
964
+
965
+ return { sourceFiles, outputPath, std, optLevel, extraFlags, showVersion, showHelp };
966
+ }
967
+
968
+ /**
969
+ * Registers the C++20 WebAssembly compiler toolchain on the global runtime and workbench.
970
+ */
971
+ export function registerCppCompilerOnRuntime(toolchain: CppToolchainManager) {
972
+ const compilerFn = async (req: any) => {
973
+ const res = await toolchain.compile({
974
+ entry: req.entry,
975
+ sourceFiles: req.sourceFiles,
976
+ outputPath: req.outputPath || '/workspace/a.out',
977
+ std: req.std,
978
+ optLevel: req.optLevel,
979
+ extraFlags: req.extraFlags,
980
+ vfs: req.vfs,
981
+ onStdout: req.onStdout,
982
+ onStderr: req.onStderr
983
+ });
984
+ return {
985
+ ok: res.ok,
986
+ exitCode: res.exitCode,
987
+ wasmBinary: res.wasmBinary,
988
+ outputPath: res.outputPath
989
+ };
990
+ };
991
+
992
+ if (typeof globalThis !== 'undefined') {
993
+ (globalThis as any).__codelabCppCompiler = compilerFn;
994
+ (globalThis as any).__codelabCppToolchain = toolchain;
995
+ }
996
+ if (typeof window !== 'undefined') {
997
+ (window as any).__codelabCppCompiler = compilerFn;
998
+ (window as any).__codelabCppToolchain = toolchain;
999
+ }
1000
+ return compilerFn;
1001
+ }
1002
+
1003
+ // ── VS Code–Style C++20 Language Intelligence & Real-time Linter ─────────────
1004
+
1005
+ /**
1006
+ * Full C++20 standard library header set + built-in CodeLab headers.
1007
+ */
1008
+ export const STANDARD_CPP20_HEADERS: ReadonlySet<string> = new Set([
1009
+ 'concepts', 'coroutine', 'any', 'bitset', 'chrono', 'compare', 'csetjmp', 'csignal',
1010
+ 'cstdarg', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctime', 'expected',
1011
+ 'functional', 'initializer_list', 'optional', 'source_location', 'tuple', 'type_traits',
1012
+ 'typeindex', 'typeinfo', 'utility', 'variant', 'version', 'memory', 'memory_resource',
1013
+ 'new', 'scoped_allocator', 'climits', 'cfloat', 'cerrno', 'exception', 'stdexcept',
1014
+ 'system_error', 'stacktrace', 'cassert', 'cctype', 'cwctype', 'cwchar', 'cuchar',
1015
+ 'string', 'string_view', 'format', 'span', 'array', 'deque', 'forward_list', 'list',
1016
+ 'vector', 'map', 'set', 'unordered_map', 'unordered_set', 'queue', 'stack', 'flat_map',
1017
+ 'flat_set', 'mdspan', 'iterator', 'ranges', 'algorithm', 'numeric', 'cmath', 'complex',
1018
+ 'valarray', 'random', 'ratio', 'cfenv', 'bit', 'numbers', 'locale', 'clocale', 'codecvt',
1019
+ 'ios', 'iosfwd', 'iostream', 'istream', 'ostream', 'sstream', 'fstream', 'syncstream',
1020
+ 'iomanip', 'streambuf', 'strstream', 'filesystem', 'regex', 'atomic', 'thread', 'stop_token',
1021
+ 'mutex', 'shared_mutex', 'condition_variable', 'future', 'semaphore', 'latch', 'barrier',
1022
+ 'bits/stdc++.h', 'codelab/dsa.hpp', 'codelab/test.hpp'
1023
+ ]);
1024
+
1025
+ export interface CppSymbolDoc {
1026
+ label: string;
1027
+ kind?: string;
1028
+ detail: string;
1029
+ documentation: string;
1030
+ insertText?: string;
1031
+ header?: string;
1032
+ complexity?: string;
1033
+ }
1034
+
1035
+ export const CPP_COMPLETIONS_AND_HOVERS: Record<string, CppSymbolDoc> = {
1036
+ 'std::vector': {
1037
+ label: 'std::vector',
1038
+ detail: 'template <typename T, typename Allocator = std::allocator<T>> class vector;',
1039
+ 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)$',
1040
+ insertText: 'std::vector<${1:int}> ${2:vec};',
1041
+ header: '<vector>',
1042
+ complexity: 'O(1) access, Amortized O(1) push_back'
1043
+ },
1044
+ 'std::unordered_map': {
1045
+ label: 'std::unordered_map',
1046
+ detail: 'template <typename Key, typename T> class unordered_map;',
1047
+ 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)$',
1048
+ insertText: 'std::unordered_map<${1:std::string}, ${2:int}> ${3:map};',
1049
+ header: '<unordered_map>',
1050
+ complexity: 'Average O(1) lookup & insertion'
1051
+ },
1052
+ 'std::map': {
1053
+ label: 'std::map',
1054
+ detail: 'template <typename Key, typename T> class map;',
1055
+ 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)$',
1056
+ insertText: 'std::map<${1:std::string}, ${2:int}> ${3:map};',
1057
+ header: '<map>',
1058
+ complexity: 'O(log N)'
1059
+ },
1060
+ 'std::set': {
1061
+ label: 'std::set',
1062
+ detail: 'template <typename Key> class set;',
1063
+ documentation: 'Sorted associative container containing unique keys (Red-Black Tree).\n\n- Header: `<set>`\n- Search/Insert/Delete: $O(\\log N)$',
1064
+ insertText: 'std::set<${1:int}> ${2:s};',
1065
+ header: '<set>',
1066
+ complexity: 'O(log N)'
1067
+ },
1068
+ 'std::priority_queue': {
1069
+ label: 'std::priority_queue',
1070
+ detail: 'template <typename T, typename Container = std::vector<T>> class priority_queue;',
1071
+ 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)$',
1072
+ insertText: 'std::priority_queue<${1:int}> ${2:pq};',
1073
+ header: '<queue>',
1074
+ complexity: 'O(1) top, O(log N) push/pop'
1075
+ },
1076
+ 'std::deque': {
1077
+ label: 'std::deque',
1078
+ detail: 'template <typename T> class deque;',
1079
+ documentation: 'Double-ended queue sequence container.\n\n- Header: `<deque>`\n- Push/Pop Front & Back: $O(1)$\n- Random Access: $O(1)$',
1080
+ insertText: 'std::deque<${1:int}> ${2:dq};',
1081
+ header: '<deque>',
1082
+ complexity: 'O(1) front & back operations'
1083
+ },
1084
+ 'std::stack': {
1085
+ label: 'std::stack',
1086
+ detail: 'template <typename T> class stack;',
1087
+ documentation: 'LIFO stack container adaptor.\n\n- Header: `<stack>`\n- Push / Pop / Top: $O(1)$',
1088
+ insertText: 'std::stack<${1:int}> ${2:st};',
1089
+ header: '<stack>',
1090
+ complexity: 'O(1)'
1091
+ },
1092
+ 'std::queue': {
1093
+ label: 'std::queue',
1094
+ detail: 'template <typename T> class queue;',
1095
+ documentation: 'FIFO queue container adaptor.\n\n- Header: `<queue>`\n- Push / Pop / Front: $O(1)$',
1096
+ insertText: 'std::queue<${1:int}> ${2:q};',
1097
+ header: '<queue>',
1098
+ complexity: 'O(1)'
1099
+ },
1100
+ 'std::string': {
1101
+ label: 'std::string',
1102
+ detail: 'typedef basic_string<char> string;',
1103
+ documentation: 'Standard char sequence container with SSO (Small String Optimization).\n\n- Header: `<string>`',
1104
+ insertText: 'std::string ${1:str};',
1105
+ header: '<string>',
1106
+ complexity: 'O(1) size, O(1) amortized append'
1107
+ },
1108
+ 'std::optional': {
1109
+ label: 'std::optional',
1110
+ detail: 'template <typename T> class optional;',
1111
+ documentation: 'Manages an optional contained value, i.e. a value that may or may not be present.\n\n- Header: `<optional>`',
1112
+ insertText: 'std::optional<${1:int}> ${2:opt};',
1113
+ header: '<optional>',
1114
+ complexity: 'Zero heap allocation overhead'
1115
+ },
1116
+ 'std::pair': {
1117
+ label: 'std::pair',
1118
+ detail: 'template <typename T1, typename T2> struct pair;',
1119
+ documentation: 'Heterogeneous pair of values.\n\n- Header: `<utility>`',
1120
+ insertText: 'std::pair<${1:int}, ${2:int}> ${3:p};',
1121
+ header: '<utility>',
1122
+ complexity: 'O(1)'
1123
+ },
1124
+ 'std::tuple': {
1125
+ label: 'std::tuple',
1126
+ detail: 'template <typename... Types> class tuple;',
1127
+ documentation: 'Fixed-size collection of heterogeneous values.\n\n- Header: `<tuple>`',
1128
+ insertText: 'std::tuple<${1:int}, ${2:std::string}> ${3:t};',
1129
+ header: '<tuple>',
1130
+ complexity: 'O(1)'
1131
+ },
1132
+ 'std::sort': {
1133
+ label: 'std::sort',
1134
+ detail: 'void sort(RandomIt first, RandomIt last, Compare comp = {});',
1135
+ documentation: 'Sorts elements in range [first, last) in non-descending order (IntroSort).\n\n- Header: `<algorithm>`\n- Complexity: $O(N \\log N)$ comparisons',
1136
+ insertText: 'std::sort(${1:vec}.begin(), ${1:vec}.end());',
1137
+ header: '<algorithm>',
1138
+ complexity: 'O(N log N)'
1139
+ },
1140
+ 'std::lower_bound': {
1141
+ label: 'std::lower_bound',
1142
+ detail: 'ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value);',
1143
+ 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',
1144
+ insertText: 'std::lower_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
1145
+ header: '<algorithm>',
1146
+ complexity: 'O(log N)'
1147
+ },
1148
+ 'std::upper_bound': {
1149
+ label: 'std::upper_bound',
1150
+ detail: 'ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value);',
1151
+ documentation: 'Returns iterator to the first element that is strictly greater than value.\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$ comparisons',
1152
+ insertText: 'std::upper_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
1153
+ header: '<algorithm>',
1154
+ complexity: 'O(log N)'
1155
+ },
1156
+ 'std::binary_search': {
1157
+ label: 'std::binary_search',
1158
+ detail: 'bool binary_search(ForwardIt first, ForwardIt last, const T& value);',
1159
+ documentation: 'Checks if value exists in sorted range [first, last).\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$',
1160
+ insertText: 'std::binary_search(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
1161
+ header: '<algorithm>',
1162
+ complexity: 'O(log N)'
1163
+ },
1164
+ 'std::next_permutation': {
1165
+ label: 'std::next_permutation',
1166
+ detail: 'bool next_permutation(BidirIt first, BidirIt last);',
1167
+ documentation: 'Rearranges elements into the lexicographically next greater permutation.\n\n- Header: `<algorithm>`\n- Complexity: $O(N)$',
1168
+ insertText: 'std::next_permutation(${1:vec}.begin(), ${1:vec}.end());',
1169
+ header: '<algorithm>',
1170
+ complexity: 'O(N)'
1171
+ },
1172
+ 'std::accumulate': {
1173
+ label: 'std::accumulate',
1174
+ detail: 'T accumulate(InputIt first, InputIt last, T init);',
1175
+ documentation: 'Computes sum of the given value init and elements in range [first, last).\n\n- Header: `<numeric>`\n- Complexity: $O(N)$',
1176
+ insertText: 'std::accumulate(${1:vec}.begin(), ${1:vec}.end(), ${2:0});',
1177
+ header: '<numeric>',
1178
+ complexity: 'O(N)'
1179
+ },
1180
+ 'std::gcd': {
1181
+ label: 'std::gcd',
1182
+ detail: 'constexpr common_type_t<M, N> gcd(M m, N n);',
1183
+ documentation: 'Computes greatest common divisor of m and n (Euclidean algorithm).\n\n- Header: `<numeric>`\n- Complexity: $O(\\log(\\min(m, n)))$',
1184
+ insertText: 'std::gcd(${1:a}, ${2:b});',
1185
+ header: '<numeric>',
1186
+ complexity: 'O(log(min(a, b)))'
1187
+ },
1188
+ 'ListNode': {
1189
+ label: 'ListNode',
1190
+ detail: 'struct ListNode { int val; ListNode* next; ... };',
1191
+ documentation: 'Standard LeetCode / DSA singly linked list node.\n\n- Header: `<codelab/dsa.hpp>`',
1192
+ insertText: 'ListNode* ${1:head} = new ListNode(${2:0});',
1193
+ header: '<codelab/dsa.hpp>',
1194
+ complexity: 'O(1) allocation'
1195
+ },
1196
+ 'TreeNode': {
1197
+ label: 'TreeNode',
1198
+ detail: 'struct TreeNode { int val; TreeNode* left; TreeNode* right; ... };',
1199
+ documentation: 'Standard LeetCode / DSA binary tree node.\n\n- Header: `<codelab/dsa.hpp>`',
1200
+ insertText: 'TreeNode* ${1:root} = new TreeNode(${2:0});',
1201
+ header: '<codelab/dsa.hpp>',
1202
+ complexity: 'O(1) allocation'
1203
+ },
1204
+ 'buildLinkedList': {
1205
+ label: 'buildLinkedList',
1206
+ detail: 'ListNode* buildLinkedList(const std::vector<int>& values);',
1207
+ documentation: 'Constructs a singly linked list from a std::vector of integers.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
1208
+ insertText: 'buildLinkedList({${1:1, 2, 3}});',
1209
+ header: '<codelab/dsa.hpp>',
1210
+ complexity: 'O(N)'
1211
+ },
1212
+ 'linkedListToVector': {
1213
+ label: 'linkedListToVector',
1214
+ detail: 'std::vector<int> linkedListToVector(const ListNode* head);',
1215
+ documentation: 'Traverses a linked list and collects node values into a std::vector.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
1216
+ insertText: 'linkedListToVector(${1:head});',
1217
+ header: '<codelab/dsa.hpp>',
1218
+ complexity: 'O(N)'
1219
+ },
1220
+ 'buildBinaryTree': {
1221
+ label: 'buildBinaryTree',
1222
+ detail: 'TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN);',
1223
+ 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)$',
1224
+ insertText: 'buildBinaryTree({${1:1, 2, 3}});',
1225
+ header: '<codelab/dsa.hpp>',
1226
+ complexity: 'O(N)'
1227
+ },
1228
+ 'DESCRIBE': {
1229
+ label: 'DESCRIBE',
1230
+ detail: 'DESCRIBE(suite_name)',
1231
+ documentation: 'Defines a named test suite in the CodeLab test harness.\n\n- Header: `<codelab/test.hpp>`',
1232
+ insertText: 'DESCRIBE("${1:Suite Name}");\n',
1233
+ header: '<codelab/test.hpp>',
1234
+ complexity: 'CodeLab Test Suite'
1235
+ },
1236
+ 'TEST': {
1237
+ label: 'TEST',
1238
+ detail: 'TEST(test_name, block)',
1239
+ documentation: 'Defines and runs a single test case within the active suite.\n\n- Header: `<codelab/test.hpp>`',
1240
+ insertText: 'TEST("${1:should pass}", {\n ASSERT_EQ(${2:actual}, ${3:expected});\n});',
1241
+ header: '<codelab/test.hpp>',
1242
+ complexity: 'CodeLab Test Runner'
1243
+ },
1244
+ 'ASSERT_EQ': {
1245
+ label: 'ASSERT_EQ',
1246
+ detail: 'ASSERT_EQ(actual, expected)',
1247
+ documentation: 'Asserts that actual == expected; logs failure message and stack if not.\n\n- Header: `<codelab/test.hpp>`',
1248
+ insertText: 'ASSERT_EQ(${1:actual}, ${2:expected});',
1249
+ header: '<codelab/test.hpp>',
1250
+ complexity: 'Assertion'
1251
+ },
1252
+ 'ASSERT_TRUE': {
1253
+ label: 'ASSERT_TRUE',
1254
+ detail: 'ASSERT_TRUE(condition)',
1255
+ documentation: 'Asserts that condition evaluates to true.\n\n- Header: `<codelab/test.hpp>`',
1256
+ insertText: 'ASSERT_TRUE(${1:condition});',
1257
+ header: '<codelab/test.hpp>',
1258
+ complexity: 'Assertion'
1259
+ },
1260
+ 'ASSERT_FALSE': {
1261
+ label: 'ASSERT_FALSE',
1262
+ detail: 'ASSERT_FALSE(condition)',
1263
+ documentation: 'Asserts that condition evaluates to false.\n\n- Header: `<codelab/test.hpp>`',
1264
+ insertText: 'ASSERT_FALSE(${1:condition});',
1265
+ header: '<codelab/test.hpp>',
1266
+ complexity: 'Assertion'
1267
+ },
1268
+ 'ASSERT_NE': {
1269
+ label: 'ASSERT_NE',
1270
+ detail: 'ASSERT_NE(actual, expected)',
1271
+ documentation: 'Asserts that actual != expected.\n\n- Header: `<codelab/test.hpp>`',
1272
+ insertText: 'ASSERT_NE(${1:actual}, ${2:expected});',
1273
+ header: '<codelab/test.hpp>',
1274
+ complexity: 'Assertion'
1275
+ },
1276
+ 'CODELAB_TEST_EXIT_CODE': {
1277
+ label: 'CODELAB_TEST_EXIT_CODE',
1278
+ detail: 'CODELAB_TEST_EXIT_CODE()',
1279
+ documentation: 'Returns 0 if all tests passed, 1 if any failed.\n\n- Header: `<codelab/test.hpp>`',
1280
+ insertText: 'return CODELAB_TEST_EXIT_CODE();',
1281
+ header: '<codelab/test.hpp>',
1282
+ complexity: 'Exit Code'
1283
+ }
1284
+ };
1285
+
1286
+ let _monacoCppRegistered = false;
1287
+
1288
+ /**
1289
+ * Registers Monaco C++20 completion and hover providers.
1290
+ */
1291
+ export function registerMonacoCppLanguageService(monacoInstance: any): boolean {
1292
+ if (!monacoInstance || !monacoInstance.languages) return false;
1293
+ if (_monacoCppRegistered) return true;
1294
+ _monacoCppRegistered = true;
1295
+
1296
+ try {
1297
+ monacoInstance.languages.registerCompletionItemProvider('cpp', {
1298
+ triggerCharacters: ['.', ':', '>', '<'],
1299
+ provideCompletionItems(model: any, position: any) {
1300
+ const wordInfo = model.getWordUntilPosition(position);
1301
+ const range = {
1302
+ startLineNumber: position.lineNumber,
1303
+ endLineNumber: position.lineNumber,
1304
+ startColumn: wordInfo.startColumn,
1305
+ endColumn: wordInfo.endColumn
1306
+ };
1307
+
1308
+ const suggestions = Object.keys(CPP_COMPLETIONS_AND_HOVERS).map((key) => {
1309
+ const item = CPP_COMPLETIONS_AND_HOVERS[key];
1310
+ return {
1311
+ label: item.label,
1312
+ kind: monacoInstance.languages.CompletionItemKind.Function,
1313
+ detail: item.detail,
1314
+ documentation: { value: item.documentation },
1315
+ insertText: item.insertText || item.label,
1316
+ insertTextRules: monacoInstance.languages.CompletionItemInsertTextRule.InsertAsSnippet,
1317
+ range
1318
+ };
1319
+ });
1320
+
1321
+ return { suggestions };
1322
+ }
1323
+ });
1324
+
1325
+ monacoInstance.languages.registerHoverProvider('cpp', {
1326
+ provideHover(model: any, position: any) {
1327
+ const word = model.getWordAtPosition(position);
1328
+ if (!word) return null;
1329
+
1330
+ // Try exact match or std:: + word
1331
+ const key = CPP_COMPLETIONS_AND_HOVERS[word.word]
1332
+ ? word.word
1333
+ : (CPP_COMPLETIONS_AND_HOVERS['std::' + word.word] ? 'std::' + word.word : null);
1334
+
1335
+ if (!key) return null;
1336
+ const item = CPP_COMPLETIONS_AND_HOVERS[key];
1337
+ return {
1338
+ range: {
1339
+ startLineNumber: position.lineNumber,
1340
+ endLineNumber: position.lineNumber,
1341
+ startColumn: word.startColumn,
1342
+ endColumn: word.endColumn
1343
+ },
1344
+ contents: [
1345
+ { value: `**${item.label}** — \`${item.detail}\`` },
1346
+ { value: item.documentation }
1347
+ ]
1348
+ };
1349
+ }
1350
+ });
1351
+ return true;
1352
+ } catch (err) {
1353
+ if (typeof console !== 'undefined' && console.warn) {
1354
+ console.warn('[C++ Monaco Intelligence Error]:', err);
1355
+ }
1356
+ return false;
1357
+ }
1358
+ }
1359
+
1360
+ /**
1361
+ * Real-time C++20 static AST/syntax linter.
1362
+ * Debounced on keystroke in `.cpp`, `.cc`, `.cxx`, `.hpp`, `.h` files.
1363
+ */
1364
+ export function analyzeCppSource(source: string, filename = 'main.cpp', vfs?: any): DiagnosticItem[] {
1365
+ const diagnostics: DiagnosticItem[] = [];
1366
+ if (!source || typeof source !== 'string') return diagnostics;
1367
+
1368
+ const lines = source.split('\n');
1369
+
1370
+ // 1. Bracket stack matching: {}, (), []
1371
+ const stack: Array<{ char: string; line: number; col: number }> = [];
1372
+ const matchingPairs: Record<string, string> = { '}': '{', ')': '(', ']': '[' };
1373
+
1374
+ let inBlockComment = false;
1375
+ for (let l = 0; l < lines.length; l++) {
1376
+ const line = lines[l];
1377
+ const lineNum = l + 1;
1378
+ let inString = false;
1379
+ let inChar = false;
1380
+ let stringQuote = '';
1381
+
1382
+ for (let c = 0; c < line.length; c++) {
1383
+ const ch = line[c];
1384
+ const next = line[c + 1] || '';
1385
+
1386
+ if (inBlockComment) {
1387
+ if (ch === '*' && next === '/') {
1388
+ inBlockComment = false;
1389
+ c++;
1390
+ }
1391
+ continue;
1392
+ }
1393
+
1394
+ if (!inString && !inChar) {
1395
+ if (ch === '/' && next === '*') {
1396
+ inBlockComment = true;
1397
+ c++;
1398
+ continue;
1399
+ }
1400
+ if (ch === '/' && next === '/') {
1401
+ break; // Rest of line is comment
1402
+ }
1403
+ }
1404
+
1405
+ // Check string & char literal bounds
1406
+ if (!inChar && (ch === '"' || (ch === 'R' && next === '"'))) {
1407
+ if (ch === 'R') c++; // Raw string literal prefix
1408
+ if (c === 0 || line[c - 1] !== '\\') {
1409
+ inString = !inString;
1410
+ stringQuote = inString ? '"' : '';
1411
+ }
1412
+ continue;
1413
+ }
1414
+
1415
+ if (!inString && ch === '\'') {
1416
+ if (c === 0 || line[c - 1] !== '\\') {
1417
+ inChar = !inChar;
1418
+ }
1419
+ continue;
1420
+ }
1421
+
1422
+ if (inString || inChar) continue;
1423
+
1424
+ if (ch === '{' || ch === '(' || ch === '[') {
1425
+ stack.push({ char: ch, line: lineNum, col: c + 1 });
1426
+ } else if (ch === '}' || ch === ')' || ch === ']') {
1427
+ const expectedOpening = matchingPairs[ch];
1428
+ const last = stack.pop();
1429
+ if (!last) {
1430
+ diagnostics.push({
1431
+ id: `cpp-bracket-unmatched-${lineNum}-${c + 1}`,
1432
+ file: filename,
1433
+ line: lineNum,
1434
+ col: c + 1,
1435
+ severity: 'error',
1436
+ message: `Unmatched closing bracket '${ch}' with no opening counterpart.`,
1437
+ source: 'cpp-linter'
1438
+ });
1439
+ } else if (last.char !== expectedOpening) {
1440
+ diagnostics.push({
1441
+ id: `cpp-bracket-mismatch-${lineNum}-${c + 1}`,
1442
+ file: filename,
1443
+ line: lineNum,
1444
+ col: c + 1,
1445
+ severity: 'error',
1446
+ message: `Mismatched bracket: found '${ch}' but expected closing for '${last.char}' from line ${last.line}.`,
1447
+ source: 'cpp-linter'
1448
+ });
1449
+ }
1450
+ }
1451
+ }
1452
+
1453
+ if (inString && !inBlockComment) {
1454
+ diagnostics.push({
1455
+ id: `cpp-string-unterminated-${lineNum}`,
1456
+ file: filename,
1457
+ line: lineNum,
1458
+ col: line.length,
1459
+ severity: 'error',
1460
+ message: 'Unterminated string literal on line.',
1461
+ source: 'cpp-linter'
1462
+ });
1463
+ }
1464
+ }
1465
+
1466
+ for (const unclosed of stack) {
1467
+ diagnostics.push({
1468
+ id: `cpp-bracket-unclosed-${unclosed.line}-${unclosed.col}`,
1469
+ file: filename,
1470
+ line: unclosed.line,
1471
+ col: unclosed.col,
1472
+ severity: 'error',
1473
+ message: `Unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
1474
+ source: 'cpp-linter'
1475
+ });
1476
+ }
1477
+
1478
+ // 2. Validate #include <...> against C++20 standard library + VFS
1479
+ const includeRegex = /#include\s*([<"])([^>"]+)[>"]/g;
1480
+ let incMatch: RegExpExecArray | null;
1481
+ const includedHeaders = new Set<string>();
1482
+
1483
+ while ((incMatch = includeRegex.exec(source)) !== null) {
1484
+ const isAngle = incMatch[1] === '<';
1485
+ const hdr = incMatch[2].trim();
1486
+ includedHeaders.add(hdr);
1487
+ const lineIndex = source.slice(0, incMatch.index).split('\n').length;
1488
+
1489
+ if (isAngle) {
1490
+ const known = STANDARD_CPP20_HEADERS.has(hdr) ||
1491
+ hdr.startsWith('bits/') ||
1492
+ hdr.startsWith('codelab/') ||
1493
+ (vfs && (vfs.existsSync(`/usr/include/${hdr}`) || vfs.existsSync(`/workspace/${hdr}`)));
1494
+ if (!known) {
1495
+ diagnostics.push({
1496
+ id: `cpp-unknown-include-${lineIndex}`,
1497
+ file: filename,
1498
+ line: lineIndex,
1499
+ col: 1,
1500
+ severity: 'warning',
1501
+ message: `Unknown or unresolvable C++ header <${hdr}>.`,
1502
+ source: 'cpp-linter'
1503
+ });
1504
+ }
1505
+ }
1506
+ }
1507
+
1508
+ // 3. Missing #include checks for DSA utilities and Test harness
1509
+ const hasDsaHeader = includedHeaders.has('codelab/dsa.hpp') || includedHeaders.has('bits/stdc++.h');
1510
+ const dsaSymbols = ['ListNode', 'TreeNode', 'buildLinkedList', 'linkedListToVector', 'buildBinaryTree'];
1511
+ for (const sym of dsaSymbols) {
1512
+ const symRegex = new RegExp(`\\b${sym}\\b`);
1513
+ if (symRegex.test(source) && !hasDsaHeader) {
1514
+ diagnostics.push({
1515
+ id: `cpp-missing-dsa-include-${sym}`,
1516
+ file: filename,
1517
+ line: 1,
1518
+ col: 1,
1519
+ severity: 'warning',
1520
+ message: `Symbol '${sym}' used without #include <codelab/dsa.hpp>.`,
1521
+ source: 'cpp-linter'
1522
+ });
1523
+ break;
1524
+ }
1525
+ }
1526
+
1527
+ const hasTestHeader = includedHeaders.has('codelab/test.hpp');
1528
+ const testSymbols = ['DESCRIBE', 'TEST', 'ASSERT_EQ', 'ASSERT_NE', 'ASSERT_TRUE', 'ASSERT_FALSE', 'CODELAB_TEST_EXIT_CODE'];
1529
+ for (const sym of testSymbols) {
1530
+ const symRegex = new RegExp(`\\b${sym}\\b`);
1531
+ if (symRegex.test(source) && !hasTestHeader) {
1532
+ diagnostics.push({
1533
+ id: `cpp-missing-test-include-${sym}`,
1534
+ file: filename,
1535
+ line: 1,
1536
+ col: 1,
1537
+ severity: 'warning',
1538
+ message: `Test macro '${sym}' used without #include <codelab/test.hpp>.`,
1539
+ source: 'cpp-linter'
1540
+ });
1541
+ break;
1542
+ }
1543
+ }
1544
+
1545
+ // 4. Suspicious assignment inside if condition (e.g. if (x = 5))
1546
+ for (let l = 0; l < lines.length; l++) {
1547
+ const line = lines[l];
1548
+ const assignMatch = /\bif\s*\(([^;)]*[^=!<>]=[^=][^;)]*)\)/.exec(line);
1549
+ if (assignMatch) {
1550
+ diagnostics.push({
1551
+ id: `cpp-suspicious-assign-${l + 1}`,
1552
+ file: filename,
1553
+ line: l + 1,
1554
+ col: assignMatch.index + 1,
1555
+ severity: 'warning',
1556
+ message: `Suspicious assignment '=' inside 'if' condition; did you mean '=='?`,
1557
+ source: 'cpp-linter'
1558
+ });
1559
+ }
1560
+ }
1561
+
1562
+ // 5. Missing semicolon after class or struct definitions
1563
+ const structRegex = /(?:struct|class)\s+([A-Za-z0-9_]+)\s*\{[^}]*\}\s*(?!;)(?=[A-Za-z0-9_#\s\n])/g;
1564
+ let structMatch: RegExpExecArray | null;
1565
+ while ((structMatch = structRegex.exec(source)) !== null) {
1566
+ const lineIndex = source.slice(0, structMatch.index + structMatch[0].length).split('\n').length;
1567
+ diagnostics.push({
1568
+ id: `cpp-missing-semicolon-${lineIndex}`,
1569
+ file: filename,
1570
+ line: lineIndex,
1571
+ col: 1,
1572
+ severity: 'error',
1573
+ message: `Missing semicolon ';' after '${structMatch[1]}' class/struct definition.`,
1574
+ source: 'cpp-linter'
1575
+ });
1576
+ }
1577
+
1578
+ return diagnostics;
1579
+ }
1580
+
1581
+ /**
1582
+ * Parses Clang / LLVM WASI compiler stderr and applies diagnostics to Monaco and DiagnosticsStore.
1583
+ */
1584
+ export function applyClangStderrDiagnostics(
1585
+ stderrText: string,
1586
+ diagnosticsStore?: any,
1587
+ monacoInstance?: any,
1588
+ activeModel?: any
1589
+ ): DiagnosticItem[] {
1590
+ const diagnostics: DiagnosticItem[] = [];
1591
+ if (!stderrText || typeof stderrText !== 'string') return diagnostics;
1592
+
1593
+ if (diagnosticsStore && typeof diagnosticsStore.clear === 'function') {
1594
+ diagnosticsStore.clear('clang');
1595
+ }
1596
+
1597
+ const clangRegex = /(?:(?:^|\n)(?:\/workspace\/)?([^\s:\n]+)):(\d+):(\d+):\s*(fatal error|error|warning|note):\s*([^\n]+)/g;
1598
+ let match: RegExpExecArray | null;
1599
+ let idx = 0;
1600
+
1601
+ while ((match = clangRegex.exec(stderrText)) !== null) {
1602
+ const rawFile = match[1].trim();
1603
+ const line = parseInt(match[2], 10) || 1;
1604
+ const col = parseInt(match[3], 10) || 1;
1605
+ const rawKind = match[4].toLowerCase();
1606
+ const message = match[5].trim();
1607
+
1608
+ let severity: 'error' | 'warning' | 'info' = 'error';
1609
+ if (rawKind === 'warning') severity = 'warning';
1610
+ else if (rawKind === 'note') severity = 'info';
1611
+
1612
+ const item: DiagnosticItem = {
1613
+ id: `clang-${rawFile}-${line}-${col}-${idx++}`,
1614
+ file: rawFile,
1615
+ line,
1616
+ col,
1617
+ severity,
1618
+ message: `[Clang] ${message}`,
1619
+ source: 'clang'
1620
+ };
1621
+ diagnostics.push(item);
1622
+ if (diagnosticsStore && typeof diagnosticsStore.add === 'function') {
1623
+ diagnosticsStore.add(item);
1624
+ }
1625
+ }
1626
+
1627
+ if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === 'function') {
1628
+ const markers = diagnostics.map((d) => ({
1629
+ startLineNumber: d.line,
1630
+ startColumn: d.col || 1,
1631
+ endLineNumber: d.line,
1632
+ endColumn: (d.col || 1) + 20,
1633
+ message: d.message,
1634
+ severity: d.severity === 'error'
1635
+ ? monacoInstance.MarkerSeverity.Error
1636
+ : (d.severity === 'warning' ? monacoInstance.MarkerSeverity.Warning : monacoInstance.MarkerSeverity.Info)
1637
+ }));
1638
+ monacoInstance.editor.setModelMarkers(activeModel, 'clang', markers);
1639
+ }
1640
+
1641
+ return diagnostics;
1642
+ }
1643
+
1644
+ /**
1645
+ * Real C++20 in WebAssembly Extension for CodeLab (`@innovatorved/code-lab/extensions/cpp`).
1646
+ *
1647
+ * Enables:
1648
+ * - Real Clang/LLVM + LLD + WASI C++20 compilation in WebAssembly (~35 MB downloaded on demand & cached in IndexedDB)
1649
+ * - `<bits/stdc++.h>`, `<codelab/dsa.hpp>`, and `<codelab/test.hpp>` headers in VirtualFS
1650
+ * - `JS | TS | C++` language switcher in the CodeLab workbench
1651
+ * - `g++`, `clang++`, `c++`, and `./a.out` binary execution in the POSIX shell
1652
+ * - Guided Lab `cppStarterFiles`, `cppSolutionFiles`, and `cppFiles` curriculum support
1653
+ * - Monaco IntelliSense, hovers, debounced C++20 static linter, and Clang compiler squiggles
1654
+ */
1655
+ export function installCppExtension(workbench: any, options: ExtendedCppExtensionOptions = {}) {
1656
+ const toolchain = new CppToolchainManager(options);
1657
+ const compilerFn = registerCppCompilerOnRuntime(toolchain);
1658
+
1659
+ if (!workbench) return toolchain;
1660
+
1661
+ workbench.cppToolchain = toolchain;
1662
+ workbench.cppCompiler = compilerFn;
1663
+ workbench.cppOptions = toolchain.options;
1664
+
1665
+ // Register Monaco language service if monaco is available
1666
+ if (typeof window !== 'undefined' && (window as any).monaco) {
1667
+ registerMonacoCppLanguageService((window as any).monaco);
1668
+ }
1669
+
1670
+ if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
1671
+ workbench.enabledLanguages = new Set(['js', 'cpp']);
1672
+ } else {
1673
+ workbench.enabledLanguages.add('cpp');
1674
+ }
1675
+
1676
+ if (options.files && typeof options.files === 'object') {
1677
+ workbench.cppFiles = { ...(workbench.cppFiles || {}), ...options.files };
1678
+ if (workbench.guidedConfig) {
1679
+ workbench.guidedConfig.cppFiles = { ...(workbench.guidedConfig.cppFiles || {}), ...options.files };
1680
+ }
1681
+ }
1682
+ if (options.starterFiles && typeof options.starterFiles === 'object') {
1683
+ if (!workbench.guidedConfig) workbench.guidedConfig = {};
1684
+ workbench.guidedConfig.cppStarterFiles = {
1685
+ ...(workbench.guidedConfig.cppStarterFiles || {}),
1686
+ ...options.starterFiles
1687
+ };
1688
+ }
1689
+ if (options.solutionFiles && typeof options.solutionFiles === 'object') {
1690
+ if (!workbench.guidedConfig) workbench.guidedConfig = {};
1691
+ workbench.guidedConfig.cppSolutionFiles = {
1692
+ ...(workbench.guidedConfig.cppSolutionFiles || {}),
1693
+ ...options.solutionFiles
1694
+ };
1695
+ }
1696
+
1697
+ if (workbench.vfs) {
1698
+ seedCppHeadersIntoVfs(workbench.vfs, toolchain.options.extraHeaders);
1699
+ }
1700
+
1701
+ workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
1702
+
1703
+ // Wire up debounced static linter if workbench has diagnostics store
1704
+ if (workbench._diagnosticsStore) {
1705
+ let lintTimer: any = null;
1706
+ const originalOnCodeChange = workbench.options?.onCodeChange;
1707
+ workbench._cppLintHandler = (file: string, code: string) => {
1708
+ if (!file || !/\.(?:cpp|cc|cxx|hpp|h)$/.test(file)) return;
1709
+ if (lintTimer) clearTimeout(lintTimer);
1710
+ lintTimer = setTimeout(() => {
1711
+ const diags = analyzeCppSource(code, file, workbench.vfs);
1712
+ workbench._diagnosticsStore.clear('cpp-linter');
1713
+ for (const d of diags) {
1714
+ workbench._diagnosticsStore.add(d);
1715
+ }
1716
+ if (typeof window !== 'undefined' && (window as any).monaco && workbench.editor) {
1717
+ const model = workbench.editor.getModel();
1718
+ if (model) {
1719
+ const markers = diags.map((d) => ({
1720
+ startLineNumber: d.line,
1721
+ startColumn: d.col || 1,
1722
+ endLineNumber: d.line,
1723
+ endColumn: (d.col || 1) + 20,
1724
+ message: d.message,
1725
+ severity: d.severity === 'error'
1726
+ ? (window as any).monaco.MarkerSeverity.Error
1727
+ : (window as any).monaco.MarkerSeverity.Warning
1728
+ }));
1729
+ (window as any).monaco.editor.setModelMarkers(model, 'cpp-linter', markers);
1730
+ }
1731
+ }
1732
+ }, 180);
1733
+ };
1734
+ }
1735
+
1736
+ if (options.preload) {
1737
+ toolchain.ensureLoaded().catch((err) => {
1738
+ if (typeof workbench._appendTerminalOutput === 'function') {
1739
+ workbench._appendTerminalOutput('stderr', `[C++ Toolchain preload warning]: ${err.message || err}\n`);
1740
+ }
1741
+ });
1742
+ }
1743
+
1744
+ if (options.activate && typeof workbench.setLanguage === 'function') {
1745
+ workbench.setLanguage('cpp');
1746
+ } else if (typeof workbench._refreshToolbarAndTabs === 'function') {
1747
+ workbench._refreshToolbarAndTabs();
1748
+ } else if (typeof workbench._renderShell === 'function' && workbench.container) {
1749
+ workbench._renderShell();
1750
+ if (typeof workbench._bindEvents === 'function') workbench._bindEvents();
1751
+ if (typeof workbench._renderFileLists === 'function') workbench._renderFileLists();
1752
+ }
1753
+
1754
+ return workbench;
1755
+ }
1756
+
1757
+ export function cppExtension(workbenchOrOptions?: any, maybeOptions?: ExtendedCppExtensionOptions): any {
1758
+ if (workbenchOrOptions === null) {
1759
+ const toolchain = new CppToolchainManager(maybeOptions || {});
1760
+ registerCppCompilerOnRuntime(toolchain);
1761
+ return toolchain;
1762
+ }
1763
+ if (
1764
+ workbenchOrOptions === undefined ||
1765
+ (typeof workbenchOrOptions === 'object' &&
1766
+ !('enabledLanguages' in workbenchOrOptions) &&
1767
+ !('container' in workbenchOrOptions) &&
1768
+ !('_renderShell' in workbenchOrOptions))
1769
+ ) {
1770
+ const opts = (workbenchOrOptions || {}) as ExtendedCppExtensionOptions;
1771
+ const plugin: any = (wb: any, runOpts: any = {}) => {
1772
+ return installCppExtension(wb, { ...opts, ...(runOpts || {}) });
1773
+ };
1774
+ plugin.extensionName = 'cpp';
1775
+ plugin.languageId = 'cpp' as const;
1776
+ plugin.install = plugin;
1777
+ return plugin;
1778
+ }
1779
+ return installCppExtension(workbenchOrOptions, maybeOptions);
1780
+ }
1781
+
1782
+ export function createCppExtension(options: ExtendedCppExtensionOptions = {}) {
1783
+ return cppExtension(options);
1784
+ }
1785
+
1786
+ export default cppExtension;