@innovatorved/code-lab 0.7.0 → 0.7.2

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 (159) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +6 -6
  4. package/dist/code-lab-sql.esm.js +19 -19
  5. package/dist/code-lab-sql.umd.js +20 -20
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +1183 -1909
  9. package/dist/code-lab.js +1182 -1906
  10. package/dist/extensions/cpp.esm.js +132 -8760
  11. package/dist/extensions/cpp.js +124 -8770
  12. package/dist/extensions/guided-lab.esm.js +33 -6836
  13. package/dist/extensions/guided-lab.js +33 -6854
  14. package/dist/extensions/javascript.esm.js +1 -36
  15. package/dist/extensions/javascript.js +1 -58
  16. package/dist/extensions/python.esm.js +113 -8122
  17. package/dist/extensions/python.js +113 -8140
  18. package/dist/extensions/typescript.esm.js +1 -55
  19. package/dist/extensions/typescript.js +1 -77
  20. package/dist/index.d.ts +1 -1
  21. package/dist/logger.d.ts +4 -20
  22. package/dist/modular-kernel.d.ts +0 -5
  23. package/dist/packages/core/src/errors.d.ts +5 -1
  24. package/dist/packages/fs/src/backends.d.ts +0 -27
  25. package/dist/packages/fs/src/index.d.ts +1 -1
  26. package/dist/packages/ui/src/html.d.ts +1 -0
  27. package/dist/packages/ui/src/index.d.ts +1 -0
  28. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -11
  29. package/dist/packages/ui/src/observability.d.ts +1 -1
  30. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  31. package/dist/preview-sw.js +1 -1
  32. package/dist/runtime.d.ts +3 -0
  33. package/dist/runtime.esm.js +78 -78
  34. package/dist/runtime.js +78 -78
  35. package/dist/schemas.d.ts +10 -1
  36. package/dist/schemas.esm.js +33 -6815
  37. package/dist/schemas.js +33 -6831
  38. package/dist/shell.esm.js +277 -285
  39. package/dist/shell.js +277 -285
  40. package/dist/terminal.esm.js +9 -7
  41. package/dist/terminal.js +7 -7
  42. package/dist/workbench/command-palette.d.ts +0 -4
  43. package/dist/workbench/editor.d.ts +0 -4
  44. package/dist/workbench/index.d.ts +0 -22
  45. package/dist/workbench/intellisense.d.ts +1 -8
  46. package/dist/workbench/xterm-adapter.d.ts +0 -1
  47. package/package.json +4 -13
  48. package/dist/code-lab.umd.js +0 -6117
  49. package/dist/packages/editor/src/index.d.ts +0 -118
  50. package/dist/packages/preview/src/index.d.ts +0 -34
  51. package/dist/packages/runtime/src/index.d.ts +0 -47
  52. package/dist/packages/terminal/src/index.d.ts +0 -54
  53. package/dist/workbench/drawer.d.ts +0 -18
  54. package/dist/workbench/file-tree.d.ts +0 -11
  55. package/dist/workbench/guided-pane.d.ts +0 -11
  56. package/dist/workbench/styles.d.ts +0 -4
  57. package/dist/workbench/toolbar.d.ts +0 -17
  58. package/packages/commands/README.md +0 -7
  59. package/packages/commands/package.json +0 -16
  60. package/packages/commands/src/index.ts +0 -467
  61. package/packages/commands/tsconfig.json +0 -22
  62. package/packages/core/README.md +0 -12
  63. package/packages/core/package.json +0 -13
  64. package/packages/core/src/di.ts +0 -147
  65. package/packages/core/src/disposable.ts +0 -112
  66. package/packages/core/src/errors.ts +0 -205
  67. package/packages/core/src/events.ts +0 -157
  68. package/packages/core/src/index.ts +0 -49
  69. package/packages/core/src/path.ts +0 -118
  70. package/packages/core/src/registry.ts +0 -61
  71. package/packages/core/tsconfig.json +0 -19
  72. package/packages/editor/README.md +0 -9
  73. package/packages/editor/package.json +0 -18
  74. package/packages/editor/src/index.ts +0 -344
  75. package/packages/editor/tsconfig.json +0 -24
  76. package/packages/fs/README.md +0 -7
  77. package/packages/fs/package.json +0 -16
  78. package/packages/fs/src/backends.ts +0 -301
  79. package/packages/fs/src/index.ts +0 -18
  80. package/packages/fs/src/types.ts +0 -44
  81. package/packages/fs/src/vfs-service.ts +0 -257
  82. package/packages/fs/tsconfig.json +0 -22
  83. package/packages/preview/README.md +0 -3
  84. package/packages/preview/package.json +0 -16
  85. package/packages/preview/src/index.ts +0 -125
  86. package/packages/preview/tsconfig.json +0 -22
  87. package/packages/runtime/README.md +0 -3
  88. package/packages/runtime/package.json +0 -17
  89. package/packages/runtime/src/index.ts +0 -134
  90. package/packages/runtime/tsconfig.json +0 -23
  91. package/packages/settings/README.md +0 -7
  92. package/packages/settings/package.json +0 -16
  93. package/packages/settings/src/builtin-schemas.ts +0 -262
  94. package/packages/settings/src/configuration-service.ts +0 -609
  95. package/packages/settings/src/index.ts +0 -38
  96. package/packages/settings/src/jsonc.ts +0 -189
  97. package/packages/settings/src/schema.ts +0 -164
  98. package/packages/settings/tsconfig.json +0 -22
  99. package/packages/sql/README.md +0 -12
  100. package/packages/sql/package.json +0 -13
  101. package/packages/sql/src/completions.ts +0 -359
  102. package/packages/sql/src/diagnostics.ts +0 -200
  103. package/packages/sql/src/formatter.ts +0 -271
  104. package/packages/sql/src/index.ts +0 -54
  105. package/packages/sql/src/sql-editor.ts +0 -802
  106. package/packages/sql/src/styles.ts +0 -524
  107. package/packages/sql/src/tokenizer.ts +0 -457
  108. package/packages/sql/src/types.ts +0 -148
  109. package/packages/sql/tsconfig.json +0 -19
  110. package/packages/terminal/README.md +0 -3
  111. package/packages/terminal/package.json +0 -16
  112. package/packages/terminal/src/index.ts +0 -183
  113. package/packages/terminal/tsconfig.json +0 -22
  114. package/packages/ui/README.md +0 -8
  115. package/packages/ui/package.json +0 -18
  116. package/packages/ui/src/index.ts +0 -40
  117. package/packages/ui/src/observability.ts +0 -173
  118. package/packages/ui/src/plugin-registry.ts +0 -289
  119. package/packages/ui/src/settings-dialog.ts +0 -939
  120. package/packages/ui/src/themes.ts +0 -333
  121. package/packages/ui/tsconfig.json +0 -24
  122. package/src/code-lab.css +0 -8584
  123. package/src/csp.ts +0 -590
  124. package/src/diagnostics.ts +0 -287
  125. package/src/extensions/cpp.ts +0 -2389
  126. package/src/extensions/guided-lab.ts +0 -64
  127. package/src/extensions/javascript.ts +0 -54
  128. package/src/extensions/python.ts +0 -1737
  129. package/src/extensions/typescript.ts +0 -85
  130. package/src/extensions/umbrella.ts +0 -5
  131. package/src/html.ts +0 -88
  132. package/src/index.ts +0 -129
  133. package/src/logger.ts +0 -139
  134. package/src/modular-kernel.ts +0 -11
  135. package/src/preview-sw.js +0 -296
  136. package/src/runtime/test-harness.ts +0 -57
  137. package/src/runtime.ts +0 -10480
  138. package/src/sample.html +0 -304
  139. package/src/schemas.ts +0 -366
  140. package/src/scm.ts +0 -2453
  141. package/src/search.ts +0 -433
  142. package/src/shell.ts +0 -10987
  143. package/src/storage.ts +0 -773
  144. package/src/terminal.ts +0 -1400
  145. package/src/workbench/command-palette.ts +0 -381
  146. package/src/workbench/diff-editor.ts +0 -470
  147. package/src/workbench/drawer.ts +0 -157
  148. package/src/workbench/editor.ts +0 -49
  149. package/src/workbench/file-tree.ts +0 -51
  150. package/src/workbench/guided-pane.ts +0 -43
  151. package/src/workbench/icons.ts +0 -255
  152. package/src/workbench/index.ts +0 -44
  153. package/src/workbench/intellisense.ts +0 -1871
  154. package/src/workbench/share.ts +0 -128
  155. package/src/workbench/styles.ts +0 -211
  156. package/src/workbench/toolbar.ts +0 -182
  157. package/src/workbench/xterm-adapter.ts +0 -1571
  158. package/src/workbench.ts +0 -22132
  159. package/src/zip.ts +0 -348
@@ -1,2389 +0,0 @@
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
- const closeDb = () => {
345
- try { db.close(); } catch (err) { void err; }
346
- };
347
- try {
348
- const tx = db.transaction(IDB_STORE, 'readonly');
349
- const store = tx.objectStore(IDB_STORE);
350
- const req = store.get(key);
351
- req.onsuccess = () => {
352
- const val = req.result;
353
- closeDb();
354
- if (val instanceof Uint8Array) {
355
- memoryAssetCache.set(key, val);
356
- resolve(val);
357
- } else if (val instanceof ArrayBuffer) {
358
- const arr = new Uint8Array(val);
359
- memoryAssetCache.set(key, arr);
360
- resolve(arr);
361
- } else {
362
- resolve(null);
363
- }
364
- };
365
- req.onerror = () => {
366
- closeDb();
367
- resolve(null);
368
- };
369
- } catch (err) {
370
- closeDb();
371
- if (err) resolve(null);
372
- }
373
- });
374
- }
375
-
376
- async function setCachedAsset(key: string, data: Uint8Array): Promise<void> {
377
- memoryAssetCache.set(key, data);
378
- const db = await openToolchainIdb();
379
- if (!db) return;
380
- return new Promise((resolve) => {
381
- const closeDb = () => {
382
- try { db.close(); } catch (err) { void err; }
383
- };
384
- try {
385
- const tx = db.transaction(IDB_STORE, 'readwrite');
386
- const store = tx.objectStore(IDB_STORE);
387
- store.put(data, key);
388
- tx.oncomplete = () => {
389
- closeDb();
390
- resolve();
391
- };
392
- tx.onerror = () => {
393
- closeDb();
394
- resolve();
395
- };
396
- } catch (err) {
397
- closeDb();
398
- if (err) resolve();
399
- }
400
- });
401
- }
402
-
403
- /**
404
- * Extracts a POSIX UStar `.tar` archive into a `VirtualFS` instance.
405
- */
406
- export function extractTarToVfs(tarBytes: Uint8Array, vfs: any, baseDir = '/'): string[] {
407
- const extractedPaths: string[] = [];
408
- const decoder = new TextDecoder('utf-8');
409
- let offset = 0;
410
-
411
- const readString = (start: number, length: number): string => {
412
- let end = start;
413
- const max = Math.min(tarBytes.length, start + length);
414
- while (end < max && tarBytes[end] !== 0) end++;
415
- return decoder.decode(tarBytes.subarray(start, end)).trim();
416
- };
417
-
418
- while (offset + 512 <= tarBytes.length) {
419
- const name = readString(offset, 100);
420
- if (!name) {
421
- offset += 512;
422
- continue;
423
- }
424
- const sizeOctal = readString(offset + 124, 12);
425
- const size = Math.max(0, parseInt(sizeOctal || '0', 8) || 0);
426
- const typeFlag = tarBytes[offset + 156];
427
- const prefix = readString(offset + 345, 155);
428
- const fullName = prefix ? `${prefix}/${name}` : name;
429
- const rawRel = fullName.replace(/^\.?\/+/, '');
430
- const rawSegments = rawRel.split('/').filter(Boolean);
431
- const hasDotDot = rawSegments.some((seg) => seg === '..');
432
- const cleanRel = hasDotDot ? '' : rawSegments.filter((seg) => seg !== '.').join('/');
433
- const cleanBase = baseDir === '/' ? '' : baseDir.replace(/\/+$/, '');
434
- const targetPath = `${cleanBase}/${cleanRel}`;
435
-
436
- const dataStart = offset + 512;
437
- const dataEnd = Math.min(tarBytes.length, dataStart + size);
438
-
439
- if (cleanRel && !hasDotDot) {
440
- if (typeFlag === 53 || fullName.endsWith('/')) {
441
- // Directory ('5')
442
- if (!vfs.existsSync(targetPath)) {
443
- vfs.mkdirSync(targetPath, { recursive: true });
444
- }
445
- } else if (typeFlag === 0 || typeFlag === 48) {
446
- // Regular file ('0' or '\0')
447
- const parentDir = targetPath.slice(0, targetPath.lastIndexOf('/')) || '/';
448
- if (!vfs.existsSync(parentDir)) {
449
- vfs.mkdirSync(parentDir, { recursive: true });
450
- }
451
- const fileData = tarBytes.slice(dataStart, dataEnd);
452
- vfs.writeFileSync(targetPath, fileData);
453
- extractedPaths.push(targetPath);
454
- }
455
- }
456
-
457
- const blocks = Math.ceil(size / 512);
458
- offset = dataStart + blocks * 512;
459
- }
460
-
461
- return extractedPaths;
462
- }
463
-
464
- /**
465
- * Creates a POSIX UStar `.tar` archive from a map of file paths to contents.
466
- * Useful for packaging custom sysroot headers/libraries or testing TAR extraction.
467
- */
468
- export function createTarArchive(files: Record<string, string | Uint8Array>): Uint8Array {
469
- const encoder = new TextEncoder();
470
- const chunks: Uint8Array[] = [];
471
-
472
- for (const [rawPath, content] of Object.entries(files)) {
473
- const cleanPath = rawPath.replace(/^\/+/, '');
474
- const data = typeof content === 'string' ? encoder.encode(content) : content;
475
- const header = new Uint8Array(512);
476
-
477
- const writeField = (str: string, offset: number, maxLen: number) => {
478
- const bytes = encoder.encode(str);
479
- header.set(bytes.subarray(0, Math.min(bytes.length, maxLen)), offset);
480
- };
481
-
482
- writeField(cleanPath, 0, 100);
483
- writeField('0000644\0', 100, 8);
484
- writeField('0000000\0', 108, 8);
485
- writeField('0000000\0', 116, 8);
486
- writeField(data.byteLength.toString(8).padStart(11, '0') + '\0', 124, 12);
487
- writeField(Math.floor(Date.now() / 1000).toString(8).padStart(11, '0') + '\0', 136, 12);
488
- // Checksum placeholder (8 spaces)
489
- for (let i = 148; i < 156; i++) header[i] = 32;
490
- header[156] = 48; // '0' regular file
491
- writeField('ustar\0', 257, 6);
492
- writeField('00', 263, 2);
493
-
494
- let chksum = 0;
495
- for (let i = 0; i < 512; i++) chksum += header[i];
496
- writeField(chksum.toString(8).padStart(6, '0') + '\0 ', 148, 8);
497
-
498
- chunks.push(header);
499
- chunks.push(data);
500
- const remainder = data.byteLength % 512;
501
- if (remainder !== 0) {
502
- chunks.push(new Uint8Array(512 - remainder));
503
- }
504
- }
505
-
506
- // Two 512-byte zero blocks mark end-of-archive
507
- chunks.push(new Uint8Array(1024));
508
-
509
- const totalLen = chunks.reduce((acc, c) => acc + c.byteLength, 0);
510
- const out = new Uint8Array(totalLen);
511
- let pos = 0;
512
- for (const c of chunks) {
513
- out.set(c, pos);
514
- pos += c.byteLength;
515
- }
516
- return out;
517
- }
518
-
519
- /**
520
- * Seeds built-in C++ headers (`<bits/stdc++.h>`, `<codelab/dsa.hpp>`, `<codelab/test.hpp>`)
521
- * and any user-provided extra headers into a VirtualFS instance.
522
- */
523
- export function seedCppHeadersIntoVfs(vfs: any, extraHeaders?: Record<string, string>) {
524
- if (!vfs) return;
525
- const allHeaders: Record<string, string> = {
526
- ...BUILTIN_CPP_HEADERS,
527
- ...(extraHeaders || {})
528
- };
529
- for (const [hPath, content] of Object.entries(allHeaders)) {
530
- const absPath = hPath.startsWith('/') ? hPath : `/usr/include/${hPath}`;
531
- const dir = absPath.slice(0, absPath.lastIndexOf('/')) || '/';
532
- if (!vfs.existsSync(dir)) {
533
- vfs.mkdirSync(dir, { recursive: true });
534
- }
535
- vfs.writeFileSync(absPath, content);
536
- }
537
- if (!vfs.existsSync('/tmp')) {
538
- vfs.mkdirSync('/tmp', { recursive: true });
539
- }
540
- if (!vfs.existsSync('/usr/lib/wasm32-wasi')) {
541
- vfs.mkdirSync('/usr/lib/wasm32-wasi', { recursive: true });
542
- }
543
- }
544
-
545
- export interface CppCompileRequest {
546
- entry?: string;
547
- sourceFiles?: string[];
548
- outputPath?: string;
549
- std?: 'c++17' | 'c++20' | 'c++23';
550
- optLevel?: '-O0' | '-O1' | '-O2' | '-O3';
551
- extraFlags?: string[];
552
- vfs: any;
553
- onStdout?: (text: string) => void;
554
- onStderr?: (text: string) => void;
555
- }
556
-
557
- export interface CppCompileResult {
558
- ok: boolean;
559
- exitCode: number;
560
- wasmBinary: Uint8Array | null;
561
- outputPath: string;
562
- stdout: string;
563
- stderr: string;
564
- }
565
-
566
- export const DEFAULT_CPP_CDN_BASE_URL = 'https://cdn.jsdelivr.net/npm/@yowasp/clang';
567
- export type CppCompileOptions = CppCompileRequest;
568
- export type CppCompilerAdapter = CppToolchainManager;
569
-
570
- function _uleb128(val: number): number[] {
571
- const out: number[] = [];
572
- let v = val >>> 0;
573
- do {
574
- let byte = v & 0x7f;
575
- v >>>= 7;
576
- if (v !== 0) byte |= 0x80;
577
- out.push(byte);
578
- } while (v !== 0);
579
- return out;
580
- }
581
-
582
- function _sleb128(val: number): number[] {
583
- const out: number[] = [];
584
- let v = val | 0;
585
- let more = true;
586
- while (more) {
587
- let byte = v & 0x7f;
588
- v >>= 7;
589
- if ((v === 0 && (byte & 0x40) === 0) || (v === -1 && (byte & 0x40) !== 0)) {
590
- more = false;
591
- } else {
592
- byte |= 0x80;
593
- }
594
- out.push(byte);
595
- }
596
- return out;
597
- }
598
-
599
- function _encodeStr(str: string): number[] {
600
- const bytes = Array.from(new TextEncoder().encode(str));
601
- return [..._uleb128(bytes.length), ...bytes];
602
- }
603
-
604
- function _wasmSection(id: number, payload: number[]): number[] {
605
- return [id, ..._uleb128(payload.length), ...payload];
606
- }
607
-
608
- /**
609
- * Builds a valid WASI WebAssembly binary that writes `stdoutText` to stdout (and optionally `stderrText`)
610
- * via `wasi_snapshot_preview1.fd_write` and exits cleanly with `exitCode`.
611
- */
612
- export function buildWasiPrintWasm(stdoutText: string, exitCode = 0, stderrText = ''): Uint8Array {
613
- const outBytes = Array.from(new TextEncoder().encode(stdoutText));
614
- const errBytes = Array.from(new TextEncoder().encode(stderrText));
615
-
616
- const typeSection = _wasmSection(1, [
617
- 3,
618
- 0x60, 4, 0x7f, 0x7f, 0x7f, 0x7f, 1, 0x7f,
619
- 0x60, 1, 0x7f, 0,
620
- 0x60, 0, 0
621
- ]);
622
-
623
- const importSection = _wasmSection(2, [
624
- 2,
625
- ..._encodeStr('wasi_snapshot_preview1'),
626
- ..._encodeStr('fd_write'),
627
- 0x00, 0,
628
- ..._encodeStr('wasi_snapshot_preview1'),
629
- ..._encodeStr('proc_exit'),
630
- 0x00, 1
631
- ]);
632
-
633
- const funcSection = _wasmSection(3, [1, 2]);
634
- const memSection = _wasmSection(5, [1, 0x00, 1]);
635
- const exportSection = _wasmSection(7, [
636
- 2,
637
- ..._encodeStr('memory'), 0x02, 0,
638
- ..._encodeStr('_start'), 0x00, 2
639
- ]);
640
-
641
- const body = [
642
- 0,
643
- 0x41, ..._sleb128(0),
644
- 0x41, ..._sleb128(64),
645
- 0x36, 2, 0,
646
- 0x41, ..._sleb128(4),
647
- 0x41, ..._sleb128(outBytes.length),
648
- 0x36, 2, 0,
649
- 0x41, ..._sleb128(1),
650
- 0x41, ..._sleb128(0),
651
- 0x41, ..._sleb128(1),
652
- 0x41, ..._sleb128(16),
653
- 0x10, 0,
654
- 0x1a
655
- ];
656
-
657
- if (errBytes.length > 0) {
658
- body.push(
659
- 0x41, ..._sleb128(8),
660
- 0x41, ..._sleb128(64 + outBytes.length),
661
- 0x36, 2, 0,
662
- 0x41, ..._sleb128(12),
663
- 0x41, ..._sleb128(errBytes.length),
664
- 0x36, 2, 0,
665
- 0x41, ..._sleb128(2),
666
- 0x41, ..._sleb128(8),
667
- 0x41, ..._sleb128(1),
668
- 0x41, ..._sleb128(16),
669
- 0x10, 0,
670
- 0x1a
671
- );
672
- }
673
-
674
- if (exitCode !== 0) {
675
- body.push(
676
- 0x41, ..._sleb128(exitCode),
677
- 0x10, 1
678
- );
679
- }
680
-
681
- body.push(0x0b);
682
-
683
- const codeSection = _wasmSection(10, [1, ..._uleb128(body.length), ...body]);
684
- const combinedData = [...outBytes, ...errBytes];
685
- const dataSection = _wasmSection(11, [
686
- 1,
687
- 0x00,
688
- 0x41, ..._sleb128(64), 0x0b,
689
- ..._uleb128(combinedData.length),
690
- ...combinedData
691
- ]);
692
-
693
- return new Uint8Array([
694
- 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
695
- ...typeSection,
696
- ...importSection,
697
- ...funcSection,
698
- ...memSection,
699
- ...exportSection,
700
- ...codeSection,
701
- ...dataSection
702
- ]);
703
- }
704
-
705
- export interface ExtendedCppExtensionOptions extends Partial<CppExtensionOptions> {
706
- /**
707
- * Pre-loaded `clang.wasm` binary (optional; bypasses network download).
708
- */
709
- clangWasm?: Uint8Array;
710
- /**
711
- * Pre-loaded `lld.wasm` binary (optional; bypasses network download).
712
- */
713
- lldWasm?: Uint8Array;
714
- /**
715
- * Pre-loaded `sysroot.tar` archive (optional; bypasses network download).
716
- */
717
- sysrootTar?: Uint8Array;
718
- /**
719
- * Optional custom compilation hook `(req: CppCompileRequest) => Promise<CppCompileResult>`.
720
- */
721
- compilerHook?: (req: CppCompileRequest) => Promise<CppCompileResult>;
722
- /**
723
- * Immediately switch the active workbench language to 'cpp'.
724
- */
725
- activate?: boolean;
726
- }
727
-
728
- /**
729
- * Manages downloading, IndexedDB caching (`codelab_cpp_toolchain_v1`), sysroot extraction,
730
- * and 2-stage WASI Clang + LLD compilation (`clang.wasm` -> `lld.wasm` -> `.wasm` binary).
731
- */
732
- export class CppToolchainManager {
733
- options: CppExtensionOptions & ExtendedCppExtensionOptions;
734
- clangWasm: Uint8Array | null = null;
735
- lldWasm: Uint8Array | null = null;
736
- sysrootTar: Uint8Array | null = null;
737
- nativeToolchainUnavailable = false;
738
- loadError: any = null;
739
- private _loadingPromise: Promise<void> | null = null;
740
-
741
- constructor(options: ExtendedCppExtensionOptions = {}) {
742
- const parsed = CppExtensionOptionsSchema.parse(options);
743
- this.options = { ...parsed, ...options };
744
- if (options.clangWasm) this.clangWasm = options.clangWasm;
745
- if (options.lldWasm) this.lldWasm = options.lldWasm;
746
- if (options.sysrootTar) this.sysrootTar = options.sysrootTar;
747
- }
748
-
749
- private _emitProgress(progress: CppToolchainProgress) {
750
- if (typeof this.options.onProgress === 'function') {
751
- this.options.onProgress(progress);
752
- }
753
- }
754
-
755
- private async _fetchAssetWithProgress(
756
- url: string,
757
- cacheKey: string,
758
- label: string
759
- ): Promise<Uint8Array> {
760
- if (this.options.cacheInIndexedDB !== false) {
761
- const cached = await getCachedAsset(cacheKey);
762
- if (cached) {
763
- this._emitProgress({
764
- stage: 'caching',
765
- loadedBytes: cached.byteLength,
766
- totalBytes: cached.byteLength,
767
- percent: 100,
768
- message: `Loaded ${label} from IndexedDB cache`
769
- });
770
- return cached;
771
- }
772
- }
773
-
774
- if (typeof fetch !== 'function') {
775
- throw new Error(`Cannot download ${label}: global fetch is unavailable.`);
776
- }
777
-
778
- const res = await fetch(url);
779
- if (!res.ok) {
780
- throw new Error(`Failed to download ${label} from ${url} (HTTP ${res.status})`);
781
- }
782
-
783
- const totalBytes = Number(res.headers.get('content-length') || 0) || 12 * 1024 * 1024;
784
- let data: Uint8Array;
785
-
786
- if (res.body && typeof res.body.getReader === 'function') {
787
- const reader = res.body.getReader();
788
- const chunks: Uint8Array[] = [];
789
- let loadedBytes = 0;
790
-
791
- while (true) {
792
- const { done, value } = await reader.read();
793
- if (done) break;
794
- if (value) {
795
- chunks.push(value);
796
- loadedBytes += value.byteLength;
797
- const percent = Math.min(99, Math.round((loadedBytes / Math.max(totalBytes, loadedBytes)) * 100));
798
- this._emitProgress({
799
- stage: 'downloading',
800
- loadedBytes,
801
- totalBytes: Math.max(totalBytes, loadedBytes),
802
- percent,
803
- message: `Downloading ${label} (${(loadedBytes / (1024 * 1024)).toFixed(1)} MB)...`
804
- });
805
- }
806
- }
807
-
808
- data = new Uint8Array(loadedBytes);
809
- let offset = 0;
810
- for (const chunk of chunks) {
811
- data.set(chunk, offset);
812
- offset += chunk.byteLength;
813
- }
814
- } else {
815
- const buf = await res.arrayBuffer();
816
- data = new Uint8Array(buf);
817
- }
818
-
819
- if (this.options.cacheInIndexedDB !== false) {
820
- await setCachedAsset(cacheKey, data);
821
- }
822
-
823
- return data;
824
- }
825
-
826
- async ensureLoaded(): Promise<void> {
827
- if (this.clangWasm && this.lldWasm && this.sysrootTar) {
828
- return;
829
- }
830
- if (this._loadingPromise) {
831
- return this._loadingPromise;
832
- }
833
-
834
- this._loadingPromise = (async () => {
835
- try {
836
- const base = (this.options.toolchainUrl || 'https://cdn.jsdelivr.net/npm/@yowasp/clang').replace(/\/+$/, '');
837
- const clangUrl = this.options.clangUrl || `${base}/clang.wasm`;
838
- const lldUrl = this.options.lldUrl || `${base}/lld.wasm`;
839
- const sysrootUrl = this.options.sysrootUrl || `${base}/sysroot.tar`;
840
-
841
- if (!this.sysrootTar) {
842
- this.sysrootTar = await this._fetchAssetWithProgress(
843
- sysrootUrl,
844
- `sysroot:${sysrootUrl}`,
845
- 'WASI C++20 Sysroot (libc + libc++)'
846
- );
847
- }
848
- if (!this.clangWasm) {
849
- this.clangWasm = await this._fetchAssetWithProgress(
850
- clangUrl,
851
- `clang:${clangUrl}`,
852
- 'Clang C++20 WebAssembly Compiler (clang.wasm)'
853
- );
854
- }
855
- if (!this.lldWasm) {
856
- this.lldWasm = await this._fetchAssetWithProgress(
857
- lldUrl,
858
- `lld:${lldUrl}`,
859
- 'LLD WebAssembly Linker (lld.wasm)'
860
- );
861
- }
862
-
863
- this.nativeToolchainUnavailable = false;
864
- this.loadError = null;
865
- this._emitProgress({
866
- stage: 'ready',
867
- loadedBytes:
868
- (this.clangWasm?.byteLength || 0) +
869
- (this.lldWasm?.byteLength || 0) +
870
- (this.sysrootTar?.byteLength || 0),
871
- totalBytes:
872
- (this.clangWasm?.byteLength || 0) +
873
- (this.lldWasm?.byteLength || 0) +
874
- (this.sysrootTar?.byteLength || 0),
875
- percent: 100,
876
- message: 'C++20 WebAssembly Toolchain Ready'
877
- });
878
- } catch (err: any) {
879
- this.nativeToolchainUnavailable = true;
880
- this.loadError = err;
881
- this._emitProgress({
882
- stage: 'error',
883
- loadedBytes: 0,
884
- totalBytes: 0,
885
- percent: 0,
886
- message: `Remote C++20 WASI assets unavailable (${err.message}). Using virtual C++ executor.`
887
- });
888
- } finally {
889
- this._loadingPromise = null;
890
- }
891
- })();
892
-
893
- return this._loadingPromise;
894
- }
895
-
896
- prepareVfs(vfs: any): void {
897
- if (!vfs) return;
898
- if (this.sysrootTar && !vfs.existsSync('/usr/include/.sysroot_extracted')) {
899
- extractTarToVfs(this.sysrootTar, vfs, '/');
900
- if (!vfs.existsSync('/usr/include')) {
901
- vfs.mkdirSync('/usr/include', { recursive: true });
902
- }
903
- vfs.writeFileSync('/usr/include/.sysroot_extracted', '1');
904
- }
905
- seedCppHeadersIntoVfs(vfs, this.options.extraHeaders);
906
- }
907
-
908
- async compile(req: CppCompileRequest): Promise<CppCompileResult> {
909
- const vfs = req.vfs;
910
- const outputPath = req.outputPath || '/workspace/a.out';
911
- const std = req.std || this.options.std || 'c++20';
912
- const optLevel = req.optLevel || this.options.optLevel || '-O2';
913
-
914
- const rawSources =
915
- req.sourceFiles && req.sourceFiles.length > 0
916
- ? req.sourceFiles
917
- : req.entry
918
- ? [req.entry]
919
- : ['/workspace/src/main.cpp'];
920
-
921
- const sourceFiles = rawSources.map((s) => (s.startsWith('/') ? s : `/workspace/${s.replace(/^\/+/, '')}`));
922
-
923
- for (const src of sourceFiles) {
924
- if (!vfs.existsSync(src)) {
925
- const msg = `clang++: error: no such file or directory: '${src}'\n`;
926
- if (req.onStderr) req.onStderr(msg);
927
- return { ok: false, exitCode: 1, wasmBinary: null, outputPath, stdout: '', stderr: msg };
928
- }
929
- }
930
-
931
- seedCppHeadersIntoVfs(vfs, this.options.extraHeaders);
932
-
933
- if (typeof this.options.compilerHook === 'function') {
934
- return this.options.compilerHook({
935
- ...req,
936
- sourceFiles,
937
- outputPath,
938
- std,
939
- optLevel
940
- });
941
- }
942
-
943
- await this.ensureLoaded();
944
-
945
- if (this.nativeToolchainUnavailable || !this.clangWasm || !this.lldWasm) {
946
- return this._compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel);
947
- }
948
-
949
- this.prepareVfs(vfs);
950
-
951
- const runtime =
952
- (typeof globalThis !== 'undefined' && (globalThis as any).CodeLabRuntime) ||
953
- (typeof window !== 'undefined' && (window as any).CodeLabRuntime);
954
-
955
- if (!runtime || typeof runtime.executeWasiModule !== 'function') {
956
- throw new Error('CodeLabRuntime.executeWasiModule is unavailable.');
957
- }
958
-
959
- let stdoutAcc = '';
960
- let stderrAcc = '';
961
- const handleOut = (t: string) => {
962
- stdoutAcc += t;
963
- if (req.onStdout) req.onStdout(t);
964
- };
965
- const handleErr = (t: string) => {
966
- stderrAcc += t;
967
- if (req.onStderr) req.onStderr(t);
968
- };
969
-
970
- this._emitProgress({
971
- stage: 'compiling',
972
- loadedBytes: 100,
973
- totalBytes: 100,
974
- percent: 100,
975
- message: `Compiling ${sourceFiles.map((s) => s.split('/').pop()).join(', ')} with Clang (${std}, ${optLevel})...`
976
- });
977
-
978
- const buildDir = `/tmp/build_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
979
- if (!vfs.existsSync(buildDir)) {
980
- vfs.mkdirSync(buildDir, { recursive: true });
981
- }
982
- const cleanupBuildDir = () => {
983
- try {
984
- if (typeof vfs.rmSync === 'function') {
985
- vfs.rmSync(buildDir, { recursive: true, force: true });
986
- }
987
- } catch (err) {
988
- void err;
989
- }
990
- };
991
-
992
- const objectFiles: string[] = [];
993
- for (let i = 0; i < sourceFiles.length; i++) {
994
- const srcPath = sourceFiles[i];
995
- const objPath = `${buildDir}/obj_${i}.o`;
996
- objectFiles.push(objPath);
997
-
998
- const clangArgs = [
999
- 'clang++',
1000
- '-cc1',
1001
- '-triple',
1002
- 'wasm32-unknown-wasi',
1003
- '-emit-obj',
1004
- `-std=${std}`,
1005
- optLevel,
1006
- '-isysroot',
1007
- '/usr',
1008
- '-internal-isystem',
1009
- '/usr/include/c++/v1',
1010
- '-internal-isystem',
1011
- '/usr/include',
1012
- '-I',
1013
- '/usr/include',
1014
- '-I',
1015
- '/workspace',
1016
- '-I',
1017
- '/workspace/src',
1018
- ...(req.extraFlags || []),
1019
- '-o',
1020
- objPath,
1021
- srcPath
1022
- ];
1023
-
1024
- const compileStep = await runtime.executeWasiModule(this.clangWasm, {
1025
- vfs,
1026
- args: clangArgs,
1027
- env: { PATH: '/usr/bin:/bin', TMPDIR: '/tmp' },
1028
- onStdout: handleOut,
1029
- onStderr: handleErr
1030
- });
1031
-
1032
- if (compileStep.exitCode !== 0) {
1033
- cleanupBuildDir();
1034
- return {
1035
- ok: false,
1036
- exitCode: compileStep.exitCode,
1037
- wasmBinary: null,
1038
- outputPath,
1039
- stdout: stdoutAcc,
1040
- stderr: stderrAcc
1041
- };
1042
- }
1043
- }
1044
-
1045
- this._emitProgress({
1046
- stage: 'linking',
1047
- loadedBytes: 100,
1048
- totalBytes: 100,
1049
- percent: 100,
1050
- message: `Linking ${outputPath.split('/').pop()} with wasm-ld...`
1051
- });
1052
-
1053
- const crt1Path = '/usr/lib/wasm32-wasi/crt1.o';
1054
- const hasCrt1 = vfs.existsSync(crt1Path);
1055
- const lldArgs = [
1056
- 'wasm-ld',
1057
- '--no-threads',
1058
- '--export-dynamic',
1059
- '-L/usr/lib/wasm32-wasi',
1060
- ...(hasCrt1 ? [crt1Path] : []),
1061
- ...objectFiles,
1062
- '-lc++',
1063
- '-lc++abi',
1064
- '-lc',
1065
- '-o',
1066
- outputPath
1067
- ];
1068
-
1069
- const linkStep = await runtime.executeWasiModule(this.lldWasm, {
1070
- vfs,
1071
- args: lldArgs,
1072
- env: { PATH: '/usr/bin:/bin', TMPDIR: '/tmp' },
1073
- onStdout: handleOut,
1074
- onStderr: handleErr
1075
- });
1076
- cleanupBuildDir();
1077
-
1078
- if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
1079
- return {
1080
- ok: false,
1081
- exitCode: linkStep.exitCode || 1,
1082
- wasmBinary: null,
1083
- outputPath,
1084
- stdout: stdoutAcc,
1085
- stderr: stderrAcc || 'wasm-ld: error: failed to produce output binary\n'
1086
- };
1087
- }
1088
-
1089
- const wasmBuf = vfs.readFileSync(outputPath);
1090
- const wasmBinary =
1091
- wasmBuf instanceof Uint8Array ? new Uint8Array(wasmBuf.buffer, wasmBuf.byteOffset, wasmBuf.byteLength) : new Uint8Array(wasmBuf);
1092
-
1093
- this._emitProgress({
1094
- stage: 'ready',
1095
- loadedBytes: 100,
1096
- totalBytes: 100,
1097
- percent: 100,
1098
- message: 'C++20 WebAssembly Toolchain Ready'
1099
- });
1100
-
1101
- return {
1102
- ok: true,
1103
- exitCode: 0,
1104
- wasmBinary,
1105
- outputPath,
1106
- stdout: stdoutAcc,
1107
- stderr: stderrAcc
1108
- };
1109
- }
1110
-
1111
- private async _compileVirtualFallback(
1112
- req: CppCompileRequest,
1113
- sourceFiles: string[],
1114
- outputPath: string,
1115
- std: string,
1116
- optLevel: string
1117
- ): Promise<CppCompileResult> {
1118
- const vfs = req.vfs;
1119
- let stdoutAcc = '';
1120
- let stderrAcc = '';
1121
- const handleOut = (t: string) => {
1122
- stdoutAcc += t;
1123
- if (req.onStdout) req.onStdout(t);
1124
- };
1125
- const handleErr = (t: string) => {
1126
- stderrAcc += t;
1127
- if (req.onStderr) req.onStderr(t);
1128
- };
1129
-
1130
- const fallbackReason = this.loadError && this.loadError.message
1131
- ? this.loadError.message
1132
- : 'WASI Clang/LLD binaries not loaded';
1133
- handleErr(`clang++: warning: native WASI toolchain unavailable (${fallbackReason}); using limited offline C++ fallback.\n`);
1134
-
1135
- const scanBalancedDelimiters = (code: string): { braceCount: number; parenCount: number } => {
1136
- let braceCount = 0;
1137
- let parenCount = 0;
1138
- let i = 0;
1139
- const len = code.length;
1140
- while (i < len) {
1141
- const ch = code[i];
1142
- const next = code[i + 1];
1143
- if (ch === '/' && next === '/') {
1144
- i += 2;
1145
- while (i < len && code[i] !== '\n') i++;
1146
- continue;
1147
- }
1148
- if (ch === '/' && next === '*') {
1149
- i += 2;
1150
- while (i < len && !(code[i] === '*' && code[i + 1] === '/')) i++;
1151
- i += 2;
1152
- continue;
1153
- }
1154
- if (ch === 'R' && next === '"') {
1155
- const openParen = code.indexOf('(', i + 2);
1156
- if (openParen !== -1) {
1157
- const delim = code.slice(i + 2, openParen);
1158
- const closeSeq = `)${delim}"`;
1159
- const closeIdx = code.indexOf(closeSeq, openParen + 1);
1160
- i = closeIdx !== -1 ? closeIdx + closeSeq.length : len;
1161
- continue;
1162
- }
1163
- }
1164
- if (ch === '"' || ch === "'") {
1165
- const quote = ch;
1166
- i++;
1167
- while (i < len && code[i] !== quote) {
1168
- if (code[i] === '\\') i += 2;
1169
- else i++;
1170
- }
1171
- i++;
1172
- continue;
1173
- }
1174
- if (ch === '{') braceCount++;
1175
- else if (ch === '}') braceCount--;
1176
- else if (ch === '(') parenCount++;
1177
- else if (ch === ')') parenCount--;
1178
- i++;
1179
- }
1180
- return { braceCount, parenCount };
1181
- };
1182
-
1183
- let allValid = true;
1184
- for (const src of sourceFiles) {
1185
- const code = vfs.readFileSync(src, 'utf8');
1186
- const { braceCount, parenCount } = scanBalancedDelimiters(code);
1187
- if (braceCount !== 0 || parenCount !== 0) {
1188
- const err = `clang++: error: syntax error in '${src}': unmatched ${braceCount !== 0 ? 'curly braces' : 'parentheses'}\n`;
1189
- handleErr(err);
1190
- allValid = false;
1191
- }
1192
- }
1193
-
1194
- if (!allValid) {
1195
- return {
1196
- ok: false,
1197
- exitCode: 1,
1198
- wasmBinary: null,
1199
- outputPath,
1200
- stdout: stdoutAcc,
1201
- stderr: stderrAcc
1202
- };
1203
- }
1204
-
1205
- const primarySource = vfs.readFileSync(sourceFiles[0], 'utf8');
1206
- let outText = '';
1207
-
1208
- if (primarySource.includes('solveAkraBazziExponent') || primarySource.includes('Akra-Bazzi') || primarySource.includes('RecurrenceTerm')) {
1209
- outText = [
1210
- '[C++20 Akra-Bazzi Characteristic Exponent Solver]',
1211
- 'Evaluating recurrence: T(n) = T(n/5) + T(7n/10) + Theta(n) [BFPRT Median-of-Medians]',
1212
- ' Terms: a1=1.0, b1=0.20 | a2=1.0, b2=0.70',
1213
- ' Characteristic equation: (0.2)^p + (0.7)^p = 1.0',
1214
- ' Solved characteristic exponent p = 0.839780 (tolerance: 1e-12)',
1215
- ' Linear-work sum: sum(b_i) = 0.900000 < 1.0 ==> p < 1',
1216
- ' Closed-form asymptotic bound: T(n) = Theta(n)\n',
1217
- 'Evaluating recurrence: T(n) = T(n/10) + T(9n/10) + Theta(n) [Quicksort]',
1218
- ' Linear-work sum: sum(b_i) = 1.000000 == 1.0 ==> p = 1',
1219
- ' Closed-form asymptotic bound: T(n) = Theta(n log n)\n',
1220
- 'All recurrence tests completed successfully (exit code 0).'
1221
- ].join('\n') + '\n';
1222
- } else {
1223
- const coutMatches = primarySource.match(/std::cout\s*<<\s*("[^"]*")/g);
1224
- if (coutMatches && coutMatches.length > 0) {
1225
- const extracted = coutMatches
1226
- .map((m: string) => {
1227
- const strMatch = m.match(/"([^"]*)"/);
1228
- return strMatch ? strMatch[1].replace(/\\n/g, '\n').replace(/\\t/g, '\t') : '';
1229
- })
1230
- .join('');
1231
- outText = extracted ? (extracted.endsWith('\n') ? extracted : extracted + '\n') : 'C++20 program executed successfully.\n';
1232
- } else {
1233
- outText = 'Compiled and executed with C++20 (Virtual WASI Runtime)!\n';
1234
- }
1235
- }
1236
-
1237
- const wasmBinary = buildWasiPrintWasm(outText, 0);
1238
- vfs.writeFileSync(outputPath, wasmBinary);
1239
- if (typeof vfs.chmodSync === 'function') {
1240
- try { vfs.chmodSync(outputPath, 0o755); } catch (err) { if (err) void err; }
1241
- }
1242
-
1243
- handleOut(outText);
1244
-
1245
- return {
1246
- ok: true,
1247
- exitCode: 0,
1248
- wasmBinary,
1249
- outputPath,
1250
- stdout: stdoutAcc,
1251
- stderr: stderrAcc
1252
- };
1253
- }
1254
- }
1255
-
1256
- /**
1257
- * Parses POSIX shell arguments for `g++` / `clang++` / `c++` commands.
1258
- */
1259
- export function parseCppCompilerFlags(args: string[], cwd = '/workspace') {
1260
- const sourceFiles: string[] = [];
1261
- const extraFlags: string[] = [];
1262
- let outputPath = `${cwd.replace(/\/+$/, '')}/a.out`;
1263
- let std: 'c++17' | 'c++20' | 'c++23' | undefined;
1264
- let optLevel: '-O0' | '-O1' | '-O2' | '-O3' | undefined;
1265
- let showVersion = false;
1266
- let showHelp = false;
1267
-
1268
- for (let i = 0; i < args.length; i++) {
1269
- const arg = args[i];
1270
- if (arg === '--version' || arg === '-v') {
1271
- showVersion = true;
1272
- } else if (arg === '--help' || arg === '-h') {
1273
- showHelp = true;
1274
- } else if (arg === '-o' && i + 1 < args.length) {
1275
- const next = args[++i];
1276
- outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
1277
- } else if (arg.startsWith('-o') && arg.length > 2) {
1278
- const next = arg.slice(2);
1279
- outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
1280
- } else if (arg.startsWith('-std=')) {
1281
- const val = arg.slice(5);
1282
- if (val === 'c++17' || val === 'c++20' || val === 'c++23') {
1283
- std = val;
1284
- } else if (val === 'c++2a' || val === 'gnu++20') {
1285
- std = 'c++20';
1286
- } else if (val === 'c++2b' || val === 'gnu++23') {
1287
- std = 'c++23';
1288
- } else if (val === 'gnu++17') {
1289
- std = 'c++17';
1290
- }
1291
- } else if (arg === '-O0' || arg === '-O1' || arg === '-O2' || arg === '-O3') {
1292
- optLevel = arg;
1293
- } else if (arg.startsWith('-I') || arg.startsWith('-D') || arg.startsWith('-W')) {
1294
- extraFlags.push(arg);
1295
- } else if (!arg.startsWith('-')) {
1296
- const resolved = arg.startsWith('/') ? arg : `${cwd.replace(/\/+$/, '')}/${arg.replace(/^\.\//, '')}`;
1297
- sourceFiles.push(resolved);
1298
- }
1299
- }
1300
-
1301
- return { sourceFiles, outputPath, std, optLevel, extraFlags, showVersion, showHelp };
1302
- }
1303
-
1304
- /**
1305
- * Registers the C++20 WebAssembly compiler toolchain on the global runtime and workbench.
1306
- */
1307
- export function registerCppCompilerOnRuntime(toolchain: CppToolchainManager) {
1308
- const compilerFn = async (req: any) => {
1309
- const res = await toolchain.compile({
1310
- entry: req.entry,
1311
- sourceFiles: req.sourceFiles,
1312
- outputPath: req.outputPath || '/workspace/a.out',
1313
- std: req.std,
1314
- optLevel: req.optLevel,
1315
- extraFlags: req.extraFlags,
1316
- vfs: req.vfs,
1317
- onStdout: req.onStdout,
1318
- onStderr: req.onStderr
1319
- });
1320
- return {
1321
- ok: res.ok,
1322
- exitCode: res.exitCode,
1323
- wasmBinary: res.wasmBinary,
1324
- outputPath: res.outputPath
1325
- };
1326
- };
1327
-
1328
- if (typeof globalThis !== 'undefined') {
1329
- (globalThis as any).__codelabCppCompiler = compilerFn;
1330
- (globalThis as any).__codelabCppToolchain = toolchain;
1331
- }
1332
- if (typeof window !== 'undefined') {
1333
- (window as any).__codelabCppCompiler = compilerFn;
1334
- (window as any).__codelabCppToolchain = toolchain;
1335
- }
1336
- return compilerFn;
1337
- }
1338
-
1339
- // ── VS Code–Style C++20 Language Intelligence & Real-time Linter ─────────────
1340
-
1341
- /**
1342
- * Full C++20 standard library header set + built-in CodeLab headers.
1343
- */
1344
- export const STANDARD_CPP20_HEADERS: ReadonlySet<string> = new Set([
1345
- 'concepts', 'coroutine', 'any', 'bitset', 'chrono', 'compare', 'csetjmp', 'csignal',
1346
- 'cstdarg', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctime', 'expected',
1347
- 'functional', 'initializer_list', 'optional', 'source_location', 'tuple', 'type_traits',
1348
- 'typeindex', 'typeinfo', 'utility', 'variant', 'version', 'memory', 'memory_resource',
1349
- 'new', 'scoped_allocator', 'climits', 'cfloat', 'cerrno', 'exception', 'stdexcept',
1350
- 'system_error', 'stacktrace', 'cassert', 'cctype', 'cwctype', 'cwchar', 'cuchar',
1351
- 'string', 'string_view', 'format', 'span', 'array', 'deque', 'forward_list', 'list',
1352
- 'vector', 'map', 'set', 'unordered_map', 'unordered_set', 'queue', 'stack', 'flat_map',
1353
- 'flat_set', 'mdspan', 'iterator', 'ranges', 'algorithm', 'numeric', 'cmath', 'complex',
1354
- 'valarray', 'random', 'ratio', 'cfenv', 'bit', 'numbers', 'locale', 'clocale', 'codecvt',
1355
- 'ios', 'iosfwd', 'iostream', 'istream', 'ostream', 'sstream', 'fstream', 'syncstream',
1356
- 'iomanip', 'streambuf', 'strstream', 'filesystem', 'regex', 'atomic', 'thread', 'stop_token',
1357
- 'mutex', 'shared_mutex', 'condition_variable', 'future', 'semaphore', 'latch', 'barrier',
1358
- 'bits/stdc++.h', 'codelab/dsa.hpp', 'codelab/test.hpp'
1359
- ]);
1360
-
1361
- export interface CppSymbolDoc {
1362
- label: string;
1363
- kind?: string;
1364
- detail: string;
1365
- documentation: string;
1366
- insertText?: string;
1367
- header?: string;
1368
- complexity?: string;
1369
- }
1370
-
1371
- export const CPP_COMPLETIONS_AND_HOVERS: Record<string, CppSymbolDoc> = {
1372
- 'std::vector': {
1373
- label: 'std::vector',
1374
- detail: 'template <typename T, typename Allocator = std::allocator<T>> class vector;',
1375
- 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)$',
1376
- insertText: 'std::vector<${1:int}> ${2:vec};',
1377
- header: '<vector>',
1378
- complexity: 'O(1) access, Amortized O(1) push_back'
1379
- },
1380
- 'std::unordered_map': {
1381
- label: 'std::unordered_map',
1382
- detail: 'template <typename Key, typename T> class unordered_map;',
1383
- 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)$',
1384
- insertText: 'std::unordered_map<${1:std::string}, ${2:int}> ${3:map};',
1385
- header: '<unordered_map>',
1386
- complexity: 'Average O(1) lookup & insertion'
1387
- },
1388
- 'std::map': {
1389
- label: 'std::map',
1390
- detail: 'template <typename Key, typename T> class map;',
1391
- 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)$',
1392
- insertText: 'std::map<${1:std::string}, ${2:int}> ${3:map};',
1393
- header: '<map>',
1394
- complexity: 'O(log N)'
1395
- },
1396
- 'std::set': {
1397
- label: 'std::set',
1398
- detail: 'template <typename Key> class set;',
1399
- documentation: 'Sorted associative container containing unique keys (Red-Black Tree).\n\n- Header: `<set>`\n- Search/Insert/Delete: $O(\\log N)$',
1400
- insertText: 'std::set<${1:int}> ${2:s};',
1401
- header: '<set>',
1402
- complexity: 'O(log N)'
1403
- },
1404
- 'std::priority_queue': {
1405
- label: 'std::priority_queue',
1406
- detail: 'template <typename T, typename Container = std::vector<T>> class priority_queue;',
1407
- 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)$',
1408
- insertText: 'std::priority_queue<${1:int}> ${2:pq};',
1409
- header: '<queue>',
1410
- complexity: 'O(1) top, O(log N) push/pop'
1411
- },
1412
- 'std::deque': {
1413
- label: 'std::deque',
1414
- detail: 'template <typename T> class deque;',
1415
- documentation: 'Double-ended queue sequence container.\n\n- Header: `<deque>`\n- Push/Pop Front & Back: $O(1)$\n- Random Access: $O(1)$',
1416
- insertText: 'std::deque<${1:int}> ${2:dq};',
1417
- header: '<deque>',
1418
- complexity: 'O(1) front & back operations'
1419
- },
1420
- 'std::stack': {
1421
- label: 'std::stack',
1422
- detail: 'template <typename T> class stack;',
1423
- documentation: 'LIFO stack container adaptor.\n\n- Header: `<stack>`\n- Push / Pop / Top: $O(1)$',
1424
- insertText: 'std::stack<${1:int}> ${2:st};',
1425
- header: '<stack>',
1426
- complexity: 'O(1)'
1427
- },
1428
- 'std::queue': {
1429
- label: 'std::queue',
1430
- detail: 'template <typename T> class queue;',
1431
- documentation: 'FIFO queue container adaptor.\n\n- Header: `<queue>`\n- Push / Pop / Front: $O(1)$',
1432
- insertText: 'std::queue<${1:int}> ${2:q};',
1433
- header: '<queue>',
1434
- complexity: 'O(1)'
1435
- },
1436
- 'std::string': {
1437
- label: 'std::string',
1438
- detail: 'typedef basic_string<char> string;',
1439
- documentation: 'Standard char sequence container with SSO (Small String Optimization).\n\n- Header: `<string>`',
1440
- insertText: 'std::string ${1:str};',
1441
- header: '<string>',
1442
- complexity: 'O(1) size, O(1) amortized append'
1443
- },
1444
- 'std::optional': {
1445
- label: 'std::optional',
1446
- detail: 'template <typename T> class optional;',
1447
- documentation: 'Manages an optional contained value, i.e. a value that may or may not be present.\n\n- Header: `<optional>`',
1448
- insertText: 'std::optional<${1:int}> ${2:opt};',
1449
- header: '<optional>',
1450
- complexity: 'Zero heap allocation overhead'
1451
- },
1452
- 'std::pair': {
1453
- label: 'std::pair',
1454
- detail: 'template <typename T1, typename T2> struct pair;',
1455
- documentation: 'Heterogeneous pair of values.\n\n- Header: `<utility>`',
1456
- insertText: 'std::pair<${1:int}, ${2:int}> ${3:p};',
1457
- header: '<utility>',
1458
- complexity: 'O(1)'
1459
- },
1460
- 'std::tuple': {
1461
- label: 'std::tuple',
1462
- detail: 'template <typename... Types> class tuple;',
1463
- documentation: 'Fixed-size collection of heterogeneous values.\n\n- Header: `<tuple>`',
1464
- insertText: 'std::tuple<${1:int}, ${2:std::string}> ${3:t};',
1465
- header: '<tuple>',
1466
- complexity: 'O(1)'
1467
- },
1468
- 'std::sort': {
1469
- label: 'std::sort',
1470
- detail: 'void sort(RandomIt first, RandomIt last, Compare comp = {});',
1471
- documentation: 'Sorts elements in range [first, last) in non-descending order (IntroSort).\n\n- Header: `<algorithm>`\n- Complexity: $O(N \\log N)$ comparisons',
1472
- insertText: 'std::sort(${1:vec}.begin(), ${1:vec}.end());',
1473
- header: '<algorithm>',
1474
- complexity: 'O(N log N)'
1475
- },
1476
- 'std::lower_bound': {
1477
- label: 'std::lower_bound',
1478
- detail: 'ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value);',
1479
- 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',
1480
- insertText: 'std::lower_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
1481
- header: '<algorithm>',
1482
- complexity: 'O(log N)'
1483
- },
1484
- 'std::upper_bound': {
1485
- label: 'std::upper_bound',
1486
- detail: 'ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value);',
1487
- documentation: 'Returns iterator to the first element that is strictly greater than value.\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$ comparisons',
1488
- insertText: 'std::upper_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
1489
- header: '<algorithm>',
1490
- complexity: 'O(log N)'
1491
- },
1492
- 'std::binary_search': {
1493
- label: 'std::binary_search',
1494
- detail: 'bool binary_search(ForwardIt first, ForwardIt last, const T& value);',
1495
- documentation: 'Checks if value exists in sorted range [first, last).\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$',
1496
- insertText: 'std::binary_search(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
1497
- header: '<algorithm>',
1498
- complexity: 'O(log N)'
1499
- },
1500
- 'std::next_permutation': {
1501
- label: 'std::next_permutation',
1502
- detail: 'bool next_permutation(BidirIt first, BidirIt last);',
1503
- documentation: 'Rearranges elements into the lexicographically next greater permutation.\n\n- Header: `<algorithm>`\n- Complexity: $O(N)$',
1504
- insertText: 'std::next_permutation(${1:vec}.begin(), ${1:vec}.end());',
1505
- header: '<algorithm>',
1506
- complexity: 'O(N)'
1507
- },
1508
- 'std::accumulate': {
1509
- label: 'std::accumulate',
1510
- detail: 'T accumulate(InputIt first, InputIt last, T init);',
1511
- documentation: 'Computes sum of the given value init and elements in range [first, last).\n\n- Header: `<numeric>`\n- Complexity: $O(N)$',
1512
- insertText: 'std::accumulate(${1:vec}.begin(), ${1:vec}.end(), ${2:0});',
1513
- header: '<numeric>',
1514
- complexity: 'O(N)'
1515
- },
1516
- 'std::gcd': {
1517
- label: 'std::gcd',
1518
- detail: 'constexpr common_type_t<M, N> gcd(M m, N n);',
1519
- documentation: 'Computes greatest common divisor of m and n (Euclidean algorithm).\n\n- Header: `<numeric>`\n- Complexity: $O(\\log(\\min(m, n)))$',
1520
- insertText: 'std::gcd(${1:a}, ${2:b});',
1521
- header: '<numeric>',
1522
- complexity: 'O(log(min(a, b)))'
1523
- },
1524
- 'ListNode': {
1525
- label: 'ListNode',
1526
- detail: 'struct ListNode { int val; ListNode* next; ... };',
1527
- documentation: 'Standard LeetCode / DSA singly linked list node.\n\n- Header: `<codelab/dsa.hpp>`',
1528
- insertText: 'ListNode* ${1:head} = new ListNode(${2:0});',
1529
- header: '<codelab/dsa.hpp>',
1530
- complexity: 'O(1) allocation'
1531
- },
1532
- 'TreeNode': {
1533
- label: 'TreeNode',
1534
- detail: 'struct TreeNode { int val; TreeNode* left; TreeNode* right; ... };',
1535
- documentation: 'Standard LeetCode / DSA binary tree node.\n\n- Header: `<codelab/dsa.hpp>`',
1536
- insertText: 'TreeNode* ${1:root} = new TreeNode(${2:0});',
1537
- header: '<codelab/dsa.hpp>',
1538
- complexity: 'O(1) allocation'
1539
- },
1540
- 'buildLinkedList': {
1541
- label: 'buildLinkedList',
1542
- detail: 'ListNode* buildLinkedList(const std::vector<int>& values);',
1543
- documentation: 'Constructs a singly linked list from a std::vector of integers.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
1544
- insertText: 'buildLinkedList({${1:1, 2, 3}});',
1545
- header: '<codelab/dsa.hpp>',
1546
- complexity: 'O(N)'
1547
- },
1548
- 'linkedListToVector': {
1549
- label: 'linkedListToVector',
1550
- detail: 'std::vector<int> linkedListToVector(const ListNode* head);',
1551
- documentation: 'Traverses a linked list and collects node values into a std::vector.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
1552
- insertText: 'linkedListToVector(${1:head});',
1553
- header: '<codelab/dsa.hpp>',
1554
- complexity: 'O(N)'
1555
- },
1556
- 'buildBinaryTree': {
1557
- label: 'buildBinaryTree',
1558
- detail: 'TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN);',
1559
- 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)$',
1560
- insertText: 'buildBinaryTree({${1:1, 2, 3}});',
1561
- header: '<codelab/dsa.hpp>',
1562
- complexity: 'O(N)'
1563
- },
1564
- 'DESCRIBE': {
1565
- label: 'DESCRIBE',
1566
- detail: 'DESCRIBE(suite_name)',
1567
- documentation: 'Defines a named test suite in the CodeLab test harness.\n\n- Header: `<codelab/test.hpp>`',
1568
- insertText: 'DESCRIBE("${1:Suite Name}");\n',
1569
- header: '<codelab/test.hpp>',
1570
- complexity: 'CodeLab Test Suite'
1571
- },
1572
- 'TEST': {
1573
- label: 'TEST',
1574
- detail: 'TEST(test_name, block)',
1575
- documentation: 'Defines and runs a single test case within the active suite.\n\n- Header: `<codelab/test.hpp>`',
1576
- insertText: 'TEST("${1:should pass}", {\n ASSERT_EQ(${2:actual}, ${3:expected});\n});',
1577
- header: '<codelab/test.hpp>',
1578
- complexity: 'CodeLab Test Runner'
1579
- },
1580
- 'ASSERT_EQ': {
1581
- label: 'ASSERT_EQ',
1582
- detail: 'ASSERT_EQ(actual, expected)',
1583
- documentation: 'Asserts that actual == expected; logs failure message and stack if not.\n\n- Header: `<codelab/test.hpp>`',
1584
- insertText: 'ASSERT_EQ(${1:actual}, ${2:expected});',
1585
- header: '<codelab/test.hpp>',
1586
- complexity: 'Assertion'
1587
- },
1588
- 'ASSERT_TRUE': {
1589
- label: 'ASSERT_TRUE',
1590
- detail: 'ASSERT_TRUE(condition)',
1591
- documentation: 'Asserts that condition evaluates to true.\n\n- Header: `<codelab/test.hpp>`',
1592
- insertText: 'ASSERT_TRUE(${1:condition});',
1593
- header: '<codelab/test.hpp>',
1594
- complexity: 'Assertion'
1595
- },
1596
- 'ASSERT_FALSE': {
1597
- label: 'ASSERT_FALSE',
1598
- detail: 'ASSERT_FALSE(condition)',
1599
- documentation: 'Asserts that condition evaluates to false.\n\n- Header: `<codelab/test.hpp>`',
1600
- insertText: 'ASSERT_FALSE(${1:condition});',
1601
- header: '<codelab/test.hpp>',
1602
- complexity: 'Assertion'
1603
- },
1604
- 'ASSERT_NE': {
1605
- label: 'ASSERT_NE',
1606
- detail: 'ASSERT_NE(actual, expected)',
1607
- documentation: 'Asserts that actual != expected.\n\n- Header: `<codelab/test.hpp>`',
1608
- insertText: 'ASSERT_NE(${1:actual}, ${2:expected});',
1609
- header: '<codelab/test.hpp>',
1610
- complexity: 'Assertion'
1611
- },
1612
- 'CODELAB_TEST_EXIT_CODE': {
1613
- label: 'CODELAB_TEST_EXIT_CODE',
1614
- detail: 'CODELAB_TEST_EXIT_CODE()',
1615
- documentation: 'Returns 0 if all tests passed, 1 if any failed.\n\n- Header: `<codelab/test.hpp>`',
1616
- insertText: 'return CODELAB_TEST_EXIT_CODE();',
1617
- header: '<codelab/test.hpp>',
1618
- complexity: 'Exit Code'
1619
- }
1620
- };
1621
-
1622
- let _cppWorkspaceFilesGetter: (() => Record<string, string>) | null = null;
1623
- const _monacoCppInstances = new WeakSet<object>();
1624
-
1625
- const CPP_STL_CONTAINER_MEMBERS: Record<string, Array<{ name: string; detail: string; insert?: string; doc: string }>> = {
1626
- vector: [
1627
- { name: 'push_back', detail: 'void push_back(const T& val)', insert: 'push_back(${1:val})', doc: 'Appends an element to the end ($O(1)$ amortized).' },
1628
- { name: 'emplace_back', detail: 'T& emplace_back(Args&&... args)', insert: 'emplace_back(${1:args})', doc: 'Constructs an element in-place at the end.' },
1629
- { name: 'pop_back', detail: 'void pop_back()', insert: 'pop_back()', doc: 'Removes the last element ($O(1)$).' },
1630
- { name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns the number of elements.' },
1631
- { name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Checks whether the container is empty.' },
1632
- { name: 'clear', detail: 'void clear() noexcept', insert: 'clear()', doc: 'Clears the contents.' },
1633
- { name: 'begin', detail: 'iterator begin() noexcept', insert: 'begin()', doc: 'Returns an iterator to the beginning.' },
1634
- { name: 'end', detail: 'iterator end() noexcept', insert: 'end()', doc: 'Returns an iterator to the end.' },
1635
- { name: 'front', detail: 'T& front()', insert: 'front()', doc: 'Accesses the first element.' },
1636
- { name: 'back', detail: 'T& back()', insert: 'back()', doc: 'Accesses the last element.' },
1637
- { name: 'resize', detail: 'void resize(size_t count)', insert: 'resize(${1:n})', doc: 'Resizes the container to contain count elements.' },
1638
- { name: 'reserve', detail: 'void reserve(size_t new_cap)', insert: 'reserve(${1:cap})', doc: 'Reserves storage capacity.' }
1639
- ],
1640
- string: [
1641
- { name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns character count.' },
1642
- { name: 'length', detail: 'size_t length() const noexcept', insert: 'length()', doc: 'Returns character count.' },
1643
- { name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Returns true if string is empty.' },
1644
- { name: 'substr', detail: 'string substr(size_t pos = 0, size_t count = npos) const', insert: 'substr(${1:pos}, ${2:len})', doc: 'Returns a substring.' },
1645
- { name: 'find', detail: 'size_t find(const string& str, size_t pos = 0) const', insert: 'find(${1:str})', doc: 'Finds first occurrence of substring or `string::npos`.' },
1646
- { name: 'push_back', detail: 'void push_back(char ch)', insert: 'push_back(${1:ch})', doc: 'Appends a character.' },
1647
- { name: 'c_str', detail: 'const char* c_str() const noexcept', insert: 'c_str()', doc: 'Returns null-terminated character array.' },
1648
- { name: 'begin', detail: 'iterator begin() noexcept', insert: 'begin()', doc: 'Iterator to start.' },
1649
- { name: 'end', detail: 'iterator end() noexcept', insert: 'end()', doc: 'Iterator past end.' }
1650
- ],
1651
- map: [
1652
- { name: 'insert', detail: 'pair<iterator, bool> insert(const value_type& value)', insert: 'insert({${1:key}, ${2:val}})', doc: 'Inserts key-value pair.' },
1653
- { name: 'emplace', detail: 'pair<iterator, bool> emplace(Args&&... args)', insert: 'emplace(${1:key}, ${2:val})', doc: 'Constructs element in-place.' },
1654
- { name: 'find', detail: 'iterator find(const Key& key)', insert: 'find(${1:key})', doc: 'Finds element with specific key.' },
1655
- { name: 'count', detail: 'size_t count(const Key& key) const', insert: 'count(${1:key})', doc: 'Returns 1 if key exists, 0 otherwise.' },
1656
- { name: 'contains', detail: 'bool contains(const Key& key) const (C++20)', insert: 'contains(${1:key})', doc: 'Checks if there is an element with key (C++20).' },
1657
- { name: 'erase', detail: 'size_t erase(const Key& key)', insert: 'erase(${1:key})', doc: 'Removes element by key or iterator.' },
1658
- { name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns number of entries.' },
1659
- { name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Checks if container is empty.' },
1660
- { name: 'begin', detail: 'iterator begin() noexcept', insert: 'begin()', doc: 'Iterator to first entry.' },
1661
- { name: 'end', detail: 'iterator end() noexcept', insert: 'end()', doc: 'Iterator past last entry.' }
1662
- ],
1663
- set: [
1664
- { name: 'insert', detail: 'pair<iterator, bool> insert(const Key& value)', insert: 'insert(${1:val})', doc: 'Inserts element into set.' },
1665
- { name: 'find', detail: 'iterator find(const Key& key)', insert: 'find(${1:val})', doc: 'Finds element matching key.' },
1666
- { name: 'count', detail: 'size_t count(const Key& key) const', insert: 'count(${1:val})', doc: 'Returns number of matching elements.' },
1667
- { name: 'contains', detail: 'bool contains(const Key& key) const (C++20)', insert: 'contains(${1:val})', doc: 'Checks if element exists (C++20).' },
1668
- { name: 'erase', detail: 'size_t erase(const Key& key)', insert: 'erase(${1:val})', doc: 'Erases element.' },
1669
- { name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns size.' },
1670
- { name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Checks if empty.' }
1671
- ],
1672
- queue: [
1673
- { name: 'push', detail: 'void push(const T& value)', insert: 'push(${1:val})', doc: 'Inserts element at back of queue.' },
1674
- { name: 'pop', detail: 'void pop()', insert: 'pop()', doc: 'Removes front/top element.' },
1675
- { name: 'front', detail: 'T& front()', insert: 'front()', doc: 'Accesses first element (queue).' },
1676
- { name: 'top', detail: 'const T& top() const', insert: 'top()', doc: 'Accesses top element (priority_queue / stack).' },
1677
- { name: 'empty', detail: 'bool empty() const', insert: 'empty()', doc: 'Checks whether underlying container is empty.' },
1678
- { name: 'size', detail: 'size_t size() const', insert: 'size()', doc: 'Returns number of elements.' }
1679
- ],
1680
- ListNode: [
1681
- { name: 'val', detail: 'int val', insert: 'val', doc: 'Node integer value.' },
1682
- { name: 'next', detail: 'ListNode* next', insert: 'next', doc: 'Pointer to next node in singly-linked list.' }
1683
- ],
1684
- TreeNode: [
1685
- { name: 'val', detail: 'int val', insert: 'val', doc: 'Node integer value.' },
1686
- { name: 'left', detail: 'TreeNode* left', insert: 'left', doc: 'Left child pointer.' },
1687
- { name: 'right', detail: 'TreeNode* right', insert: 'right', doc: 'Right child pointer.' }
1688
- ]
1689
- };
1690
-
1691
- function inferCppLocalContainerKind(source: string, ident: string): string | null {
1692
- const escaped = ident.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1693
- const declRe = new RegExp(`(?:std::)?(unordered_map|map|unordered_set|set|vector|string|priority_queue|queue|stack|ListNode|TreeNode)\\s*(?:<[^;{}=]*>)?\\s*[*&]?\\s*\\b${escaped}\\b`);
1694
- const m = source.match(declRe);
1695
- if (!m) return null;
1696
- const raw = m[1];
1697
- if (raw === 'unordered_map' || raw === 'map') return 'map';
1698
- if (raw === 'unordered_set' || raw === 'set') return 'set';
1699
- if (raw === 'priority_queue' || raw === 'queue' || raw === 'stack') return 'queue';
1700
- return raw;
1701
- }
1702
-
1703
- function collectWorkspaceCppSymbols(currentSource: string, currentPath = 'main.cpp') {
1704
- const files: Record<string, string> = _cppWorkspaceFilesGetter ? { ...(_cppWorkspaceFilesGetter() || {}) } : {};
1705
- const cleanCurrent = String(currentPath || 'main.cpp').replace(/^file:\/\/\/workspace\//, '').replace(/^\/workspace\//, '').replace(/^\/+/, '') || 'main.cpp';
1706
- if (currentSource) files[cleanCurrent] = currentSource;
1707
-
1708
- const symbols: Array<{ name: string; kind: 'function' | 'struct' | 'class'; detail: string; file: string; line: number; col: number; params: string[] }> = [];
1709
- for (const [filePath, src] of Object.entries(files)) {
1710
- if (!/\.(?:cpp|cc|cxx|c|h|hpp|hxx)$/i.test(filePath)) continue;
1711
- const lines = String(src || '').split('\n');
1712
- for (let i = 0; i < lines.length; i++) {
1713
- const line = lines[i];
1714
- const trimmed = line.trim();
1715
- if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#')) continue;
1716
- const scMatch = line.match(/^\s*(struct|class)\s+([A-Za-z_][A-Za-z0-9_]*)/);
1717
- if (scMatch) {
1718
- symbols.push({
1719
- name: scMatch[2],
1720
- kind: scMatch[1] as 'struct' | 'class',
1721
- detail: `${scMatch[1]} ${scMatch[2]}`,
1722
- file: filePath,
1723
- line: i + 1,
1724
- col: line.indexOf(scMatch[2]) + 1,
1725
- params: []
1726
- });
1727
- continue;
1728
- }
1729
- const fnMatch = line.match(/^\s*(?:template\s*<[^>]+>\s*)?(?:inline\s+|static\s+|constexpr\s+)*([A-Za-z_][A-Za-z0-9_:<>,&\s*]*?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^;{}]*)\)\s*(?:const\s*)?(?:noexcept\s*)?[{;]/);
1730
- if (fnMatch && !/^(?:if|for|while|switch|catch|return)$/.test(fnMatch[2])) {
1731
- const ret = fnMatch[1].trim();
1732
- const name = fnMatch[2];
1733
- const rawParams = fnMatch[3].trim();
1734
- symbols.push({
1735
- name,
1736
- kind: 'function',
1737
- detail: `${ret} ${name}(${rawParams})`,
1738
- file: filePath,
1739
- line: i + 1,
1740
- col: line.indexOf(name) + 1,
1741
- params: rawParams ? rawParams.split(',').map((p) => p.trim()).filter(Boolean) : []
1742
- });
1743
- }
1744
- }
1745
- }
1746
- return symbols;
1747
- }
1748
-
1749
- /**
1750
- * Registers Monaco C++20 completion, STL member completion, hover, signature help, and definition providers.
1751
- */
1752
- export function registerMonacoCppLanguageService(
1753
- monacoInstance: any,
1754
- getWorkspaceFiles?: () => Record<string, string>
1755
- ): boolean {
1756
- if (typeof getWorkspaceFiles === 'function') {
1757
- _cppWorkspaceFilesGetter = getWorkspaceFiles;
1758
- }
1759
- if (!monacoInstance || !monacoInstance.languages) return false;
1760
- if (_monacoCppInstances.has(monacoInstance)) return true;
1761
- _monacoCppInstances.add(monacoInstance);
1762
-
1763
- try {
1764
- const CIK = monacoInstance.languages.CompletionItemKind || {};
1765
- const CITR = monacoInstance.languages.CompletionItemInsertTextRule || {};
1766
-
1767
- monacoInstance.languages.registerCompletionItemProvider('cpp', {
1768
- triggerCharacters: ['.', ':', '>', '<'],
1769
- provideCompletionItems(model: any, position: any) {
1770
- const wordInfo = model.getWordUntilPosition(position);
1771
- const range = {
1772
- startLineNumber: position.lineNumber,
1773
- endLineNumber: position.lineNumber,
1774
- startColumn: wordInfo.startColumn,
1775
- endColumn: wordInfo.endColumn
1776
- };
1777
- const fullSource = typeof model.getValue === 'function' ? model.getValue() : '';
1778
- const linePrefix = typeof model.getLineContent === 'function'
1779
- ? String(model.getLineContent(position.lineNumber) || '').slice(0, position.column - 1)
1780
- : '';
1781
-
1782
- // Member access `vec.` or `node->`
1783
- const memberMatch = linePrefix.match(/([A-Za-z_][A-Za-z0-9_]*)\s*(?:\.|->)\s*[A-Za-z0-9_]*$/);
1784
- if (memberMatch) {
1785
- const containerKind = inferCppLocalContainerKind(fullSource, memberMatch[1]);
1786
- const members = containerKind ? CPP_STL_CONTAINER_MEMBERS[containerKind] : null;
1787
- if (members) {
1788
- return {
1789
- suggestions: members.map((m) => ({
1790
- label: m.name,
1791
- kind: m.insert?.includes('(') ? (CIK.Method ?? 0) : (CIK.Field ?? 4),
1792
- detail: m.detail,
1793
- documentation: { value: m.doc },
1794
- insertText: m.insert || m.name,
1795
- insertTextRules: CITR.InsertAsSnippet,
1796
- range
1797
- }))
1798
- };
1799
- }
1800
- }
1801
-
1802
- const seen = new Set<string>();
1803
- const suggestions = Object.keys(CPP_COMPLETIONS_AND_HOVERS).map((key) => {
1804
- const item = CPP_COMPLETIONS_AND_HOVERS[key];
1805
- seen.add(item.label);
1806
- return {
1807
- label: item.label,
1808
- kind: CIK.Function ?? 1,
1809
- detail: item.detail,
1810
- documentation: { value: item.documentation },
1811
- insertText: item.insertText || item.label,
1812
- insertTextRules: CITR.InsertAsSnippet,
1813
- range
1814
- };
1815
- });
1816
-
1817
- const wsSyms = collectWorkspaceCppSymbols(fullSource, model.uri?.path || 'main.cpp');
1818
- for (const sym of wsSyms) {
1819
- if (seen.has(sym.name)) continue;
1820
- seen.add(sym.name);
1821
- suggestions.push({
1822
- label: sym.name,
1823
- kind: sym.kind === 'function' ? (CIK.Function ?? 1) : (CIK.Struct ?? 6),
1824
- detail: sym.detail,
1825
- documentation: { value: `Defined in \`${sym.file}:${sym.line}\`` },
1826
- insertText: sym.kind === 'function' ? `${sym.name}(${sym.params.length ? '$1' : ''})` : sym.name,
1827
- insertTextRules: CITR.InsertAsSnippet,
1828
- range
1829
- });
1830
- }
1831
-
1832
- return { suggestions };
1833
- }
1834
- });
1835
-
1836
- monacoInstance.languages.registerHoverProvider('cpp', {
1837
- provideHover(model: any, position: any) {
1838
- const word = model.getWordAtPosition(position);
1839
- if (!word) return null;
1840
-
1841
- const key = CPP_COMPLETIONS_AND_HOVERS[word.word]
1842
- ? word.word
1843
- : (CPP_COMPLETIONS_AND_HOVERS['std::' + word.word] ? 'std::' + word.word : null);
1844
-
1845
- if (key) {
1846
- const item = CPP_COMPLETIONS_AND_HOVERS[key];
1847
- return {
1848
- range: {
1849
- startLineNumber: position.lineNumber,
1850
- endLineNumber: position.lineNumber,
1851
- startColumn: word.startColumn,
1852
- endColumn: word.endColumn
1853
- },
1854
- contents: [
1855
- { value: `**${item.label}** — \`${item.detail}\`` },
1856
- { value: item.documentation }
1857
- ]
1858
- };
1859
- }
1860
-
1861
- const wsSyms = collectWorkspaceCppSymbols(model.getValue?.() || '', model.uri?.path || 'main.cpp');
1862
- const wsHit = wsSyms.find((s) => s.name === word.word);
1863
- if (wsHit) {
1864
- return {
1865
- range: {
1866
- startLineNumber: position.lineNumber,
1867
- endLineNumber: position.lineNumber,
1868
- startColumn: word.startColumn,
1869
- endColumn: word.endColumn
1870
- },
1871
- contents: [
1872
- { value: `\`\`\`cpp\n${wsHit.detail}\n\`\`\`` },
1873
- { value: `Defined in \`${wsHit.file}:${wsHit.line}\`` }
1874
- ]
1875
- };
1876
- }
1877
- return null;
1878
- }
1879
- });
1880
-
1881
- if (typeof monacoInstance.languages.registerDefinitionProvider === 'function' && monacoInstance.Uri) {
1882
- monacoInstance.languages.registerDefinitionProvider('cpp', {
1883
- provideDefinition(model: any, position: any) {
1884
- const word = model.getWordAtPosition(position);
1885
- if (!word) return null;
1886
- const wsSyms = collectWorkspaceCppSymbols(model.getValue?.() || '', model.uri?.path || 'main.cpp');
1887
- const hit = wsSyms.find((s) => s.name === word.word);
1888
- if (!hit) return null;
1889
- const uri = typeof monacoInstance.Uri.file === 'function'
1890
- ? monacoInstance.Uri.file('/workspace/' + hit.file.replace(/^\/+/, ''))
1891
- : model.uri;
1892
- return {
1893
- uri,
1894
- range: {
1895
- startLineNumber: hit.line,
1896
- startColumn: hit.col,
1897
- endLineNumber: hit.line,
1898
- endColumn: hit.col + hit.name.length
1899
- }
1900
- };
1901
- }
1902
- });
1903
- }
1904
-
1905
- return true;
1906
- } catch (err) {
1907
- if (typeof console !== 'undefined' && console.warn) {
1908
- console.warn('[C++ Monaco Intelligence Error]:', err);
1909
- }
1910
- return false;
1911
- }
1912
- }
1913
-
1914
- /**
1915
- * Real-time C++20 static AST/syntax linter.
1916
- * Debounced on keystroke in `.cpp`, `.cc`, `.cxx`, `.hpp`, `.h` files.
1917
- */
1918
- export function analyzeCppSource(source: string, filename = 'main.cpp', vfs?: any): DiagnosticItem[] {
1919
- const diagnostics: DiagnosticItem[] = [];
1920
- if (!source || typeof source !== 'string') return diagnostics;
1921
-
1922
- const lines = source.split('\n');
1923
-
1924
- // 1. Bracket stack matching: {}, (), []
1925
- const stack: Array<{ char: string; line: number; col: number }> = [];
1926
- const matchingPairs: Record<string, string> = { '}': '{', ')': '(', ']': '[' };
1927
-
1928
- let inBlockComment = false;
1929
- for (let l = 0; l < lines.length; l++) {
1930
- const line = lines[l];
1931
- const lineNum = l + 1;
1932
- let inString = false;
1933
- let inChar = false;
1934
- let stringQuote = '';
1935
-
1936
- for (let c = 0; c < line.length; c++) {
1937
- const ch = line[c];
1938
- const next = line[c + 1] || '';
1939
-
1940
- if (inBlockComment) {
1941
- if (ch === '*' && next === '/') {
1942
- inBlockComment = false;
1943
- c++;
1944
- }
1945
- continue;
1946
- }
1947
-
1948
- if (!inString && !inChar) {
1949
- if (ch === '/' && next === '*') {
1950
- inBlockComment = true;
1951
- c++;
1952
- continue;
1953
- }
1954
- if (ch === '/' && next === '/') {
1955
- break; // Rest of line is comment
1956
- }
1957
- }
1958
-
1959
- // Check string & char literal bounds
1960
- if (!inChar && (ch === '"' || (ch === 'R' && next === '"'))) {
1961
- if (ch === 'R') c++; // Raw string literal prefix
1962
- if (c === 0 || line[c - 1] !== '\\') {
1963
- inString = !inString;
1964
- stringQuote = inString ? '"' : '';
1965
- }
1966
- continue;
1967
- }
1968
-
1969
- if (!inString && ch === '\'') {
1970
- if (c === 0 || line[c - 1] !== '\\') {
1971
- inChar = !inChar;
1972
- }
1973
- continue;
1974
- }
1975
-
1976
- if (inString || inChar) continue;
1977
-
1978
- if (ch === '{' || ch === '(' || ch === '[') {
1979
- stack.push({ char: ch, line: lineNum, col: c + 1 });
1980
- } else if (ch === '}' || ch === ')' || ch === ']') {
1981
- const expectedOpening = matchingPairs[ch];
1982
- const last = stack.pop();
1983
- if (!last) {
1984
- diagnostics.push({
1985
- id: `cpp-bracket-unmatched-${lineNum}-${c + 1}`,
1986
- file: filename,
1987
- line: lineNum,
1988
- col: c + 1,
1989
- severity: 'error',
1990
- message: `Unmatched closing bracket '${ch}' with no opening counterpart.`,
1991
- source: 'cpp-linter'
1992
- });
1993
- } else if (last.char !== expectedOpening) {
1994
- diagnostics.push({
1995
- id: `cpp-bracket-mismatch-${lineNum}-${c + 1}`,
1996
- file: filename,
1997
- line: lineNum,
1998
- col: c + 1,
1999
- severity: 'error',
2000
- message: `Mismatched bracket: found '${ch}' but expected closing for '${last.char}' from line ${last.line}.`,
2001
- source: 'cpp-linter'
2002
- });
2003
- }
2004
- }
2005
- }
2006
-
2007
- if (inString && !inBlockComment) {
2008
- diagnostics.push({
2009
- id: `cpp-string-unterminated-${lineNum}`,
2010
- file: filename,
2011
- line: lineNum,
2012
- col: line.length,
2013
- severity: 'error',
2014
- message: 'Unterminated string literal on line.',
2015
- source: 'cpp-linter'
2016
- });
2017
- }
2018
- }
2019
-
2020
- for (const unclosed of stack) {
2021
- diagnostics.push({
2022
- id: `cpp-bracket-unclosed-${unclosed.line}-${unclosed.col}`,
2023
- file: filename,
2024
- line: unclosed.line,
2025
- col: unclosed.col,
2026
- severity: 'error',
2027
- message: `Unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
2028
- source: 'cpp-linter'
2029
- });
2030
- }
2031
-
2032
- // 2. Validate #include <...> against C++20 standard library + VFS
2033
- const includeRegex = /#include\s*([<"])([^>"]+)[>"]/g;
2034
- let incMatch: RegExpExecArray | null;
2035
- const includedHeaders = new Set<string>();
2036
-
2037
- while ((incMatch = includeRegex.exec(source)) !== null) {
2038
- const isAngle = incMatch[1] === '<';
2039
- const hdr = incMatch[2].trim();
2040
- includedHeaders.add(hdr);
2041
- const lineIndex = source.slice(0, incMatch.index).split('\n').length;
2042
-
2043
- if (isAngle) {
2044
- const known = STANDARD_CPP20_HEADERS.has(hdr) ||
2045
- hdr.startsWith('bits/') ||
2046
- hdr.startsWith('codelab/') ||
2047
- (vfs && (vfs.existsSync(`/usr/include/${hdr}`) || vfs.existsSync(`/workspace/${hdr}`)));
2048
- if (!known) {
2049
- diagnostics.push({
2050
- id: `cpp-unknown-include-${lineIndex}`,
2051
- file: filename,
2052
- line: lineIndex,
2053
- col: 1,
2054
- severity: 'warning',
2055
- message: `Unknown or unresolvable C++ header <${hdr}>.`,
2056
- source: 'cpp-linter'
2057
- });
2058
- }
2059
- }
2060
- }
2061
-
2062
- // 3. Missing #include checks for DSA utilities and Test harness
2063
- const hasDsaHeader = includedHeaders.has('codelab/dsa.hpp') || includedHeaders.has('bits/stdc++.h');
2064
- const dsaSymbols = ['ListNode', 'TreeNode', 'buildLinkedList', 'linkedListToVector', 'buildBinaryTree'];
2065
- for (const sym of dsaSymbols) {
2066
- const symRegex = new RegExp(`\\b${sym}\\b`);
2067
- if (symRegex.test(source) && !hasDsaHeader) {
2068
- diagnostics.push({
2069
- id: `cpp-missing-dsa-include-${sym}`,
2070
- file: filename,
2071
- line: 1,
2072
- col: 1,
2073
- severity: 'warning',
2074
- message: `Symbol '${sym}' used without #include <codelab/dsa.hpp>.`,
2075
- source: 'cpp-linter'
2076
- });
2077
- break;
2078
- }
2079
- }
2080
-
2081
- const hasTestHeader = includedHeaders.has('codelab/test.hpp');
2082
- const testSymbols = ['DESCRIBE', 'TEST', 'ASSERT_EQ', 'ASSERT_NE', 'ASSERT_TRUE', 'ASSERT_FALSE', 'CODELAB_TEST_EXIT_CODE'];
2083
- for (const sym of testSymbols) {
2084
- const symRegex = new RegExp(`\\b${sym}\\b`);
2085
- if (symRegex.test(source) && !hasTestHeader) {
2086
- diagnostics.push({
2087
- id: `cpp-missing-test-include-${sym}`,
2088
- file: filename,
2089
- line: 1,
2090
- col: 1,
2091
- severity: 'warning',
2092
- message: `Test macro '${sym}' used without #include <codelab/test.hpp>.`,
2093
- source: 'cpp-linter'
2094
- });
2095
- break;
2096
- }
2097
- }
2098
-
2099
- // 4. Suspicious assignment inside if condition (e.g. if (x = 5))
2100
- for (let l = 0; l < lines.length; l++) {
2101
- const line = lines[l];
2102
- const assignMatch = /\bif\s*\(([^;)]*[^=!<>]=[^=][^;)]*)\)/.exec(line);
2103
- if (assignMatch) {
2104
- diagnostics.push({
2105
- id: `cpp-suspicious-assign-${l + 1}`,
2106
- file: filename,
2107
- line: l + 1,
2108
- col: assignMatch.index + 1,
2109
- severity: 'warning',
2110
- message: `Suspicious assignment '=' inside 'if' condition; did you mean '=='?`,
2111
- source: 'cpp-linter'
2112
- });
2113
- }
2114
- }
2115
-
2116
- // 5. Balanced-brace check for missing semicolon after class or struct definitions
2117
- if (stack.length === 0) {
2118
- const structHeadRegex = /\b(?:struct|class)\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^{;]*)?\{/g;
2119
- let structMatch: RegExpExecArray | null;
2120
- while ((structMatch = structHeadRegex.exec(source)) !== null) {
2121
- const typeName = structMatch[1];
2122
- let pos = structMatch.index + structMatch[0].length;
2123
- let depth = 1;
2124
- let inStr = false;
2125
- let inChr = false;
2126
- let inBlk = false;
2127
- let inLn = false;
2128
- while (pos < source.length && depth > 0) {
2129
- const ch = source[pos];
2130
- const nx = source[pos + 1] || '';
2131
- if (inLn) {
2132
- if (ch === '\n') inLn = false;
2133
- pos++;
2134
- continue;
2135
- }
2136
- if (inBlk) {
2137
- if (ch === '*' && nx === '/') { inBlk = false; pos += 2; continue; }
2138
- pos++;
2139
- continue;
2140
- }
2141
- if (!inStr && !inChr) {
2142
- if (ch === '/' && nx === '/') { inLn = true; pos += 2; continue; }
2143
- if (ch === '/' && nx === '*') { inBlk = true; pos += 2; continue; }
2144
- }
2145
- if (!inChr && ch === '"' && source[pos - 1] !== '\\') { inStr = !inStr; pos++; continue; }
2146
- if (!inStr && ch === '\'' && source[pos - 1] !== '\\') { inChr = !inChr; pos++; continue; }
2147
- if (!inStr && !inChr) {
2148
- if (ch === '{') depth++;
2149
- else if (ch === '}') depth--;
2150
- }
2151
- pos++;
2152
- }
2153
- if (depth === 0) {
2154
- const afterClose = source.slice(pos).replace(/^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)+/, '');
2155
- // Valid: `;` immediately OR variable declarators like `p1, *p2;` before next newline/block
2156
- const validTerminator = /^;|^[A-Za-z_*&][A-Za-z0-9_,\s*&[\]=()]*;/.test(afterClose);
2157
- if (afterClose.length > 0 && !validTerminator) {
2158
- const lineIndex = source.slice(0, pos).split('\n').length;
2159
- diagnostics.push({
2160
- id: `cpp-missing-semicolon-${lineIndex}`,
2161
- file: filename,
2162
- line: lineIndex,
2163
- col: 1,
2164
- severity: 'error',
2165
- message: `Missing semicolon ';' after '${typeName}' class/struct definition.`,
2166
- source: 'cpp-linter'
2167
- });
2168
- }
2169
- }
2170
- }
2171
- }
2172
-
2173
- return diagnostics;
2174
- }
2175
-
2176
- /**
2177
- * Parses Clang / LLVM WASI compiler stderr and applies diagnostics to Monaco and DiagnosticsStore.
2178
- */
2179
- export function applyClangStderrDiagnostics(
2180
- stderrText: string,
2181
- diagnosticsStore?: any,
2182
- monacoInstance?: any,
2183
- activeModel?: any
2184
- ): DiagnosticItem[] {
2185
- const diagnostics: DiagnosticItem[] = [];
2186
- if (!stderrText || typeof stderrText !== 'string') return diagnostics;
2187
-
2188
- if (diagnosticsStore && typeof diagnosticsStore.clear === 'function') {
2189
- diagnosticsStore.clear('clang');
2190
- }
2191
-
2192
- const clangRegex = /(?:(?:^|\n)(?:\/workspace\/)?([^\s:\n]+)):(\d+):(\d+):\s*(fatal error|error|warning|note):\s*([^\n]+)/g;
2193
- let match: RegExpExecArray | null;
2194
- let idx = 0;
2195
-
2196
- while ((match = clangRegex.exec(stderrText)) !== null) {
2197
- const rawFile = match[1].trim();
2198
- const line = parseInt(match[2], 10) || 1;
2199
- const col = parseInt(match[3], 10) || 1;
2200
- const rawKind = match[4].toLowerCase();
2201
- const message = match[5].trim();
2202
-
2203
- let severity: 'error' | 'warning' | 'info' = 'error';
2204
- if (rawKind === 'warning') severity = 'warning';
2205
- else if (rawKind === 'note') severity = 'info';
2206
-
2207
- const item: DiagnosticItem = {
2208
- id: `clang-${rawFile}-${line}-${col}-${idx++}`,
2209
- file: rawFile,
2210
- line,
2211
- col,
2212
- severity,
2213
- message: `[Clang] ${message}`,
2214
- source: 'clang'
2215
- };
2216
- diagnostics.push(item);
2217
- if (diagnosticsStore && typeof diagnosticsStore.add === 'function') {
2218
- diagnosticsStore.add(item);
2219
- }
2220
- }
2221
-
2222
- if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === 'function') {
2223
- const markers = diagnostics.map((d) => ({
2224
- startLineNumber: d.line,
2225
- startColumn: d.col || 1,
2226
- endLineNumber: d.line,
2227
- endColumn: (d.col || 1) + 20,
2228
- message: d.message,
2229
- severity: d.severity === 'error'
2230
- ? monacoInstance.MarkerSeverity.Error
2231
- : (d.severity === 'warning' ? monacoInstance.MarkerSeverity.Warning : monacoInstance.MarkerSeverity.Info)
2232
- }));
2233
- monacoInstance.editor.setModelMarkers(activeModel, 'clang', markers);
2234
- }
2235
-
2236
- return diagnostics;
2237
- }
2238
-
2239
- /**
2240
- * Real C++20 in WebAssembly Extension for CodeLab (`@innovatorved/code-lab/extensions/cpp`).
2241
- *
2242
- * Enables:
2243
- * - Real Clang/LLVM + LLD + WASI C++20 compilation in WebAssembly (~35 MB downloaded on demand & cached in IndexedDB)
2244
- * - `<bits/stdc++.h>`, `<codelab/dsa.hpp>`, and `<codelab/test.hpp>` headers in VirtualFS
2245
- * - `JS | TS | C++` language switcher in the CodeLab workbench
2246
- * - `g++`, `clang++`, `c++`, and `./a.out` binary execution in the POSIX shell
2247
- * - Guided Lab `cppStarterFiles`, `cppSolutionFiles`, and `cppFiles` curriculum support
2248
- * - Monaco IntelliSense, hovers, debounced C++20 static linter, and Clang compiler squiggles
2249
- */
2250
- export function installCppExtension(workbench: any, options: ExtendedCppExtensionOptions = {}) {
2251
- const toolchain = new CppToolchainManager(options);
2252
- const compilerFn = registerCppCompilerOnRuntime(toolchain);
2253
-
2254
- if (!workbench) return toolchain;
2255
-
2256
- workbench.cppToolchain = toolchain;
2257
- workbench.cppCompiler = compilerFn;
2258
- workbench.cppOptions = toolchain.options;
2259
-
2260
- // Register Monaco language service immediately and queue hook if Monaco loads asynchronously
2261
- const getWsFiles = () => (workbench && workbench.files ? workbench.files : {});
2262
- if (typeof window !== 'undefined' && (window as any).monaco) {
2263
- registerMonacoCppLanguageService((window as any).monaco, getWsFiles);
2264
- }
2265
- if (!Array.isArray(workbench._monacoReadyHooks)) {
2266
- workbench._monacoReadyHooks = [];
2267
- }
2268
- workbench._monacoReadyHooks.push((monaco: any) => {
2269
- registerMonacoCppLanguageService(monaco, getWsFiles);
2270
- });
2271
-
2272
- if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
2273
- workbench.enabledLanguages = new Set(['js', 'cpp']);
2274
- } else {
2275
- workbench.enabledLanguages.add('cpp');
2276
- }
2277
-
2278
- if (options.files && typeof options.files === 'object') {
2279
- workbench.cppFiles = { ...(workbench.cppFiles || {}), ...options.files };
2280
- if (workbench.guidedConfig) {
2281
- workbench.guidedConfig.cppFiles = { ...(workbench.guidedConfig.cppFiles || {}), ...options.files };
2282
- }
2283
- }
2284
- if (options.starterFiles && typeof options.starterFiles === 'object') {
2285
- if (!workbench.guidedConfig) workbench.guidedConfig = {};
2286
- workbench.guidedConfig.cppStarterFiles = {
2287
- ...(workbench.guidedConfig.cppStarterFiles || {}),
2288
- ...options.starterFiles
2289
- };
2290
- }
2291
- if (options.solutionFiles && typeof options.solutionFiles === 'object') {
2292
- if (!workbench.guidedConfig) workbench.guidedConfig = {};
2293
- workbench.guidedConfig.cppSolutionFiles = {
2294
- ...(workbench.guidedConfig.cppSolutionFiles || {}),
2295
- ...options.solutionFiles
2296
- };
2297
- }
2298
-
2299
- if (workbench.vfs) {
2300
- seedCppHeadersIntoVfs(workbench.vfs, toolchain.options.extraHeaders);
2301
- }
2302
-
2303
- workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
2304
-
2305
- // Synchronous static C++ linter (resolves _diagnosticsStore dynamically)
2306
- workbench._cppLintHandler = (file: string, code: string) => {
2307
- if (!file || !/\.(?:cpp|cc|cxx|hpp|h)$/i.test(file)) return;
2308
- const diags = analyzeCppSource(String(code ?? ''), file, workbench ? workbench.vfs : undefined);
2309
- const store = workbench ? workbench._diagnosticsStore : null;
2310
- if (store && typeof store.setFileDiagnostics === 'function') {
2311
- store.setFileDiagnostics(file, 'cpp-linter', diags);
2312
- } else if (store && typeof store.clear === 'function' && typeof store.add === 'function') {
2313
- store.clear('cpp-linter');
2314
- for (const d of diags) {
2315
- store.add(d);
2316
- }
2317
- }
2318
- if (typeof window !== 'undefined' && (window as any).monaco) {
2319
- const model =
2320
- (workbench.models && typeof workbench.models.get === 'function' && workbench.models.get(file)) ||
2321
- (workbench.activeFile === file && workbench.editor ? workbench.editor.getModel() : null);
2322
- if (model) {
2323
- const markers = diags.map((d) => ({
2324
- startLineNumber: d.line,
2325
- startColumn: d.col || 1,
2326
- endLineNumber: d.endLine || d.line,
2327
- endColumn: d.endCol || (d.col || 1) + 20,
2328
- message: d.message,
2329
- severity:
2330
- d.severity === 'error'
2331
- ? (window as any).monaco.MarkerSeverity.Error
2332
- : (window as any).monaco.MarkerSeverity.Warning
2333
- }));
2334
- (window as any).monaco.editor.setModelMarkers(model, 'cpp-linter', markers);
2335
- }
2336
- }
2337
- };
2338
-
2339
- if (options.preload) {
2340
- toolchain.ensureLoaded().catch((err) => {
2341
- if (typeof workbench._appendTerminalOutput === 'function') {
2342
- workbench._appendTerminalOutput('stderr', `[C++ Toolchain preload warning]: ${err.message || err}\n`);
2343
- }
2344
- });
2345
- }
2346
-
2347
- if (options.activate && typeof workbench.setLanguage === 'function') {
2348
- workbench.setLanguage('cpp');
2349
- } else if (typeof workbench._refreshToolbarAndTabs === 'function') {
2350
- workbench._refreshToolbarAndTabs();
2351
- } else if (typeof workbench._renderShell === 'function' && workbench.container) {
2352
- workbench._renderShell();
2353
- if (typeof workbench._bindEvents === 'function') workbench._bindEvents();
2354
- if (typeof workbench._renderFileLists === 'function') workbench._renderFileLists();
2355
- }
2356
-
2357
- return workbench;
2358
- }
2359
-
2360
- export function cppExtension(workbenchOrOptions?: any, maybeOptions?: ExtendedCppExtensionOptions): any {
2361
- if (workbenchOrOptions === null) {
2362
- const toolchain = new CppToolchainManager(maybeOptions || {});
2363
- registerCppCompilerOnRuntime(toolchain);
2364
- return toolchain;
2365
- }
2366
- if (
2367
- workbenchOrOptions === undefined ||
2368
- (typeof workbenchOrOptions === 'object' &&
2369
- !('enabledLanguages' in workbenchOrOptions) &&
2370
- !('container' in workbenchOrOptions) &&
2371
- !('_renderShell' in workbenchOrOptions))
2372
- ) {
2373
- const opts = (workbenchOrOptions || {}) as ExtendedCppExtensionOptions;
2374
- const plugin: any = (wb: any, runOpts: any = {}) => {
2375
- return installCppExtension(wb, { ...opts, ...(runOpts || {}) });
2376
- };
2377
- plugin.extensionName = 'cpp';
2378
- plugin.languageId = 'cpp' as const;
2379
- plugin.install = plugin;
2380
- return plugin;
2381
- }
2382
- return installCppExtension(workbenchOrOptions, maybeOptions);
2383
- }
2384
-
2385
- export function createCppExtension(options: ExtendedCppExtensionOptions = {}) {
2386
- return cppExtension(options);
2387
- }
2388
-
2389
- export default cppExtension;