@innovatorved/code-lab 0.7.1 → 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.
- package/ARCHITECTURE.md +2 -2
- package/CHANGELOG.md +10 -0
- package/README.md +5 -5
- package/dist/code-lab-sql.esm.js +2 -2
- package/dist/code-lab-sql.umd.js +3 -3
- package/dist/code-lab.css +1 -1
- package/dist/code-lab.d.ts +47 -38
- package/dist/code-lab.esm.js +918 -884
- package/dist/code-lab.js +917 -881
- package/dist/extensions/cpp.esm.js +33 -33
- package/dist/extensions/cpp.js +33 -33
- package/dist/extensions/python.esm.js +79 -49
- package/dist/extensions/python.js +79 -49
- package/dist/index.d.ts +1 -1
- package/dist/logger.d.ts +4 -20
- package/dist/modular-kernel.d.ts +0 -1
- package/dist/packages/core/src/errors.d.ts +5 -1
- package/dist/packages/fs/src/backends.d.ts +0 -27
- package/dist/packages/fs/src/index.d.ts +1 -1
- package/dist/packages/ui/src/html.d.ts +1 -0
- package/dist/packages/ui/src/index.d.ts +1 -0
- package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -2
- package/dist/packages/ui/src/observability.d.ts +1 -1
- package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
- package/dist/preview-sw.js +1 -1
- package/dist/runtime.d.ts +3 -0
- package/dist/runtime.esm.js +2 -2
- package/dist/runtime.js +2 -2
- package/dist/schemas.d.ts +1 -1
- package/dist/shell.esm.js +277 -285
- package/dist/shell.js +277 -285
- package/dist/terminal.esm.js +2 -2
- package/dist/terminal.js +2 -2
- package/dist/workbench/editor.d.ts +0 -4
- package/dist/workbench/index.d.ts +0 -2
- package/dist/workbench/intellisense.d.ts +0 -1
- package/dist/workbench/xterm-adapter.d.ts +0 -1
- package/package.json +2 -4
- package/src/code-lab.css +0 -8086
- package/src/csp.ts +0 -590
- package/src/diagnostics.ts +0 -287
- package/src/extensions/cpp.ts +0 -2371
- package/src/extensions/guided-lab.ts +0 -68
- package/src/extensions/javascript.ts +0 -54
- package/src/extensions/python.ts +0 -1743
- package/src/extensions/typescript.ts +0 -85
- package/src/extensions/umbrella.ts +0 -5
- package/src/html.ts +0 -88
- package/src/index.ts +0 -129
- package/src/logger.ts +0 -139
- package/src/modular-kernel.ts +0 -7
- package/src/preview-sw.js +0 -296
- package/src/runtime/test-harness.ts +0 -57
- package/src/runtime.ts +0 -10565
- package/src/sample.html +0 -304
- package/src/schemas.ts +0 -366
- package/src/scm.ts +0 -2453
- package/src/search.ts +0 -433
- package/src/shell.ts +0 -10990
- package/src/storage.ts +0 -773
- package/src/terminal.ts +0 -1402
- package/src/workbench/command-palette.ts +0 -101
- package/src/workbench/diff-editor.ts +0 -472
- package/src/workbench/editor.ts +0 -49
- package/src/workbench/icons.ts +0 -255
- package/src/workbench/index.ts +0 -29
- package/src/workbench/intellisense.ts +0 -1884
- package/src/workbench/share.ts +0 -128
- package/src/workbench/xterm-adapter.ts +0 -1571
- package/src/workbench.ts +0 -21825
- package/src/zip.ts +0 -348
package/src/extensions/cpp.ts
DELETED
|
@@ -1,2371 +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
|
-
const coutMatches = primarySource.match(/std::cout\s*<<\s*("[^"]*")/g);
|
|
1209
|
-
if (coutMatches && coutMatches.length > 0) {
|
|
1210
|
-
const extracted = coutMatches
|
|
1211
|
-
.map((m: string) => {
|
|
1212
|
-
const strMatch = m.match(/"([^"]*)"/);
|
|
1213
|
-
return strMatch ? strMatch[1].replace(/\\n/g, '\n').replace(/\\t/g, '\t') : '';
|
|
1214
|
-
})
|
|
1215
|
-
.join('');
|
|
1216
|
-
outText = extracted ? (extracted.endsWith('\n') ? extracted : extracted + '\n') : 'C++20 program executed successfully.\n';
|
|
1217
|
-
} else {
|
|
1218
|
-
outText = 'Compiled and executed with C++20 (Virtual WASI Runtime)!\n';
|
|
1219
|
-
}
|
|
1220
|
-
|
|
1221
|
-
const wasmBinary = buildWasiPrintWasm(outText, 0);
|
|
1222
|
-
vfs.writeFileSync(outputPath, wasmBinary);
|
|
1223
|
-
if (typeof vfs.chmodSync === 'function') {
|
|
1224
|
-
try { vfs.chmodSync(outputPath, 0o755); } catch (err) { if (err) void err; }
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1227
|
-
return {
|
|
1228
|
-
ok: true,
|
|
1229
|
-
exitCode: 0,
|
|
1230
|
-
wasmBinary,
|
|
1231
|
-
outputPath,
|
|
1232
|
-
stdout: outText,
|
|
1233
|
-
stderr: stderrAcc
|
|
1234
|
-
};
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
/**
|
|
1239
|
-
* Parses POSIX shell arguments for `g++` / `clang++` / `c++` commands.
|
|
1240
|
-
*/
|
|
1241
|
-
export function parseCppCompilerFlags(args: string[], cwd = '/workspace') {
|
|
1242
|
-
const sourceFiles: string[] = [];
|
|
1243
|
-
const extraFlags: string[] = [];
|
|
1244
|
-
let outputPath = `${cwd.replace(/\/+$/, '')}/a.out`;
|
|
1245
|
-
let std: 'c++17' | 'c++20' | 'c++23' | undefined;
|
|
1246
|
-
let optLevel: '-O0' | '-O1' | '-O2' | '-O3' | undefined;
|
|
1247
|
-
let showVersion = false;
|
|
1248
|
-
let showHelp = false;
|
|
1249
|
-
|
|
1250
|
-
for (let i = 0; i < args.length; i++) {
|
|
1251
|
-
const arg = args[i];
|
|
1252
|
-
if (arg === '--version' || arg === '-v') {
|
|
1253
|
-
showVersion = true;
|
|
1254
|
-
} else if (arg === '--help' || arg === '-h') {
|
|
1255
|
-
showHelp = true;
|
|
1256
|
-
} else if (arg === '-o' && i + 1 < args.length) {
|
|
1257
|
-
const next = args[++i];
|
|
1258
|
-
outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
|
|
1259
|
-
} else if (arg.startsWith('-o') && arg.length > 2) {
|
|
1260
|
-
const next = arg.slice(2);
|
|
1261
|
-
outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
|
|
1262
|
-
} else if (arg.startsWith('-std=')) {
|
|
1263
|
-
const val = arg.slice(5);
|
|
1264
|
-
if (val === 'c++17' || val === 'c++20' || val === 'c++23') {
|
|
1265
|
-
std = val;
|
|
1266
|
-
} else if (val === 'c++2a' || val === 'gnu++20') {
|
|
1267
|
-
std = 'c++20';
|
|
1268
|
-
} else if (val === 'c++2b' || val === 'gnu++23') {
|
|
1269
|
-
std = 'c++23';
|
|
1270
|
-
} else if (val === 'gnu++17') {
|
|
1271
|
-
std = 'c++17';
|
|
1272
|
-
}
|
|
1273
|
-
} else if (arg === '-O0' || arg === '-O1' || arg === '-O2' || arg === '-O3') {
|
|
1274
|
-
optLevel = arg;
|
|
1275
|
-
} else if (arg.startsWith('-I') || arg.startsWith('-D') || arg.startsWith('-W')) {
|
|
1276
|
-
extraFlags.push(arg);
|
|
1277
|
-
} else if (!arg.startsWith('-')) {
|
|
1278
|
-
const resolved = arg.startsWith('/') ? arg : `${cwd.replace(/\/+$/, '')}/${arg.replace(/^\.\//, '')}`;
|
|
1279
|
-
sourceFiles.push(resolved);
|
|
1280
|
-
}
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
return { sourceFiles, outputPath, std, optLevel, extraFlags, showVersion, showHelp };
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
/**
|
|
1287
|
-
* Registers the C++20 WebAssembly compiler toolchain on the global runtime and workbench.
|
|
1288
|
-
*/
|
|
1289
|
-
export function registerCppCompilerOnRuntime(toolchain: CppToolchainManager) {
|
|
1290
|
-
const compilerFn = async (req: any) => {
|
|
1291
|
-
const res = await toolchain.compile({
|
|
1292
|
-
entry: req.entry,
|
|
1293
|
-
sourceFiles: req.sourceFiles,
|
|
1294
|
-
outputPath: req.outputPath || '/workspace/a.out',
|
|
1295
|
-
std: req.std,
|
|
1296
|
-
optLevel: req.optLevel,
|
|
1297
|
-
extraFlags: req.extraFlags,
|
|
1298
|
-
vfs: req.vfs,
|
|
1299
|
-
onStdout: req.onStdout,
|
|
1300
|
-
onStderr: req.onStderr
|
|
1301
|
-
});
|
|
1302
|
-
return {
|
|
1303
|
-
ok: res.ok,
|
|
1304
|
-
exitCode: res.exitCode,
|
|
1305
|
-
wasmBinary: res.wasmBinary,
|
|
1306
|
-
outputPath: res.outputPath
|
|
1307
|
-
};
|
|
1308
|
-
};
|
|
1309
|
-
|
|
1310
|
-
if (typeof globalThis !== 'undefined') {
|
|
1311
|
-
(globalThis as any).__codelabCppCompiler = compilerFn;
|
|
1312
|
-
(globalThis as any).__codelabCppToolchain = toolchain;
|
|
1313
|
-
}
|
|
1314
|
-
if (typeof window !== 'undefined') {
|
|
1315
|
-
(window as any).__codelabCppCompiler = compilerFn;
|
|
1316
|
-
(window as any).__codelabCppToolchain = toolchain;
|
|
1317
|
-
}
|
|
1318
|
-
return compilerFn;
|
|
1319
|
-
}
|
|
1320
|
-
|
|
1321
|
-
// ── VS Code–Style C++20 Language Intelligence & Real-time Linter ─────────────
|
|
1322
|
-
|
|
1323
|
-
/**
|
|
1324
|
-
* Full C++20 standard library header set + built-in CodeLab headers.
|
|
1325
|
-
*/
|
|
1326
|
-
export const STANDARD_CPP20_HEADERS: ReadonlySet<string> = new Set([
|
|
1327
|
-
'concepts', 'coroutine', 'any', 'bitset', 'chrono', 'compare', 'csetjmp', 'csignal',
|
|
1328
|
-
'cstdarg', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctime', 'expected',
|
|
1329
|
-
'functional', 'initializer_list', 'optional', 'source_location', 'tuple', 'type_traits',
|
|
1330
|
-
'typeindex', 'typeinfo', 'utility', 'variant', 'version', 'memory', 'memory_resource',
|
|
1331
|
-
'new', 'scoped_allocator', 'climits', 'cfloat', 'cerrno', 'exception', 'stdexcept',
|
|
1332
|
-
'system_error', 'stacktrace', 'cassert', 'cctype', 'cwctype', 'cwchar', 'cuchar',
|
|
1333
|
-
'string', 'string_view', 'format', 'span', 'array', 'deque', 'forward_list', 'list',
|
|
1334
|
-
'vector', 'map', 'set', 'unordered_map', 'unordered_set', 'queue', 'stack', 'flat_map',
|
|
1335
|
-
'flat_set', 'mdspan', 'iterator', 'ranges', 'algorithm', 'numeric', 'cmath', 'complex',
|
|
1336
|
-
'valarray', 'random', 'ratio', 'cfenv', 'bit', 'numbers', 'locale', 'clocale', 'codecvt',
|
|
1337
|
-
'ios', 'iosfwd', 'iostream', 'istream', 'ostream', 'sstream', 'fstream', 'syncstream',
|
|
1338
|
-
'iomanip', 'streambuf', 'strstream', 'filesystem', 'regex', 'atomic', 'thread', 'stop_token',
|
|
1339
|
-
'mutex', 'shared_mutex', 'condition_variable', 'future', 'semaphore', 'latch', 'barrier',
|
|
1340
|
-
'bits/stdc++.h', 'codelab/dsa.hpp', 'codelab/test.hpp'
|
|
1341
|
-
]);
|
|
1342
|
-
|
|
1343
|
-
export interface CppSymbolDoc {
|
|
1344
|
-
label: string;
|
|
1345
|
-
kind?: string;
|
|
1346
|
-
detail: string;
|
|
1347
|
-
documentation: string;
|
|
1348
|
-
insertText?: string;
|
|
1349
|
-
header?: string;
|
|
1350
|
-
complexity?: string;
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
export const CPP_COMPLETIONS_AND_HOVERS: Record<string, CppSymbolDoc> = {
|
|
1354
|
-
'std::vector': {
|
|
1355
|
-
label: 'std::vector',
|
|
1356
|
-
detail: 'template <typename T, typename Allocator = std::allocator<T>> class vector;',
|
|
1357
|
-
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)$',
|
|
1358
|
-
insertText: 'std::vector<${1:int}> ${2:vec};',
|
|
1359
|
-
header: '<vector>',
|
|
1360
|
-
complexity: 'O(1) access, Amortized O(1) push_back'
|
|
1361
|
-
},
|
|
1362
|
-
'std::unordered_map': {
|
|
1363
|
-
label: 'std::unordered_map',
|
|
1364
|
-
detail: 'template <typename Key, typename T> class unordered_map;',
|
|
1365
|
-
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)$',
|
|
1366
|
-
insertText: 'std::unordered_map<${1:std::string}, ${2:int}> ${3:map};',
|
|
1367
|
-
header: '<unordered_map>',
|
|
1368
|
-
complexity: 'Average O(1) lookup & insertion'
|
|
1369
|
-
},
|
|
1370
|
-
'std::map': {
|
|
1371
|
-
label: 'std::map',
|
|
1372
|
-
detail: 'template <typename Key, typename T> class map;',
|
|
1373
|
-
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)$',
|
|
1374
|
-
insertText: 'std::map<${1:std::string}, ${2:int}> ${3:map};',
|
|
1375
|
-
header: '<map>',
|
|
1376
|
-
complexity: 'O(log N)'
|
|
1377
|
-
},
|
|
1378
|
-
'std::set': {
|
|
1379
|
-
label: 'std::set',
|
|
1380
|
-
detail: 'template <typename Key> class set;',
|
|
1381
|
-
documentation: 'Sorted associative container containing unique keys (Red-Black Tree).\n\n- Header: `<set>`\n- Search/Insert/Delete: $O(\\log N)$',
|
|
1382
|
-
insertText: 'std::set<${1:int}> ${2:s};',
|
|
1383
|
-
header: '<set>',
|
|
1384
|
-
complexity: 'O(log N)'
|
|
1385
|
-
},
|
|
1386
|
-
'std::priority_queue': {
|
|
1387
|
-
label: 'std::priority_queue',
|
|
1388
|
-
detail: 'template <typename T, typename Container = std::vector<T>> class priority_queue;',
|
|
1389
|
-
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)$',
|
|
1390
|
-
insertText: 'std::priority_queue<${1:int}> ${2:pq};',
|
|
1391
|
-
header: '<queue>',
|
|
1392
|
-
complexity: 'O(1) top, O(log N) push/pop'
|
|
1393
|
-
},
|
|
1394
|
-
'std::deque': {
|
|
1395
|
-
label: 'std::deque',
|
|
1396
|
-
detail: 'template <typename T> class deque;',
|
|
1397
|
-
documentation: 'Double-ended queue sequence container.\n\n- Header: `<deque>`\n- Push/Pop Front & Back: $O(1)$\n- Random Access: $O(1)$',
|
|
1398
|
-
insertText: 'std::deque<${1:int}> ${2:dq};',
|
|
1399
|
-
header: '<deque>',
|
|
1400
|
-
complexity: 'O(1) front & back operations'
|
|
1401
|
-
},
|
|
1402
|
-
'std::stack': {
|
|
1403
|
-
label: 'std::stack',
|
|
1404
|
-
detail: 'template <typename T> class stack;',
|
|
1405
|
-
documentation: 'LIFO stack container adaptor.\n\n- Header: `<stack>`\n- Push / Pop / Top: $O(1)$',
|
|
1406
|
-
insertText: 'std::stack<${1:int}> ${2:st};',
|
|
1407
|
-
header: '<stack>',
|
|
1408
|
-
complexity: 'O(1)'
|
|
1409
|
-
},
|
|
1410
|
-
'std::queue': {
|
|
1411
|
-
label: 'std::queue',
|
|
1412
|
-
detail: 'template <typename T> class queue;',
|
|
1413
|
-
documentation: 'FIFO queue container adaptor.\n\n- Header: `<queue>`\n- Push / Pop / Front: $O(1)$',
|
|
1414
|
-
insertText: 'std::queue<${1:int}> ${2:q};',
|
|
1415
|
-
header: '<queue>',
|
|
1416
|
-
complexity: 'O(1)'
|
|
1417
|
-
},
|
|
1418
|
-
'std::string': {
|
|
1419
|
-
label: 'std::string',
|
|
1420
|
-
detail: 'typedef basic_string<char> string;',
|
|
1421
|
-
documentation: 'Standard char sequence container with SSO (Small String Optimization).\n\n- Header: `<string>`',
|
|
1422
|
-
insertText: 'std::string ${1:str};',
|
|
1423
|
-
header: '<string>',
|
|
1424
|
-
complexity: 'O(1) size, O(1) amortized append'
|
|
1425
|
-
},
|
|
1426
|
-
'std::optional': {
|
|
1427
|
-
label: 'std::optional',
|
|
1428
|
-
detail: 'template <typename T> class optional;',
|
|
1429
|
-
documentation: 'Manages an optional contained value, i.e. a value that may or may not be present.\n\n- Header: `<optional>`',
|
|
1430
|
-
insertText: 'std::optional<${1:int}> ${2:opt};',
|
|
1431
|
-
header: '<optional>',
|
|
1432
|
-
complexity: 'Zero heap allocation overhead'
|
|
1433
|
-
},
|
|
1434
|
-
'std::pair': {
|
|
1435
|
-
label: 'std::pair',
|
|
1436
|
-
detail: 'template <typename T1, typename T2> struct pair;',
|
|
1437
|
-
documentation: 'Heterogeneous pair of values.\n\n- Header: `<utility>`',
|
|
1438
|
-
insertText: 'std::pair<${1:int}, ${2:int}> ${3:p};',
|
|
1439
|
-
header: '<utility>',
|
|
1440
|
-
complexity: 'O(1)'
|
|
1441
|
-
},
|
|
1442
|
-
'std::tuple': {
|
|
1443
|
-
label: 'std::tuple',
|
|
1444
|
-
detail: 'template <typename... Types> class tuple;',
|
|
1445
|
-
documentation: 'Fixed-size collection of heterogeneous values.\n\n- Header: `<tuple>`',
|
|
1446
|
-
insertText: 'std::tuple<${1:int}, ${2:std::string}> ${3:t};',
|
|
1447
|
-
header: '<tuple>',
|
|
1448
|
-
complexity: 'O(1)'
|
|
1449
|
-
},
|
|
1450
|
-
'std::sort': {
|
|
1451
|
-
label: 'std::sort',
|
|
1452
|
-
detail: 'void sort(RandomIt first, RandomIt last, Compare comp = {});',
|
|
1453
|
-
documentation: 'Sorts elements in range [first, last) in non-descending order (IntroSort).\n\n- Header: `<algorithm>`\n- Complexity: $O(N \\log N)$ comparisons',
|
|
1454
|
-
insertText: 'std::sort(${1:vec}.begin(), ${1:vec}.end());',
|
|
1455
|
-
header: '<algorithm>',
|
|
1456
|
-
complexity: 'O(N log N)'
|
|
1457
|
-
},
|
|
1458
|
-
'std::lower_bound': {
|
|
1459
|
-
label: 'std::lower_bound',
|
|
1460
|
-
detail: 'ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value);',
|
|
1461
|
-
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',
|
|
1462
|
-
insertText: 'std::lower_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
|
|
1463
|
-
header: '<algorithm>',
|
|
1464
|
-
complexity: 'O(log N)'
|
|
1465
|
-
},
|
|
1466
|
-
'std::upper_bound': {
|
|
1467
|
-
label: 'std::upper_bound',
|
|
1468
|
-
detail: 'ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value);',
|
|
1469
|
-
documentation: 'Returns iterator to the first element that is strictly greater than value.\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$ comparisons',
|
|
1470
|
-
insertText: 'std::upper_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
|
|
1471
|
-
header: '<algorithm>',
|
|
1472
|
-
complexity: 'O(log N)'
|
|
1473
|
-
},
|
|
1474
|
-
'std::binary_search': {
|
|
1475
|
-
label: 'std::binary_search',
|
|
1476
|
-
detail: 'bool binary_search(ForwardIt first, ForwardIt last, const T& value);',
|
|
1477
|
-
documentation: 'Checks if value exists in sorted range [first, last).\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$',
|
|
1478
|
-
insertText: 'std::binary_search(${1:vec}.begin(), ${1:vec}.end(), ${2:val});',
|
|
1479
|
-
header: '<algorithm>',
|
|
1480
|
-
complexity: 'O(log N)'
|
|
1481
|
-
},
|
|
1482
|
-
'std::next_permutation': {
|
|
1483
|
-
label: 'std::next_permutation',
|
|
1484
|
-
detail: 'bool next_permutation(BidirIt first, BidirIt last);',
|
|
1485
|
-
documentation: 'Rearranges elements into the lexicographically next greater permutation.\n\n- Header: `<algorithm>`\n- Complexity: $O(N)$',
|
|
1486
|
-
insertText: 'std::next_permutation(${1:vec}.begin(), ${1:vec}.end());',
|
|
1487
|
-
header: '<algorithm>',
|
|
1488
|
-
complexity: 'O(N)'
|
|
1489
|
-
},
|
|
1490
|
-
'std::accumulate': {
|
|
1491
|
-
label: 'std::accumulate',
|
|
1492
|
-
detail: 'T accumulate(InputIt first, InputIt last, T init);',
|
|
1493
|
-
documentation: 'Computes sum of the given value init and elements in range [first, last).\n\n- Header: `<numeric>`\n- Complexity: $O(N)$',
|
|
1494
|
-
insertText: 'std::accumulate(${1:vec}.begin(), ${1:vec}.end(), ${2:0});',
|
|
1495
|
-
header: '<numeric>',
|
|
1496
|
-
complexity: 'O(N)'
|
|
1497
|
-
},
|
|
1498
|
-
'std::gcd': {
|
|
1499
|
-
label: 'std::gcd',
|
|
1500
|
-
detail: 'constexpr common_type_t<M, N> gcd(M m, N n);',
|
|
1501
|
-
documentation: 'Computes greatest common divisor of m and n (Euclidean algorithm).\n\n- Header: `<numeric>`\n- Complexity: $O(\\log(\\min(m, n)))$',
|
|
1502
|
-
insertText: 'std::gcd(${1:a}, ${2:b});',
|
|
1503
|
-
header: '<numeric>',
|
|
1504
|
-
complexity: 'O(log(min(a, b)))'
|
|
1505
|
-
},
|
|
1506
|
-
'ListNode': {
|
|
1507
|
-
label: 'ListNode',
|
|
1508
|
-
detail: 'struct ListNode { int val; ListNode* next; ... };',
|
|
1509
|
-
documentation: 'Standard LeetCode / DSA singly linked list node.\n\n- Header: `<codelab/dsa.hpp>`',
|
|
1510
|
-
insertText: 'ListNode* ${1:head} = new ListNode(${2:0});',
|
|
1511
|
-
header: '<codelab/dsa.hpp>',
|
|
1512
|
-
complexity: 'O(1) allocation'
|
|
1513
|
-
},
|
|
1514
|
-
'TreeNode': {
|
|
1515
|
-
label: 'TreeNode',
|
|
1516
|
-
detail: 'struct TreeNode { int val; TreeNode* left; TreeNode* right; ... };',
|
|
1517
|
-
documentation: 'Standard LeetCode / DSA binary tree node.\n\n- Header: `<codelab/dsa.hpp>`',
|
|
1518
|
-
insertText: 'TreeNode* ${1:root} = new TreeNode(${2:0});',
|
|
1519
|
-
header: '<codelab/dsa.hpp>',
|
|
1520
|
-
complexity: 'O(1) allocation'
|
|
1521
|
-
},
|
|
1522
|
-
'buildLinkedList': {
|
|
1523
|
-
label: 'buildLinkedList',
|
|
1524
|
-
detail: 'ListNode* buildLinkedList(const std::vector<int>& values);',
|
|
1525
|
-
documentation: 'Constructs a singly linked list from a std::vector of integers.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
|
|
1526
|
-
insertText: 'buildLinkedList({${1:1, 2, 3}});',
|
|
1527
|
-
header: '<codelab/dsa.hpp>',
|
|
1528
|
-
complexity: 'O(N)'
|
|
1529
|
-
},
|
|
1530
|
-
'linkedListToVector': {
|
|
1531
|
-
label: 'linkedListToVector',
|
|
1532
|
-
detail: 'std::vector<int> linkedListToVector(const ListNode* head);',
|
|
1533
|
-
documentation: 'Traverses a linked list and collects node values into a std::vector.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$',
|
|
1534
|
-
insertText: 'linkedListToVector(${1:head});',
|
|
1535
|
-
header: '<codelab/dsa.hpp>',
|
|
1536
|
-
complexity: 'O(N)'
|
|
1537
|
-
},
|
|
1538
|
-
'buildBinaryTree': {
|
|
1539
|
-
label: 'buildBinaryTree',
|
|
1540
|
-
detail: 'TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN);',
|
|
1541
|
-
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)$',
|
|
1542
|
-
insertText: 'buildBinaryTree({${1:1, 2, 3}});',
|
|
1543
|
-
header: '<codelab/dsa.hpp>',
|
|
1544
|
-
complexity: 'O(N)'
|
|
1545
|
-
},
|
|
1546
|
-
'DESCRIBE': {
|
|
1547
|
-
label: 'DESCRIBE',
|
|
1548
|
-
detail: 'DESCRIBE(suite_name)',
|
|
1549
|
-
documentation: 'Defines a named test suite in the CodeLab test harness.\n\n- Header: `<codelab/test.hpp>`',
|
|
1550
|
-
insertText: 'DESCRIBE("${1:Suite Name}");\n',
|
|
1551
|
-
header: '<codelab/test.hpp>',
|
|
1552
|
-
complexity: 'CodeLab Test Suite'
|
|
1553
|
-
},
|
|
1554
|
-
'TEST': {
|
|
1555
|
-
label: 'TEST',
|
|
1556
|
-
detail: 'TEST(test_name, block)',
|
|
1557
|
-
documentation: 'Defines and runs a single test case within the active suite.\n\n- Header: `<codelab/test.hpp>`',
|
|
1558
|
-
insertText: 'TEST("${1:should pass}", {\n ASSERT_EQ(${2:actual}, ${3:expected});\n});',
|
|
1559
|
-
header: '<codelab/test.hpp>',
|
|
1560
|
-
complexity: 'CodeLab Test Runner'
|
|
1561
|
-
},
|
|
1562
|
-
'ASSERT_EQ': {
|
|
1563
|
-
label: 'ASSERT_EQ',
|
|
1564
|
-
detail: 'ASSERT_EQ(actual, expected)',
|
|
1565
|
-
documentation: 'Asserts that actual == expected; logs failure message and stack if not.\n\n- Header: `<codelab/test.hpp>`',
|
|
1566
|
-
insertText: 'ASSERT_EQ(${1:actual}, ${2:expected});',
|
|
1567
|
-
header: '<codelab/test.hpp>',
|
|
1568
|
-
complexity: 'Assertion'
|
|
1569
|
-
},
|
|
1570
|
-
'ASSERT_TRUE': {
|
|
1571
|
-
label: 'ASSERT_TRUE',
|
|
1572
|
-
detail: 'ASSERT_TRUE(condition)',
|
|
1573
|
-
documentation: 'Asserts that condition evaluates to true.\n\n- Header: `<codelab/test.hpp>`',
|
|
1574
|
-
insertText: 'ASSERT_TRUE(${1:condition});',
|
|
1575
|
-
header: '<codelab/test.hpp>',
|
|
1576
|
-
complexity: 'Assertion'
|
|
1577
|
-
},
|
|
1578
|
-
'ASSERT_FALSE': {
|
|
1579
|
-
label: 'ASSERT_FALSE',
|
|
1580
|
-
detail: 'ASSERT_FALSE(condition)',
|
|
1581
|
-
documentation: 'Asserts that condition evaluates to false.\n\n- Header: `<codelab/test.hpp>`',
|
|
1582
|
-
insertText: 'ASSERT_FALSE(${1:condition});',
|
|
1583
|
-
header: '<codelab/test.hpp>',
|
|
1584
|
-
complexity: 'Assertion'
|
|
1585
|
-
},
|
|
1586
|
-
'ASSERT_NE': {
|
|
1587
|
-
label: 'ASSERT_NE',
|
|
1588
|
-
detail: 'ASSERT_NE(actual, expected)',
|
|
1589
|
-
documentation: 'Asserts that actual != expected.\n\n- Header: `<codelab/test.hpp>`',
|
|
1590
|
-
insertText: 'ASSERT_NE(${1:actual}, ${2:expected});',
|
|
1591
|
-
header: '<codelab/test.hpp>',
|
|
1592
|
-
complexity: 'Assertion'
|
|
1593
|
-
},
|
|
1594
|
-
'CODELAB_TEST_EXIT_CODE': {
|
|
1595
|
-
label: 'CODELAB_TEST_EXIT_CODE',
|
|
1596
|
-
detail: 'CODELAB_TEST_EXIT_CODE()',
|
|
1597
|
-
documentation: 'Returns 0 if all tests passed, 1 if any failed.\n\n- Header: `<codelab/test.hpp>`',
|
|
1598
|
-
insertText: 'return CODELAB_TEST_EXIT_CODE();',
|
|
1599
|
-
header: '<codelab/test.hpp>',
|
|
1600
|
-
complexity: 'Exit Code'
|
|
1601
|
-
}
|
|
1602
|
-
};
|
|
1603
|
-
|
|
1604
|
-
let _cppWorkspaceFilesGetter: (() => Record<string, string>) | null = null;
|
|
1605
|
-
const _monacoCppInstances = new WeakSet<object>();
|
|
1606
|
-
|
|
1607
|
-
const CPP_STL_CONTAINER_MEMBERS: Record<string, Array<{ name: string; detail: string; insert?: string; doc: string }>> = {
|
|
1608
|
-
vector: [
|
|
1609
|
-
{ 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).' },
|
|
1610
|
-
{ name: 'emplace_back', detail: 'T& emplace_back(Args&&... args)', insert: 'emplace_back(${1:args})', doc: 'Constructs an element in-place at the end.' },
|
|
1611
|
-
{ name: 'pop_back', detail: 'void pop_back()', insert: 'pop_back()', doc: 'Removes the last element ($O(1)$).' },
|
|
1612
|
-
{ name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns the number of elements.' },
|
|
1613
|
-
{ name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Checks whether the container is empty.' },
|
|
1614
|
-
{ name: 'clear', detail: 'void clear() noexcept', insert: 'clear()', doc: 'Clears the contents.' },
|
|
1615
|
-
{ name: 'begin', detail: 'iterator begin() noexcept', insert: 'begin()', doc: 'Returns an iterator to the beginning.' },
|
|
1616
|
-
{ name: 'end', detail: 'iterator end() noexcept', insert: 'end()', doc: 'Returns an iterator to the end.' },
|
|
1617
|
-
{ name: 'front', detail: 'T& front()', insert: 'front()', doc: 'Accesses the first element.' },
|
|
1618
|
-
{ name: 'back', detail: 'T& back()', insert: 'back()', doc: 'Accesses the last element.' },
|
|
1619
|
-
{ name: 'resize', detail: 'void resize(size_t count)', insert: 'resize(${1:n})', doc: 'Resizes the container to contain count elements.' },
|
|
1620
|
-
{ name: 'reserve', detail: 'void reserve(size_t new_cap)', insert: 'reserve(${1:cap})', doc: 'Reserves storage capacity.' }
|
|
1621
|
-
],
|
|
1622
|
-
string: [
|
|
1623
|
-
{ name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns character count.' },
|
|
1624
|
-
{ name: 'length', detail: 'size_t length() const noexcept', insert: 'length()', doc: 'Returns character count.' },
|
|
1625
|
-
{ name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Returns true if string is empty.' },
|
|
1626
|
-
{ name: 'substr', detail: 'string substr(size_t pos = 0, size_t count = npos) const', insert: 'substr(${1:pos}, ${2:len})', doc: 'Returns a substring.' },
|
|
1627
|
-
{ 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`.' },
|
|
1628
|
-
{ name: 'push_back', detail: 'void push_back(char ch)', insert: 'push_back(${1:ch})', doc: 'Appends a character.' },
|
|
1629
|
-
{ name: 'c_str', detail: 'const char* c_str() const noexcept', insert: 'c_str()', doc: 'Returns null-terminated character array.' },
|
|
1630
|
-
{ name: 'begin', detail: 'iterator begin() noexcept', insert: 'begin()', doc: 'Iterator to start.' },
|
|
1631
|
-
{ name: 'end', detail: 'iterator end() noexcept', insert: 'end()', doc: 'Iterator past end.' }
|
|
1632
|
-
],
|
|
1633
|
-
map: [
|
|
1634
|
-
{ name: 'insert', detail: 'pair<iterator, bool> insert(const value_type& value)', insert: 'insert({${1:key}, ${2:val}})', doc: 'Inserts key-value pair.' },
|
|
1635
|
-
{ name: 'emplace', detail: 'pair<iterator, bool> emplace(Args&&... args)', insert: 'emplace(${1:key}, ${2:val})', doc: 'Constructs element in-place.' },
|
|
1636
|
-
{ name: 'find', detail: 'iterator find(const Key& key)', insert: 'find(${1:key})', doc: 'Finds element with specific key.' },
|
|
1637
|
-
{ name: 'count', detail: 'size_t count(const Key& key) const', insert: 'count(${1:key})', doc: 'Returns 1 if key exists, 0 otherwise.' },
|
|
1638
|
-
{ 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).' },
|
|
1639
|
-
{ name: 'erase', detail: 'size_t erase(const Key& key)', insert: 'erase(${1:key})', doc: 'Removes element by key or iterator.' },
|
|
1640
|
-
{ name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns number of entries.' },
|
|
1641
|
-
{ name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Checks if container is empty.' },
|
|
1642
|
-
{ name: 'begin', detail: 'iterator begin() noexcept', insert: 'begin()', doc: 'Iterator to first entry.' },
|
|
1643
|
-
{ name: 'end', detail: 'iterator end() noexcept', insert: 'end()', doc: 'Iterator past last entry.' }
|
|
1644
|
-
],
|
|
1645
|
-
set: [
|
|
1646
|
-
{ name: 'insert', detail: 'pair<iterator, bool> insert(const Key& value)', insert: 'insert(${1:val})', doc: 'Inserts element into set.' },
|
|
1647
|
-
{ name: 'find', detail: 'iterator find(const Key& key)', insert: 'find(${1:val})', doc: 'Finds element matching key.' },
|
|
1648
|
-
{ name: 'count', detail: 'size_t count(const Key& key) const', insert: 'count(${1:val})', doc: 'Returns number of matching elements.' },
|
|
1649
|
-
{ name: 'contains', detail: 'bool contains(const Key& key) const (C++20)', insert: 'contains(${1:val})', doc: 'Checks if element exists (C++20).' },
|
|
1650
|
-
{ name: 'erase', detail: 'size_t erase(const Key& key)', insert: 'erase(${1:val})', doc: 'Erases element.' },
|
|
1651
|
-
{ name: 'size', detail: 'size_t size() const noexcept', insert: 'size()', doc: 'Returns size.' },
|
|
1652
|
-
{ name: 'empty', detail: 'bool empty() const noexcept', insert: 'empty()', doc: 'Checks if empty.' }
|
|
1653
|
-
],
|
|
1654
|
-
queue: [
|
|
1655
|
-
{ name: 'push', detail: 'void push(const T& value)', insert: 'push(${1:val})', doc: 'Inserts element at back of queue.' },
|
|
1656
|
-
{ name: 'pop', detail: 'void pop()', insert: 'pop()', doc: 'Removes front/top element.' },
|
|
1657
|
-
{ name: 'front', detail: 'T& front()', insert: 'front()', doc: 'Accesses first element (queue).' },
|
|
1658
|
-
{ name: 'top', detail: 'const T& top() const', insert: 'top()', doc: 'Accesses top element (priority_queue / stack).' },
|
|
1659
|
-
{ name: 'empty', detail: 'bool empty() const', insert: 'empty()', doc: 'Checks whether underlying container is empty.' },
|
|
1660
|
-
{ name: 'size', detail: 'size_t size() const', insert: 'size()', doc: 'Returns number of elements.' }
|
|
1661
|
-
],
|
|
1662
|
-
ListNode: [
|
|
1663
|
-
{ name: 'val', detail: 'int val', insert: 'val', doc: 'Node integer value.' },
|
|
1664
|
-
{ name: 'next', detail: 'ListNode* next', insert: 'next', doc: 'Pointer to next node in singly-linked list.' }
|
|
1665
|
-
],
|
|
1666
|
-
TreeNode: [
|
|
1667
|
-
{ name: 'val', detail: 'int val', insert: 'val', doc: 'Node integer value.' },
|
|
1668
|
-
{ name: 'left', detail: 'TreeNode* left', insert: 'left', doc: 'Left child pointer.' },
|
|
1669
|
-
{ name: 'right', detail: 'TreeNode* right', insert: 'right', doc: 'Right child pointer.' }
|
|
1670
|
-
]
|
|
1671
|
-
};
|
|
1672
|
-
|
|
1673
|
-
function inferCppLocalContainerKind(source: string, ident: string): string | null {
|
|
1674
|
-
const escaped = ident.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1675
|
-
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`);
|
|
1676
|
-
const m = source.match(declRe);
|
|
1677
|
-
if (!m) return null;
|
|
1678
|
-
const raw = m[1];
|
|
1679
|
-
if (raw === 'unordered_map' || raw === 'map') return 'map';
|
|
1680
|
-
if (raw === 'unordered_set' || raw === 'set') return 'set';
|
|
1681
|
-
if (raw === 'priority_queue' || raw === 'queue' || raw === 'stack') return 'queue';
|
|
1682
|
-
return raw;
|
|
1683
|
-
}
|
|
1684
|
-
|
|
1685
|
-
function collectWorkspaceCppSymbols(currentSource: string, currentPath = 'main.cpp') {
|
|
1686
|
-
const files: Record<string, string> = _cppWorkspaceFilesGetter ? { ...(_cppWorkspaceFilesGetter() || {}) } : {};
|
|
1687
|
-
const cleanCurrent = String(currentPath || 'main.cpp').replace(/^file:\/\/\/workspace\//, '').replace(/^\/workspace\//, '').replace(/^\/+/, '') || 'main.cpp';
|
|
1688
|
-
if (currentSource) files[cleanCurrent] = currentSource;
|
|
1689
|
-
|
|
1690
|
-
const symbols: Array<{ name: string; kind: 'function' | 'struct' | 'class'; detail: string; file: string; line: number; col: number; params: string[] }> = [];
|
|
1691
|
-
for (const [filePath, src] of Object.entries(files)) {
|
|
1692
|
-
if (!/\.(?:cpp|cc|cxx|c|h|hpp|hxx)$/i.test(filePath)) continue;
|
|
1693
|
-
const lines = String(src || '').split('\n');
|
|
1694
|
-
for (let i = 0; i < lines.length; i++) {
|
|
1695
|
-
const line = lines[i];
|
|
1696
|
-
const trimmed = line.trim();
|
|
1697
|
-
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#')) continue;
|
|
1698
|
-
const scMatch = line.match(/^\s*(struct|class)\s+([A-Za-z_][A-Za-z0-9_]*)/);
|
|
1699
|
-
if (scMatch) {
|
|
1700
|
-
symbols.push({
|
|
1701
|
-
name: scMatch[2],
|
|
1702
|
-
kind: scMatch[1] as 'struct' | 'class',
|
|
1703
|
-
detail: `${scMatch[1]} ${scMatch[2]}`,
|
|
1704
|
-
file: filePath,
|
|
1705
|
-
line: i + 1,
|
|
1706
|
-
col: line.indexOf(scMatch[2]) + 1,
|
|
1707
|
-
params: []
|
|
1708
|
-
});
|
|
1709
|
-
continue;
|
|
1710
|
-
}
|
|
1711
|
-
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*)?[{;]/);
|
|
1712
|
-
if (fnMatch && !/^(?:if|for|while|switch|catch|return)$/.test(fnMatch[2])) {
|
|
1713
|
-
const ret = fnMatch[1].trim();
|
|
1714
|
-
const name = fnMatch[2];
|
|
1715
|
-
const rawParams = fnMatch[3].trim();
|
|
1716
|
-
symbols.push({
|
|
1717
|
-
name,
|
|
1718
|
-
kind: 'function',
|
|
1719
|
-
detail: `${ret} ${name}(${rawParams})`,
|
|
1720
|
-
file: filePath,
|
|
1721
|
-
line: i + 1,
|
|
1722
|
-
col: line.indexOf(name) + 1,
|
|
1723
|
-
params: rawParams ? rawParams.split(',').map((p) => p.trim()).filter(Boolean) : []
|
|
1724
|
-
});
|
|
1725
|
-
}
|
|
1726
|
-
}
|
|
1727
|
-
}
|
|
1728
|
-
return symbols;
|
|
1729
|
-
}
|
|
1730
|
-
|
|
1731
|
-
/**
|
|
1732
|
-
* Registers Monaco C++20 completion, STL member completion, hover, signature help, and definition providers.
|
|
1733
|
-
*/
|
|
1734
|
-
export function registerMonacoCppLanguageService(
|
|
1735
|
-
monacoInstance: any,
|
|
1736
|
-
getWorkspaceFiles?: () => Record<string, string>
|
|
1737
|
-
): boolean {
|
|
1738
|
-
if (typeof getWorkspaceFiles === 'function') {
|
|
1739
|
-
_cppWorkspaceFilesGetter = getWorkspaceFiles;
|
|
1740
|
-
}
|
|
1741
|
-
if (!monacoInstance || !monacoInstance.languages) return false;
|
|
1742
|
-
if (_monacoCppInstances.has(monacoInstance)) return true;
|
|
1743
|
-
_monacoCppInstances.add(monacoInstance);
|
|
1744
|
-
|
|
1745
|
-
try {
|
|
1746
|
-
const CIK = monacoInstance.languages.CompletionItemKind || {};
|
|
1747
|
-
const CITR = monacoInstance.languages.CompletionItemInsertTextRule || {};
|
|
1748
|
-
|
|
1749
|
-
monacoInstance.languages.registerCompletionItemProvider('cpp', {
|
|
1750
|
-
triggerCharacters: ['.', ':', '>', '<'],
|
|
1751
|
-
provideCompletionItems(model: any, position: any) {
|
|
1752
|
-
const wordInfo = model.getWordUntilPosition(position);
|
|
1753
|
-
const range = {
|
|
1754
|
-
startLineNumber: position.lineNumber,
|
|
1755
|
-
endLineNumber: position.lineNumber,
|
|
1756
|
-
startColumn: wordInfo.startColumn,
|
|
1757
|
-
endColumn: wordInfo.endColumn
|
|
1758
|
-
};
|
|
1759
|
-
const fullSource = typeof model.getValue === 'function' ? model.getValue() : '';
|
|
1760
|
-
const linePrefix = typeof model.getLineContent === 'function'
|
|
1761
|
-
? String(model.getLineContent(position.lineNumber) || '').slice(0, position.column - 1)
|
|
1762
|
-
: '';
|
|
1763
|
-
|
|
1764
|
-
// Member access `vec.` or `node->`
|
|
1765
|
-
const memberMatch = linePrefix.match(/([A-Za-z_][A-Za-z0-9_]*)\s*(?:\.|->)\s*[A-Za-z0-9_]*$/);
|
|
1766
|
-
if (memberMatch) {
|
|
1767
|
-
const containerKind = inferCppLocalContainerKind(fullSource, memberMatch[1]);
|
|
1768
|
-
const members = containerKind ? CPP_STL_CONTAINER_MEMBERS[containerKind] : null;
|
|
1769
|
-
if (members) {
|
|
1770
|
-
return {
|
|
1771
|
-
suggestions: members.map((m) => ({
|
|
1772
|
-
label: m.name,
|
|
1773
|
-
kind: m.insert?.includes('(') ? (CIK.Method ?? 0) : (CIK.Field ?? 4),
|
|
1774
|
-
detail: m.detail,
|
|
1775
|
-
documentation: { value: m.doc },
|
|
1776
|
-
insertText: m.insert || m.name,
|
|
1777
|
-
insertTextRules: CITR.InsertAsSnippet,
|
|
1778
|
-
range
|
|
1779
|
-
}))
|
|
1780
|
-
};
|
|
1781
|
-
}
|
|
1782
|
-
}
|
|
1783
|
-
|
|
1784
|
-
const seen = new Set<string>();
|
|
1785
|
-
const suggestions = Object.keys(CPP_COMPLETIONS_AND_HOVERS).map((key) => {
|
|
1786
|
-
const item = CPP_COMPLETIONS_AND_HOVERS[key];
|
|
1787
|
-
seen.add(item.label);
|
|
1788
|
-
return {
|
|
1789
|
-
label: item.label,
|
|
1790
|
-
kind: CIK.Function ?? 1,
|
|
1791
|
-
detail: item.detail,
|
|
1792
|
-
documentation: { value: item.documentation },
|
|
1793
|
-
insertText: item.insertText || item.label,
|
|
1794
|
-
insertTextRules: CITR.InsertAsSnippet,
|
|
1795
|
-
range
|
|
1796
|
-
};
|
|
1797
|
-
});
|
|
1798
|
-
|
|
1799
|
-
const wsSyms = collectWorkspaceCppSymbols(fullSource, model.uri?.path || 'main.cpp');
|
|
1800
|
-
for (const sym of wsSyms) {
|
|
1801
|
-
if (seen.has(sym.name)) continue;
|
|
1802
|
-
seen.add(sym.name);
|
|
1803
|
-
suggestions.push({
|
|
1804
|
-
label: sym.name,
|
|
1805
|
-
kind: sym.kind === 'function' ? (CIK.Function ?? 1) : (CIK.Struct ?? 6),
|
|
1806
|
-
detail: sym.detail,
|
|
1807
|
-
documentation: { value: `Defined in \`${sym.file}:${sym.line}\`` },
|
|
1808
|
-
insertText: sym.kind === 'function' ? `${sym.name}(${sym.params.length ? '$1' : ''})` : sym.name,
|
|
1809
|
-
insertTextRules: CITR.InsertAsSnippet,
|
|
1810
|
-
range
|
|
1811
|
-
});
|
|
1812
|
-
}
|
|
1813
|
-
|
|
1814
|
-
return { suggestions };
|
|
1815
|
-
}
|
|
1816
|
-
});
|
|
1817
|
-
|
|
1818
|
-
monacoInstance.languages.registerHoverProvider('cpp', {
|
|
1819
|
-
provideHover(model: any, position: any) {
|
|
1820
|
-
const word = model.getWordAtPosition(position);
|
|
1821
|
-
if (!word) return null;
|
|
1822
|
-
|
|
1823
|
-
const key = CPP_COMPLETIONS_AND_HOVERS[word.word]
|
|
1824
|
-
? word.word
|
|
1825
|
-
: (CPP_COMPLETIONS_AND_HOVERS['std::' + word.word] ? 'std::' + word.word : null);
|
|
1826
|
-
|
|
1827
|
-
if (key) {
|
|
1828
|
-
const item = CPP_COMPLETIONS_AND_HOVERS[key];
|
|
1829
|
-
return {
|
|
1830
|
-
range: {
|
|
1831
|
-
startLineNumber: position.lineNumber,
|
|
1832
|
-
endLineNumber: position.lineNumber,
|
|
1833
|
-
startColumn: word.startColumn,
|
|
1834
|
-
endColumn: word.endColumn
|
|
1835
|
-
},
|
|
1836
|
-
contents: [
|
|
1837
|
-
{ value: `**${item.label}** — \`${item.detail}\`` },
|
|
1838
|
-
{ value: item.documentation }
|
|
1839
|
-
]
|
|
1840
|
-
};
|
|
1841
|
-
}
|
|
1842
|
-
|
|
1843
|
-
const wsSyms = collectWorkspaceCppSymbols(model.getValue?.() || '', model.uri?.path || 'main.cpp');
|
|
1844
|
-
const wsHit = wsSyms.find((s) => s.name === word.word);
|
|
1845
|
-
if (wsHit) {
|
|
1846
|
-
return {
|
|
1847
|
-
range: {
|
|
1848
|
-
startLineNumber: position.lineNumber,
|
|
1849
|
-
endLineNumber: position.lineNumber,
|
|
1850
|
-
startColumn: word.startColumn,
|
|
1851
|
-
endColumn: word.endColumn
|
|
1852
|
-
},
|
|
1853
|
-
contents: [
|
|
1854
|
-
{ value: `\`\`\`cpp\n${wsHit.detail}\n\`\`\`` },
|
|
1855
|
-
{ value: `Defined in \`${wsHit.file}:${wsHit.line}\`` }
|
|
1856
|
-
]
|
|
1857
|
-
};
|
|
1858
|
-
}
|
|
1859
|
-
return null;
|
|
1860
|
-
}
|
|
1861
|
-
});
|
|
1862
|
-
|
|
1863
|
-
if (typeof monacoInstance.languages.registerDefinitionProvider === 'function' && monacoInstance.Uri) {
|
|
1864
|
-
monacoInstance.languages.registerDefinitionProvider('cpp', {
|
|
1865
|
-
provideDefinition(model: any, position: any) {
|
|
1866
|
-
const word = model.getWordAtPosition(position);
|
|
1867
|
-
if (!word) return null;
|
|
1868
|
-
const wsSyms = collectWorkspaceCppSymbols(model.getValue?.() || '', model.uri?.path || 'main.cpp');
|
|
1869
|
-
const hit = wsSyms.find((s) => s.name === word.word);
|
|
1870
|
-
if (!hit) return null;
|
|
1871
|
-
const uri = typeof monacoInstance.Uri.file === 'function'
|
|
1872
|
-
? monacoInstance.Uri.file('/workspace/' + hit.file.replace(/^\/+/, ''))
|
|
1873
|
-
: model.uri;
|
|
1874
|
-
return {
|
|
1875
|
-
uri,
|
|
1876
|
-
range: {
|
|
1877
|
-
startLineNumber: hit.line,
|
|
1878
|
-
startColumn: hit.col,
|
|
1879
|
-
endLineNumber: hit.line,
|
|
1880
|
-
endColumn: hit.col + hit.name.length
|
|
1881
|
-
}
|
|
1882
|
-
};
|
|
1883
|
-
}
|
|
1884
|
-
});
|
|
1885
|
-
}
|
|
1886
|
-
|
|
1887
|
-
return true;
|
|
1888
|
-
} catch (err) {
|
|
1889
|
-
if (typeof console !== 'undefined' && console.warn) {
|
|
1890
|
-
console.warn('[C++ Monaco Intelligence Error]:', err);
|
|
1891
|
-
}
|
|
1892
|
-
return false;
|
|
1893
|
-
}
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
|
-
/**
|
|
1897
|
-
* Real-time C++20 static AST/syntax linter.
|
|
1898
|
-
* Debounced on keystroke in `.cpp`, `.cc`, `.cxx`, `.hpp`, `.h` files.
|
|
1899
|
-
*/
|
|
1900
|
-
export function analyzeCppSource(source: string, filename = 'main.cpp', vfs?: any): DiagnosticItem[] {
|
|
1901
|
-
const diagnostics: DiagnosticItem[] = [];
|
|
1902
|
-
if (!source || typeof source !== 'string') return diagnostics;
|
|
1903
|
-
|
|
1904
|
-
const lines = source.split('\n');
|
|
1905
|
-
|
|
1906
|
-
// 1. Bracket stack matching: {}, (), []
|
|
1907
|
-
const stack: Array<{ char: string; line: number; col: number }> = [];
|
|
1908
|
-
const matchingPairs: Record<string, string> = { '}': '{', ')': '(', ']': '[' };
|
|
1909
|
-
|
|
1910
|
-
let inBlockComment = false;
|
|
1911
|
-
for (let l = 0; l < lines.length; l++) {
|
|
1912
|
-
const line = lines[l];
|
|
1913
|
-
const lineNum = l + 1;
|
|
1914
|
-
let inString = false;
|
|
1915
|
-
let inChar = false;
|
|
1916
|
-
let stringQuote = '';
|
|
1917
|
-
|
|
1918
|
-
for (let c = 0; c < line.length; c++) {
|
|
1919
|
-
const ch = line[c];
|
|
1920
|
-
const next = line[c + 1] || '';
|
|
1921
|
-
|
|
1922
|
-
if (inBlockComment) {
|
|
1923
|
-
if (ch === '*' && next === '/') {
|
|
1924
|
-
inBlockComment = false;
|
|
1925
|
-
c++;
|
|
1926
|
-
}
|
|
1927
|
-
continue;
|
|
1928
|
-
}
|
|
1929
|
-
|
|
1930
|
-
if (!inString && !inChar) {
|
|
1931
|
-
if (ch === '/' && next === '*') {
|
|
1932
|
-
inBlockComment = true;
|
|
1933
|
-
c++;
|
|
1934
|
-
continue;
|
|
1935
|
-
}
|
|
1936
|
-
if (ch === '/' && next === '/') {
|
|
1937
|
-
break; // Rest of line is comment
|
|
1938
|
-
}
|
|
1939
|
-
}
|
|
1940
|
-
|
|
1941
|
-
// Check string & char literal bounds
|
|
1942
|
-
if (!inChar && (ch === '"' || (ch === 'R' && next === '"'))) {
|
|
1943
|
-
if (ch === 'R') c++; // Raw string literal prefix
|
|
1944
|
-
if (c === 0 || line[c - 1] !== '\\') {
|
|
1945
|
-
inString = !inString;
|
|
1946
|
-
stringQuote = inString ? '"' : '';
|
|
1947
|
-
}
|
|
1948
|
-
continue;
|
|
1949
|
-
}
|
|
1950
|
-
|
|
1951
|
-
if (!inString && ch === '\'') {
|
|
1952
|
-
if (c === 0 || line[c - 1] !== '\\') {
|
|
1953
|
-
inChar = !inChar;
|
|
1954
|
-
}
|
|
1955
|
-
continue;
|
|
1956
|
-
}
|
|
1957
|
-
|
|
1958
|
-
if (inString || inChar) continue;
|
|
1959
|
-
|
|
1960
|
-
if (ch === '{' || ch === '(' || ch === '[') {
|
|
1961
|
-
stack.push({ char: ch, line: lineNum, col: c + 1 });
|
|
1962
|
-
} else if (ch === '}' || ch === ')' || ch === ']') {
|
|
1963
|
-
const expectedOpening = matchingPairs[ch];
|
|
1964
|
-
const last = stack.pop();
|
|
1965
|
-
if (!last) {
|
|
1966
|
-
diagnostics.push({
|
|
1967
|
-
id: `cpp-bracket-unmatched-${lineNum}-${c + 1}`,
|
|
1968
|
-
file: filename,
|
|
1969
|
-
line: lineNum,
|
|
1970
|
-
col: c + 1,
|
|
1971
|
-
severity: 'error',
|
|
1972
|
-
message: `Unmatched closing bracket '${ch}' with no opening counterpart.`,
|
|
1973
|
-
source: 'cpp-linter'
|
|
1974
|
-
});
|
|
1975
|
-
} else if (last.char !== expectedOpening) {
|
|
1976
|
-
diagnostics.push({
|
|
1977
|
-
id: `cpp-bracket-mismatch-${lineNum}-${c + 1}`,
|
|
1978
|
-
file: filename,
|
|
1979
|
-
line: lineNum,
|
|
1980
|
-
col: c + 1,
|
|
1981
|
-
severity: 'error',
|
|
1982
|
-
message: `Mismatched bracket: found '${ch}' but expected closing for '${last.char}' from line ${last.line}.`,
|
|
1983
|
-
source: 'cpp-linter'
|
|
1984
|
-
});
|
|
1985
|
-
}
|
|
1986
|
-
}
|
|
1987
|
-
}
|
|
1988
|
-
|
|
1989
|
-
if (inString && !inBlockComment) {
|
|
1990
|
-
diagnostics.push({
|
|
1991
|
-
id: `cpp-string-unterminated-${lineNum}`,
|
|
1992
|
-
file: filename,
|
|
1993
|
-
line: lineNum,
|
|
1994
|
-
col: line.length,
|
|
1995
|
-
severity: 'error',
|
|
1996
|
-
message: 'Unterminated string literal on line.',
|
|
1997
|
-
source: 'cpp-linter'
|
|
1998
|
-
});
|
|
1999
|
-
}
|
|
2000
|
-
}
|
|
2001
|
-
|
|
2002
|
-
for (const unclosed of stack) {
|
|
2003
|
-
diagnostics.push({
|
|
2004
|
-
id: `cpp-bracket-unclosed-${unclosed.line}-${unclosed.col}`,
|
|
2005
|
-
file: filename,
|
|
2006
|
-
line: unclosed.line,
|
|
2007
|
-
col: unclosed.col,
|
|
2008
|
-
severity: 'error',
|
|
2009
|
-
message: `Unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
|
|
2010
|
-
source: 'cpp-linter'
|
|
2011
|
-
});
|
|
2012
|
-
}
|
|
2013
|
-
|
|
2014
|
-
// 2. Validate #include <...> against C++20 standard library + VFS
|
|
2015
|
-
const includeRegex = /#include\s*([<"])([^>"]+)[>"]/g;
|
|
2016
|
-
let incMatch: RegExpExecArray | null;
|
|
2017
|
-
const includedHeaders = new Set<string>();
|
|
2018
|
-
|
|
2019
|
-
while ((incMatch = includeRegex.exec(source)) !== null) {
|
|
2020
|
-
const isAngle = incMatch[1] === '<';
|
|
2021
|
-
const hdr = incMatch[2].trim();
|
|
2022
|
-
includedHeaders.add(hdr);
|
|
2023
|
-
const lineIndex = source.slice(0, incMatch.index).split('\n').length;
|
|
2024
|
-
|
|
2025
|
-
if (isAngle) {
|
|
2026
|
-
const known = STANDARD_CPP20_HEADERS.has(hdr) ||
|
|
2027
|
-
hdr.startsWith('bits/') ||
|
|
2028
|
-
hdr.startsWith('codelab/') ||
|
|
2029
|
-
(vfs && (vfs.existsSync(`/usr/include/${hdr}`) || vfs.existsSync(`/workspace/${hdr}`)));
|
|
2030
|
-
if (!known) {
|
|
2031
|
-
diagnostics.push({
|
|
2032
|
-
id: `cpp-unknown-include-${lineIndex}`,
|
|
2033
|
-
file: filename,
|
|
2034
|
-
line: lineIndex,
|
|
2035
|
-
col: 1,
|
|
2036
|
-
severity: 'warning',
|
|
2037
|
-
message: `Unknown or unresolvable C++ header <${hdr}>.`,
|
|
2038
|
-
source: 'cpp-linter'
|
|
2039
|
-
});
|
|
2040
|
-
}
|
|
2041
|
-
}
|
|
2042
|
-
}
|
|
2043
|
-
|
|
2044
|
-
// 3. Missing #include checks for DSA utilities and Test harness
|
|
2045
|
-
const hasDsaHeader = includedHeaders.has('codelab/dsa.hpp') || includedHeaders.has('bits/stdc++.h');
|
|
2046
|
-
const dsaSymbols = ['ListNode', 'TreeNode', 'buildLinkedList', 'linkedListToVector', 'buildBinaryTree'];
|
|
2047
|
-
for (const sym of dsaSymbols) {
|
|
2048
|
-
const symRegex = new RegExp(`\\b${sym}\\b`);
|
|
2049
|
-
if (symRegex.test(source) && !hasDsaHeader) {
|
|
2050
|
-
diagnostics.push({
|
|
2051
|
-
id: `cpp-missing-dsa-include-${sym}`,
|
|
2052
|
-
file: filename,
|
|
2053
|
-
line: 1,
|
|
2054
|
-
col: 1,
|
|
2055
|
-
severity: 'warning',
|
|
2056
|
-
message: `Symbol '${sym}' used without #include <codelab/dsa.hpp>.`,
|
|
2057
|
-
source: 'cpp-linter'
|
|
2058
|
-
});
|
|
2059
|
-
break;
|
|
2060
|
-
}
|
|
2061
|
-
}
|
|
2062
|
-
|
|
2063
|
-
const hasTestHeader = includedHeaders.has('codelab/test.hpp');
|
|
2064
|
-
const testSymbols = ['DESCRIBE', 'TEST', 'ASSERT_EQ', 'ASSERT_NE', 'ASSERT_TRUE', 'ASSERT_FALSE', 'CODELAB_TEST_EXIT_CODE'];
|
|
2065
|
-
for (const sym of testSymbols) {
|
|
2066
|
-
const symRegex = new RegExp(`\\b${sym}\\b`);
|
|
2067
|
-
if (symRegex.test(source) && !hasTestHeader) {
|
|
2068
|
-
diagnostics.push({
|
|
2069
|
-
id: `cpp-missing-test-include-${sym}`,
|
|
2070
|
-
file: filename,
|
|
2071
|
-
line: 1,
|
|
2072
|
-
col: 1,
|
|
2073
|
-
severity: 'warning',
|
|
2074
|
-
message: `Test macro '${sym}' used without #include <codelab/test.hpp>.`,
|
|
2075
|
-
source: 'cpp-linter'
|
|
2076
|
-
});
|
|
2077
|
-
break;
|
|
2078
|
-
}
|
|
2079
|
-
}
|
|
2080
|
-
|
|
2081
|
-
// 4. Suspicious assignment inside if condition (e.g. if (x = 5))
|
|
2082
|
-
for (let l = 0; l < lines.length; l++) {
|
|
2083
|
-
const line = lines[l];
|
|
2084
|
-
const assignMatch = /\bif\s*\(([^;)]*[^=!<>]=[^=][^;)]*)\)/.exec(line);
|
|
2085
|
-
if (assignMatch) {
|
|
2086
|
-
diagnostics.push({
|
|
2087
|
-
id: `cpp-suspicious-assign-${l + 1}`,
|
|
2088
|
-
file: filename,
|
|
2089
|
-
line: l + 1,
|
|
2090
|
-
col: assignMatch.index + 1,
|
|
2091
|
-
severity: 'warning',
|
|
2092
|
-
message: `Suspicious assignment '=' inside 'if' condition; did you mean '=='?`,
|
|
2093
|
-
source: 'cpp-linter'
|
|
2094
|
-
});
|
|
2095
|
-
}
|
|
2096
|
-
}
|
|
2097
|
-
|
|
2098
|
-
// 5. Balanced-brace check for missing semicolon after class or struct definitions
|
|
2099
|
-
if (stack.length === 0) {
|
|
2100
|
-
const structHeadRegex = /\b(?:struct|class)\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^{;]*)?\{/g;
|
|
2101
|
-
let structMatch: RegExpExecArray | null;
|
|
2102
|
-
while ((structMatch = structHeadRegex.exec(source)) !== null) {
|
|
2103
|
-
const typeName = structMatch[1];
|
|
2104
|
-
let pos = structMatch.index + structMatch[0].length;
|
|
2105
|
-
let depth = 1;
|
|
2106
|
-
let inStr = false;
|
|
2107
|
-
let inChr = false;
|
|
2108
|
-
let inBlk = false;
|
|
2109
|
-
let inLn = false;
|
|
2110
|
-
while (pos < source.length && depth > 0) {
|
|
2111
|
-
const ch = source[pos];
|
|
2112
|
-
const nx = source[pos + 1] || '';
|
|
2113
|
-
if (inLn) {
|
|
2114
|
-
if (ch === '\n') inLn = false;
|
|
2115
|
-
pos++;
|
|
2116
|
-
continue;
|
|
2117
|
-
}
|
|
2118
|
-
if (inBlk) {
|
|
2119
|
-
if (ch === '*' && nx === '/') { inBlk = false; pos += 2; continue; }
|
|
2120
|
-
pos++;
|
|
2121
|
-
continue;
|
|
2122
|
-
}
|
|
2123
|
-
if (!inStr && !inChr) {
|
|
2124
|
-
if (ch === '/' && nx === '/') { inLn = true; pos += 2; continue; }
|
|
2125
|
-
if (ch === '/' && nx === '*') { inBlk = true; pos += 2; continue; }
|
|
2126
|
-
}
|
|
2127
|
-
if (!inChr && ch === '"' && source[pos - 1] !== '\\') { inStr = !inStr; pos++; continue; }
|
|
2128
|
-
if (!inStr && ch === '\'' && source[pos - 1] !== '\\') { inChr = !inChr; pos++; continue; }
|
|
2129
|
-
if (!inStr && !inChr) {
|
|
2130
|
-
if (ch === '{') depth++;
|
|
2131
|
-
else if (ch === '}') depth--;
|
|
2132
|
-
}
|
|
2133
|
-
pos++;
|
|
2134
|
-
}
|
|
2135
|
-
if (depth === 0) {
|
|
2136
|
-
const afterClose = source.slice(pos).replace(/^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)+/, '');
|
|
2137
|
-
// Valid: `;` immediately OR variable declarators like `p1, *p2;` before next newline/block
|
|
2138
|
-
const validTerminator = /^;|^[A-Za-z_*&][A-Za-z0-9_,\s*&[\]=()]*;/.test(afterClose);
|
|
2139
|
-
if (afterClose.length > 0 && !validTerminator) {
|
|
2140
|
-
const lineIndex = source.slice(0, pos).split('\n').length;
|
|
2141
|
-
diagnostics.push({
|
|
2142
|
-
id: `cpp-missing-semicolon-${lineIndex}`,
|
|
2143
|
-
file: filename,
|
|
2144
|
-
line: lineIndex,
|
|
2145
|
-
col: 1,
|
|
2146
|
-
severity: 'error',
|
|
2147
|
-
message: `Missing semicolon ';' after '${typeName}' class/struct definition.`,
|
|
2148
|
-
source: 'cpp-linter'
|
|
2149
|
-
});
|
|
2150
|
-
}
|
|
2151
|
-
}
|
|
2152
|
-
}
|
|
2153
|
-
}
|
|
2154
|
-
|
|
2155
|
-
return diagnostics;
|
|
2156
|
-
}
|
|
2157
|
-
|
|
2158
|
-
/**
|
|
2159
|
-
* Parses Clang / LLVM WASI compiler stderr and applies diagnostics to Monaco and DiagnosticsStore.
|
|
2160
|
-
*/
|
|
2161
|
-
export function applyClangStderrDiagnostics(
|
|
2162
|
-
stderrText: string,
|
|
2163
|
-
diagnosticsStore?: any,
|
|
2164
|
-
monacoInstance?: any,
|
|
2165
|
-
activeModel?: any
|
|
2166
|
-
): DiagnosticItem[] {
|
|
2167
|
-
const diagnostics: DiagnosticItem[] = [];
|
|
2168
|
-
if (!stderrText || typeof stderrText !== 'string') return diagnostics;
|
|
2169
|
-
|
|
2170
|
-
if (diagnosticsStore && typeof diagnosticsStore.clear === 'function') {
|
|
2171
|
-
diagnosticsStore.clear('clang');
|
|
2172
|
-
}
|
|
2173
|
-
|
|
2174
|
-
const clangRegex = /(?:(?:^|\n)(?:\/workspace\/)?([^\s:\n]+)):(\d+):(\d+):\s*(fatal error|error|warning|note):\s*([^\n]+)/g;
|
|
2175
|
-
let match: RegExpExecArray | null;
|
|
2176
|
-
let idx = 0;
|
|
2177
|
-
|
|
2178
|
-
while ((match = clangRegex.exec(stderrText)) !== null) {
|
|
2179
|
-
const rawFile = match[1].trim();
|
|
2180
|
-
const line = parseInt(match[2], 10) || 1;
|
|
2181
|
-
const col = parseInt(match[3], 10) || 1;
|
|
2182
|
-
const rawKind = match[4].toLowerCase();
|
|
2183
|
-
const message = match[5].trim();
|
|
2184
|
-
|
|
2185
|
-
let severity: 'error' | 'warning' | 'info' = 'error';
|
|
2186
|
-
if (rawKind === 'warning') severity = 'warning';
|
|
2187
|
-
else if (rawKind === 'note') severity = 'info';
|
|
2188
|
-
|
|
2189
|
-
const item: DiagnosticItem = {
|
|
2190
|
-
id: `clang-${rawFile}-${line}-${col}-${idx++}`,
|
|
2191
|
-
file: rawFile,
|
|
2192
|
-
line,
|
|
2193
|
-
col,
|
|
2194
|
-
severity,
|
|
2195
|
-
message: `[Clang] ${message}`,
|
|
2196
|
-
source: 'clang'
|
|
2197
|
-
};
|
|
2198
|
-
diagnostics.push(item);
|
|
2199
|
-
if (diagnosticsStore && typeof diagnosticsStore.add === 'function') {
|
|
2200
|
-
diagnosticsStore.add(item);
|
|
2201
|
-
}
|
|
2202
|
-
}
|
|
2203
|
-
|
|
2204
|
-
if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === 'function') {
|
|
2205
|
-
const markers = diagnostics.map((d) => ({
|
|
2206
|
-
startLineNumber: d.line,
|
|
2207
|
-
startColumn: d.col || 1,
|
|
2208
|
-
endLineNumber: d.line,
|
|
2209
|
-
endColumn: (d.col || 1) + 20,
|
|
2210
|
-
message: d.message,
|
|
2211
|
-
severity: d.severity === 'error'
|
|
2212
|
-
? monacoInstance.MarkerSeverity.Error
|
|
2213
|
-
: (d.severity === 'warning' ? monacoInstance.MarkerSeverity.Warning : monacoInstance.MarkerSeverity.Info)
|
|
2214
|
-
}));
|
|
2215
|
-
monacoInstance.editor.setModelMarkers(activeModel, 'clang', markers);
|
|
2216
|
-
}
|
|
2217
|
-
|
|
2218
|
-
return diagnostics;
|
|
2219
|
-
}
|
|
2220
|
-
|
|
2221
|
-
/**
|
|
2222
|
-
* Real C++20 in WebAssembly Extension for CodeLab (`@innovatorved/code-lab/extensions/cpp`).
|
|
2223
|
-
*
|
|
2224
|
-
* Enables:
|
|
2225
|
-
* - Real Clang/LLVM + LLD + WASI C++20 compilation in WebAssembly (~35 MB downloaded on demand & cached in IndexedDB)
|
|
2226
|
-
* - `<bits/stdc++.h>`, `<codelab/dsa.hpp>`, and `<codelab/test.hpp>` headers in VirtualFS
|
|
2227
|
-
* - `JS | TS | C++` language switcher in the CodeLab workbench
|
|
2228
|
-
* - `g++`, `clang++`, `c++`, and `./a.out` binary execution in the POSIX shell
|
|
2229
|
-
* - Guided Lab `cppStarterFiles`, `cppSolutionFiles`, and `cppFiles` curriculum support
|
|
2230
|
-
* - Monaco IntelliSense, hovers, debounced C++20 static linter, and Clang compiler squiggles
|
|
2231
|
-
*/
|
|
2232
|
-
export function installCppExtension(workbench: any, options: ExtendedCppExtensionOptions = {}) {
|
|
2233
|
-
const toolchain = new CppToolchainManager(options);
|
|
2234
|
-
const compilerFn = registerCppCompilerOnRuntime(toolchain);
|
|
2235
|
-
|
|
2236
|
-
if (!workbench) return toolchain;
|
|
2237
|
-
|
|
2238
|
-
workbench.cppToolchain = toolchain;
|
|
2239
|
-
workbench.cppCompiler = compilerFn;
|
|
2240
|
-
workbench.cppOptions = toolchain.options;
|
|
2241
|
-
|
|
2242
|
-
// Register Monaco language service immediately and queue hook if Monaco loads asynchronously
|
|
2243
|
-
const getWsFiles = () => (workbench && workbench.files ? workbench.files : {});
|
|
2244
|
-
if (typeof window !== 'undefined' && (window as any).monaco) {
|
|
2245
|
-
registerMonacoCppLanguageService((window as any).monaco, getWsFiles);
|
|
2246
|
-
}
|
|
2247
|
-
if (!Array.isArray(workbench._monacoReadyHooks)) {
|
|
2248
|
-
workbench._monacoReadyHooks = [];
|
|
2249
|
-
}
|
|
2250
|
-
workbench._monacoReadyHooks.push((monaco: any) => {
|
|
2251
|
-
registerMonacoCppLanguageService(monaco, getWsFiles);
|
|
2252
|
-
});
|
|
2253
|
-
|
|
2254
|
-
if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
|
|
2255
|
-
workbench.enabledLanguages = new Set(['js', 'cpp']);
|
|
2256
|
-
} else {
|
|
2257
|
-
workbench.enabledLanguages.add('cpp');
|
|
2258
|
-
}
|
|
2259
|
-
|
|
2260
|
-
if (options.files && typeof options.files === 'object') {
|
|
2261
|
-
workbench.cppFiles = { ...(workbench.cppFiles || {}), ...options.files };
|
|
2262
|
-
if (workbench.guidedConfig) {
|
|
2263
|
-
workbench.guidedConfig.cppFiles = { ...(workbench.guidedConfig.cppFiles || {}), ...options.files };
|
|
2264
|
-
}
|
|
2265
|
-
}
|
|
2266
|
-
if (options.starterFiles && typeof options.starterFiles === 'object') {
|
|
2267
|
-
if (!workbench.guidedConfig) workbench.guidedConfig = {};
|
|
2268
|
-
workbench.guidedConfig.cppStarterFiles = {
|
|
2269
|
-
...(workbench.guidedConfig.cppStarterFiles || {}),
|
|
2270
|
-
...options.starterFiles
|
|
2271
|
-
};
|
|
2272
|
-
}
|
|
2273
|
-
if (options.solutionFiles && typeof options.solutionFiles === 'object') {
|
|
2274
|
-
if (!workbench.guidedConfig) workbench.guidedConfig = {};
|
|
2275
|
-
workbench.guidedConfig.cppSolutionFiles = {
|
|
2276
|
-
...(workbench.guidedConfig.cppSolutionFiles || {}),
|
|
2277
|
-
...options.solutionFiles
|
|
2278
|
-
};
|
|
2279
|
-
}
|
|
2280
|
-
|
|
2281
|
-
if (workbench.vfs) {
|
|
2282
|
-
seedCppHeadersIntoVfs(workbench.vfs, toolchain.options.extraHeaders);
|
|
2283
|
-
}
|
|
2284
|
-
|
|
2285
|
-
workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
|
|
2286
|
-
|
|
2287
|
-
// Synchronous static C++ linter (resolves _diagnosticsStore dynamically)
|
|
2288
|
-
workbench._cppLintHandler = (file: string, code: string) => {
|
|
2289
|
-
if (!file || !/\.(?:cpp|cc|cxx|hpp|h)$/i.test(file)) return;
|
|
2290
|
-
const diags = analyzeCppSource(String(code ?? ''), file, workbench ? workbench.vfs : undefined);
|
|
2291
|
-
const store = workbench ? workbench._diagnosticsStore : null;
|
|
2292
|
-
if (store && typeof store.setFileDiagnostics === 'function') {
|
|
2293
|
-
store.setFileDiagnostics(file, 'cpp-linter', diags);
|
|
2294
|
-
} else if (store && typeof store.clear === 'function' && typeof store.add === 'function') {
|
|
2295
|
-
store.clear('cpp-linter');
|
|
2296
|
-
for (const d of diags) {
|
|
2297
|
-
store.add(d);
|
|
2298
|
-
}
|
|
2299
|
-
}
|
|
2300
|
-
if (typeof window !== 'undefined' && (window as any).monaco) {
|
|
2301
|
-
const model =
|
|
2302
|
-
(workbench.models && typeof workbench.models.get === 'function' && workbench.models.get(file)) ||
|
|
2303
|
-
(workbench.activeFile === file && workbench.editor ? workbench.editor.getModel() : null);
|
|
2304
|
-
if (model) {
|
|
2305
|
-
const markers = diags.map((d) => ({
|
|
2306
|
-
startLineNumber: d.line,
|
|
2307
|
-
startColumn: d.col || 1,
|
|
2308
|
-
endLineNumber: d.endLine || d.line,
|
|
2309
|
-
endColumn: d.endCol || (d.col || 1) + 20,
|
|
2310
|
-
message: d.message,
|
|
2311
|
-
severity:
|
|
2312
|
-
d.severity === 'error'
|
|
2313
|
-
? (window as any).monaco.MarkerSeverity.Error
|
|
2314
|
-
: (window as any).monaco.MarkerSeverity.Warning
|
|
2315
|
-
}));
|
|
2316
|
-
(window as any).monaco.editor.setModelMarkers(model, 'cpp-linter', markers);
|
|
2317
|
-
}
|
|
2318
|
-
}
|
|
2319
|
-
};
|
|
2320
|
-
|
|
2321
|
-
if (options.preload) {
|
|
2322
|
-
toolchain.ensureLoaded().catch((err) => {
|
|
2323
|
-
if (typeof workbench._appendTerminalOutput === 'function') {
|
|
2324
|
-
workbench._appendTerminalOutput('stderr', `[C++ Toolchain preload warning]: ${err.message || err}\n`);
|
|
2325
|
-
}
|
|
2326
|
-
});
|
|
2327
|
-
}
|
|
2328
|
-
|
|
2329
|
-
if (options.activate && typeof workbench.setLanguage === 'function') {
|
|
2330
|
-
workbench.setLanguage('cpp');
|
|
2331
|
-
} else if (typeof workbench._refreshToolbarAndTabs === 'function') {
|
|
2332
|
-
workbench._refreshToolbarAndTabs();
|
|
2333
|
-
} else if (typeof workbench._renderShell === 'function' && workbench.container) {
|
|
2334
|
-
workbench._renderShell();
|
|
2335
|
-
if (typeof workbench._bindEvents === 'function') workbench._bindEvents();
|
|
2336
|
-
if (typeof workbench._renderFileLists === 'function') workbench._renderFileLists();
|
|
2337
|
-
}
|
|
2338
|
-
|
|
2339
|
-
return workbench;
|
|
2340
|
-
}
|
|
2341
|
-
|
|
2342
|
-
export function cppExtension(workbenchOrOptions?: any, maybeOptions?: ExtendedCppExtensionOptions): any {
|
|
2343
|
-
if (workbenchOrOptions === null) {
|
|
2344
|
-
const toolchain = new CppToolchainManager(maybeOptions || {});
|
|
2345
|
-
registerCppCompilerOnRuntime(toolchain);
|
|
2346
|
-
return toolchain;
|
|
2347
|
-
}
|
|
2348
|
-
if (
|
|
2349
|
-
workbenchOrOptions === undefined ||
|
|
2350
|
-
(typeof workbenchOrOptions === 'object' &&
|
|
2351
|
-
!('enabledLanguages' in workbenchOrOptions) &&
|
|
2352
|
-
!('container' in workbenchOrOptions) &&
|
|
2353
|
-
!('_renderShell' in workbenchOrOptions))
|
|
2354
|
-
) {
|
|
2355
|
-
const opts = (workbenchOrOptions || {}) as ExtendedCppExtensionOptions;
|
|
2356
|
-
const plugin: any = (wb: any, runOpts: any = {}) => {
|
|
2357
|
-
return installCppExtension(wb, { ...opts, ...(runOpts || {}) });
|
|
2358
|
-
};
|
|
2359
|
-
plugin.extensionName = 'cpp';
|
|
2360
|
-
plugin.languageId = 'cpp' as const;
|
|
2361
|
-
plugin.install = plugin;
|
|
2362
|
-
return plugin;
|
|
2363
|
-
}
|
|
2364
|
-
return installCppExtension(workbenchOrOptions, maybeOptions);
|
|
2365
|
-
}
|
|
2366
|
-
|
|
2367
|
-
export function createCppExtension(options: ExtendedCppExtensionOptions = {}) {
|
|
2368
|
-
return cppExtension(options);
|
|
2369
|
-
}
|
|
2370
|
-
|
|
2371
|
-
export default cppExtension;
|