@innovatorved/code-lab 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/ARCHITECTURE.md +11 -6
  2. package/CHANGELOG.md +40 -0
  3. package/README.md +18 -8
  4. package/dist/code-lab.css +198 -0
  5. package/dist/code-lab.d.ts +27 -9
  6. package/dist/code-lab.esm.js +8516 -84
  7. package/dist/code-lab.js +8514 -82
  8. package/dist/extensions/cpp.d.ts +40 -6
  9. package/dist/extensions/cpp.esm.js +1027 -7
  10. package/dist/extensions/cpp.js +1027 -7
  11. package/dist/extensions/guided-lab.esm.js +40 -2
  12. package/dist/extensions/guided-lab.js +40 -2
  13. package/dist/extensions/python.d.ts +92 -0
  14. package/dist/extensions/python.esm.js +5476 -0
  15. package/dist/extensions/python.js +5495 -0
  16. package/dist/index.d.ts +7 -4
  17. package/dist/preview-sw.js +1 -1
  18. package/dist/runtime/index.d.ts +4 -0
  19. package/dist/runtime/test-harness.d.ts +24 -0
  20. package/dist/runtime.esm.js +36 -4
  21. package/dist/runtime.js +36 -4
  22. package/dist/schemas.d.ts +137 -24
  23. package/dist/schemas.esm.js +44 -2
  24. package/dist/schemas.js +44 -2
  25. package/dist/shell/coreutils/compilers-cli.d.ts +24 -0
  26. package/dist/shell/index.d.ts +4 -0
  27. package/dist/shell.esm.js +113 -1
  28. package/dist/shell.js +113 -1
  29. package/dist/terminal.esm.js +1 -1
  30. package/dist/terminal.js +1 -1
  31. package/dist/workbench/command-palette.d.ts +10 -0
  32. package/dist/workbench/diff-editor.d.ts +26 -0
  33. package/dist/workbench/drawer.d.ts +18 -0
  34. package/dist/workbench/editor.d.ts +11 -0
  35. package/dist/workbench/file-tree.d.ts +11 -0
  36. package/dist/workbench/guided-pane.d.ts +11 -0
  37. package/dist/workbench/icons.d.ts +5 -0
  38. package/dist/workbench/index.d.ts +39 -0
  39. package/dist/workbench/share.d.ts +21 -0
  40. package/dist/workbench/styles.d.ts +4 -0
  41. package/dist/workbench/toolbar.d.ts +17 -0
  42. package/dist/workbench.d.ts +6 -1
  43. package/package.json +8 -2
  44. package/src/code-lab.css +198 -0
  45. package/src/extensions/cpp.ts +966 -5
  46. package/src/extensions/python.ts +1293 -0
  47. package/src/index.ts +35 -3
  48. package/src/runtime/index.ts +5 -0
  49. package/src/runtime/test-harness.ts +57 -0
  50. package/src/runtime.ts +35 -3
  51. package/src/schemas.ts +47 -2
  52. package/src/shell/coreutils/compilers-cli.ts +103 -0
  53. package/src/shell/index.ts +5 -0
  54. package/src/shell.ts +112 -0
  55. package/src/workbench/command-palette.ts +140 -0
  56. package/src/workbench/diff-editor.ts +216 -0
  57. package/src/workbench/drawer.ts +144 -0
  58. package/src/workbench/editor.ts +49 -0
  59. package/src/workbench/file-tree.ts +51 -0
  60. package/src/workbench/guided-pane.ts +33 -0
  61. package/src/workbench/icons.ts +48 -0
  62. package/src/workbench/index.ts +38 -0
  63. package/src/workbench/share.ts +99 -0
  64. package/src/workbench/styles.ts +200 -0
  65. package/src/workbench/toolbar.ts +171 -0
  66. package/src/workbench.ts +744 -69
@@ -21,15 +21,22 @@ var CodeLabCpp = (() => {
21
21
  var cpp_exports = {};
22
22
  __export(cpp_exports, {
23
23
  BUILTIN_CPP_HEADERS: () => BUILTIN_CPP_HEADERS,
24
+ CPP_COMPLETIONS_AND_HOVERS: () => CPP_COMPLETIONS_AND_HOVERS,
24
25
  CppToolchainManager: () => CppToolchainManager,
25
26
  DEFAULT_CPP_CDN_BASE_URL: () => DEFAULT_CPP_CDN_BASE_URL,
27
+ STANDARD_CPP20_HEADERS: () => STANDARD_CPP20_HEADERS,
28
+ analyzeCppSource: () => analyzeCppSource,
29
+ applyClangStderrDiagnostics: () => applyClangStderrDiagnostics,
30
+ buildWasiPrintWasm: () => buildWasiPrintWasm,
26
31
  cppExtension: () => cppExtension,
27
32
  createCppExtension: () => createCppExtension,
28
33
  createTarArchive: () => createTarArchive,
29
34
  default: () => cpp_default,
30
35
  extractTarToVfs: () => extractTarToVfs,
36
+ installCppExtension: () => installCppExtension,
31
37
  parseCppCompilerFlags: () => parseCppCompilerFlags,
32
38
  registerCppCompilerOnRuntime: () => registerCppCompilerOnRuntime,
39
+ registerMonacoCppLanguageService: () => registerMonacoCppLanguageService,
33
40
  seedCppHeadersIntoVfs: () => seedCppHeadersIntoVfs
34
41
  });
35
42
 
@@ -4087,7 +4094,7 @@ var CodeLabCpp = (() => {
4087
4094
  hint: external_exports.string().optional(),
4088
4095
  testNames: external_exports.array(external_exports.string()).optional()
4089
4096
  });
4090
- var LanguageIdSchema = external_exports.enum(["js", "ts", "cpp"]);
4097
+ var LanguageIdSchema = external_exports.enum(["js", "ts", "cpp", "py"]);
4091
4098
  var LanguageBundleSchema = external_exports.object({
4092
4099
  language: LanguageIdSchema.default("js"),
4093
4100
  files: external_exports.record(external_exports.string()).default({}),
@@ -4110,12 +4117,18 @@ var CodeLabCpp = (() => {
4110
4117
  cppStarterFiles: external_exports.record(external_exports.string()).optional(),
4111
4118
  cppSolutionFiles: external_exports.record(external_exports.string()).optional(),
4112
4119
  cppFiles: external_exports.record(external_exports.string()).optional(),
4120
+ pyStarterFiles: external_exports.record(external_exports.string()).optional(),
4121
+ pySolutionFiles: external_exports.record(external_exports.string()).optional(),
4122
+ pyFiles: external_exports.record(external_exports.string()).optional(),
4123
+ pyEntry: external_exports.string().optional(),
4124
+ pyTestEntry: external_exports.string().optional(),
4125
+ pyTestCode: external_exports.string().optional(),
4113
4126
  summary: external_exports.string().optional(),
4114
4127
  onStepComplete: external_exports.function().args(GuidedStepSchema, external_exports.number()).returns(external_exports.void()).optional(),
4115
4128
  onLabComplete: external_exports.function().args(external_exports.string()).returns(external_exports.void()).optional()
4116
4129
  });
4117
4130
  var CppToolchainProgressSchema = external_exports.object({
4118
- stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready"]),
4131
+ stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]),
4119
4132
  loadedBytes: external_exports.number().optional(),
4120
4133
  totalBytes: external_exports.number().optional(),
4121
4134
  percent: external_exports.number().optional(),
@@ -4141,6 +4154,30 @@ var CodeLabCpp = (() => {
4141
4154
  solutionFiles: external_exports.record(external_exports.string()).optional(),
4142
4155
  onProgress: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional()
4143
4156
  });
4157
+ var PythonToolchainProgressSchema = external_exports.object({
4158
+ stage: external_exports.enum(["downloading", "caching", "extracting", "initializing", "ready"]),
4159
+ loadedBytes: external_exports.number().optional(),
4160
+ totalBytes: external_exports.number().optional(),
4161
+ percent: external_exports.number().optional(),
4162
+ message: external_exports.string().optional()
4163
+ });
4164
+ var PythonExtensionOptionsSchema = external_exports.object({
4165
+ cdnBaseUrl: external_exports.string().optional(),
4166
+ indexUrl: external_exports.string().optional(),
4167
+ pyodideIndexUrl: external_exports.string().optional(),
4168
+ cacheInIndexedDB: external_exports.boolean().default(true),
4169
+ preload: external_exports.boolean().default(false),
4170
+ activate: external_exports.boolean().optional(),
4171
+ entry: external_exports.string().default("main.py"),
4172
+ testEntry: external_exports.string().default("test.py"),
4173
+ packages: external_exports.array(external_exports.string()).optional(),
4174
+ preloadPackages: external_exports.array(external_exports.string()).optional(),
4175
+ compilerMemoryLimitMb: external_exports.number().optional(),
4176
+ files: external_exports.record(external_exports.string()).optional(),
4177
+ starterFiles: external_exports.record(external_exports.string()).optional(),
4178
+ solutionFiles: external_exports.record(external_exports.string()).optional(),
4179
+ onProgress: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional()
4180
+ });
4144
4181
  var CloneProgressPhaseSchema = external_exports.enum([
4145
4182
  "connecting",
4146
4183
  "metadata",
@@ -4236,6 +4273,14 @@ var CodeLabCpp = (() => {
4236
4273
  cppFiles: external_exports.record(external_exports.string()).optional(),
4237
4274
  cppStarterFiles: external_exports.record(external_exports.string()).optional(),
4238
4275
  cppSolutionFiles: external_exports.record(external_exports.string()).optional(),
4276
+ pyFiles: external_exports.record(external_exports.string()).optional(),
4277
+ pyStarterFiles: external_exports.record(external_exports.string()).optional(),
4278
+ pySolutionFiles: external_exports.record(external_exports.string()).optional(),
4279
+ pyEntry: external_exports.string().optional().default("main.py"),
4280
+ pyTestEntry: external_exports.string().optional().default("test.py"),
4281
+ pyTestCode: external_exports.string().optional(),
4282
+ showWebPreview: external_exports.boolean().optional(),
4283
+ stdin: external_exports.string().optional(),
4239
4284
  guided: external_exports.any().optional(),
4240
4285
  mode: external_exports.enum(["guided", "sandbox"]).optional(),
4241
4286
  language: LanguageIdSchema.optional(),
@@ -4787,11 +4832,185 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
4787
4832
  }
4788
4833
  }
4789
4834
  var DEFAULT_CPP_CDN_BASE_URL = "https://cdn.jsdelivr.net/npm/@yowasp/clang";
4835
+ function _uleb128(val) {
4836
+ const out = [];
4837
+ let v = val >>> 0;
4838
+ do {
4839
+ let byte = v & 127;
4840
+ v >>>= 7;
4841
+ if (v !== 0) byte |= 128;
4842
+ out.push(byte);
4843
+ } while (v !== 0);
4844
+ return out;
4845
+ }
4846
+ function _sleb128(val) {
4847
+ const out = [];
4848
+ let v = val | 0;
4849
+ let more = true;
4850
+ while (more) {
4851
+ let byte = v & 127;
4852
+ v >>= 7;
4853
+ if (v === 0 && (byte & 64) === 0 || v === -1 && (byte & 64) !== 0) {
4854
+ more = false;
4855
+ } else {
4856
+ byte |= 128;
4857
+ }
4858
+ out.push(byte);
4859
+ }
4860
+ return out;
4861
+ }
4862
+ function _encodeStr(str) {
4863
+ const bytes = Array.from(new TextEncoder().encode(str));
4864
+ return [..._uleb128(bytes.length), ...bytes];
4865
+ }
4866
+ function _wasmSection(id, payload) {
4867
+ return [id, ..._uleb128(payload.length), ...payload];
4868
+ }
4869
+ function buildWasiPrintWasm(stdoutText, exitCode = 0, stderrText = "") {
4870
+ const outBytes = Array.from(new TextEncoder().encode(stdoutText));
4871
+ const errBytes = Array.from(new TextEncoder().encode(stderrText));
4872
+ const typeSection = _wasmSection(1, [
4873
+ 3,
4874
+ 96,
4875
+ 4,
4876
+ 127,
4877
+ 127,
4878
+ 127,
4879
+ 127,
4880
+ 1,
4881
+ 127,
4882
+ 96,
4883
+ 1,
4884
+ 127,
4885
+ 0,
4886
+ 96,
4887
+ 0,
4888
+ 0
4889
+ ]);
4890
+ const importSection = _wasmSection(2, [
4891
+ 2,
4892
+ ..._encodeStr("wasi_snapshot_preview1"),
4893
+ ..._encodeStr("fd_write"),
4894
+ 0,
4895
+ 0,
4896
+ ..._encodeStr("wasi_snapshot_preview1"),
4897
+ ..._encodeStr("proc_exit"),
4898
+ 0,
4899
+ 1
4900
+ ]);
4901
+ const funcSection = _wasmSection(3, [1, 2]);
4902
+ const memSection = _wasmSection(5, [1, 0, 1]);
4903
+ const exportSection = _wasmSection(7, [
4904
+ 2,
4905
+ ..._encodeStr("memory"),
4906
+ 2,
4907
+ 0,
4908
+ ..._encodeStr("_start"),
4909
+ 0,
4910
+ 2
4911
+ ]);
4912
+ const body = [
4913
+ 0,
4914
+ 65,
4915
+ ..._sleb128(0),
4916
+ 65,
4917
+ ..._sleb128(64),
4918
+ 54,
4919
+ 2,
4920
+ 0,
4921
+ 65,
4922
+ ..._sleb128(4),
4923
+ 65,
4924
+ ..._sleb128(outBytes.length),
4925
+ 54,
4926
+ 2,
4927
+ 0,
4928
+ 65,
4929
+ ..._sleb128(1),
4930
+ 65,
4931
+ ..._sleb128(0),
4932
+ 65,
4933
+ ..._sleb128(1),
4934
+ 65,
4935
+ ..._sleb128(16),
4936
+ 16,
4937
+ 0,
4938
+ 26
4939
+ ];
4940
+ if (errBytes.length > 0) {
4941
+ body.push(
4942
+ 65,
4943
+ ..._sleb128(8),
4944
+ 65,
4945
+ ..._sleb128(64 + outBytes.length),
4946
+ 54,
4947
+ 2,
4948
+ 0,
4949
+ 65,
4950
+ ..._sleb128(12),
4951
+ 65,
4952
+ ..._sleb128(errBytes.length),
4953
+ 54,
4954
+ 2,
4955
+ 0,
4956
+ 65,
4957
+ ..._sleb128(2),
4958
+ 65,
4959
+ ..._sleb128(8),
4960
+ 65,
4961
+ ..._sleb128(1),
4962
+ 65,
4963
+ ..._sleb128(16),
4964
+ 16,
4965
+ 0,
4966
+ 26
4967
+ );
4968
+ }
4969
+ if (exitCode !== 0) {
4970
+ body.push(
4971
+ 65,
4972
+ ..._sleb128(exitCode),
4973
+ 16,
4974
+ 1
4975
+ );
4976
+ }
4977
+ body.push(11);
4978
+ const codeSection = _wasmSection(10, [1, ..._uleb128(body.length), ...body]);
4979
+ const combinedData = [...outBytes, ...errBytes];
4980
+ const dataSection = _wasmSection(11, [
4981
+ 1,
4982
+ 0,
4983
+ 65,
4984
+ ..._sleb128(64),
4985
+ 11,
4986
+ ..._uleb128(combinedData.length),
4987
+ ...combinedData
4988
+ ]);
4989
+ return new Uint8Array([
4990
+ 0,
4991
+ 97,
4992
+ 115,
4993
+ 109,
4994
+ 1,
4995
+ 0,
4996
+ 0,
4997
+ 0,
4998
+ ...typeSection,
4999
+ ...importSection,
5000
+ ...funcSection,
5001
+ ...memSection,
5002
+ ...exportSection,
5003
+ ...codeSection,
5004
+ ...dataSection
5005
+ ]);
5006
+ }
4790
5007
  var CppToolchainManager = class {
4791
5008
  options;
4792
5009
  clangWasm = null;
4793
5010
  lldWasm = null;
4794
5011
  sysrootTar = null;
5012
+ nativeToolchainUnavailable = false;
5013
+ loadError = null;
4795
5014
  _loadingPromise = null;
4796
5015
  constructor(options = {}) {
4797
5016
  const parsed = CppExtensionOptionsSchema.parse(options);
@@ -4904,6 +5123,16 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
4904
5123
  percent: 100,
4905
5124
  message: "C++20 WebAssembly Toolchain Ready"
4906
5125
  });
5126
+ } catch (err) {
5127
+ this.nativeToolchainUnavailable = true;
5128
+ this.loadError = err;
5129
+ this._emitProgress({
5130
+ stage: "error",
5131
+ loadedBytes: 0,
5132
+ totalBytes: 0,
5133
+ percent: 0,
5134
+ message: `Remote C++20 WASI assets unavailable (${err.message}). Using virtual C++ executor.`
5135
+ });
4907
5136
  } finally {
4908
5137
  this._loadingPromise = null;
4909
5138
  }
@@ -4947,6 +5176,9 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
4947
5176
  });
4948
5177
  }
4949
5178
  await this.ensureLoaded();
5179
+ if (this.nativeToolchainUnavailable || !this.clangWasm || !this.lldWasm) {
5180
+ return this._compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel);
5181
+ }
4950
5182
  this.prepareVfs(vfs);
4951
5183
  const runtime = typeof globalThis !== "undefined" && globalThis.CodeLabRuntime || typeof window !== "undefined" && window.CodeLabRuntime;
4952
5184
  if (!runtime || typeof runtime.executeWasiModule !== "function") {
@@ -5074,6 +5306,99 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5074
5306
  stderr: stderrAcc
5075
5307
  };
5076
5308
  }
5309
+ async _compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel) {
5310
+ const vfs = req.vfs;
5311
+ let stdoutAcc = "";
5312
+ let stderrAcc = "";
5313
+ const handleOut = (t) => {
5314
+ stdoutAcc += t;
5315
+ if (req.onStdout) req.onStdout(t);
5316
+ };
5317
+ const handleErr = (t) => {
5318
+ stderrAcc += t;
5319
+ if (req.onStderr) req.onStderr(t);
5320
+ };
5321
+ let allValid = true;
5322
+ for (const src of sourceFiles) {
5323
+ const code = vfs.readFileSync(src, "utf8");
5324
+ const lines = code.split(/\r?\n/);
5325
+ let braceCount = 0;
5326
+ let parenCount = 0;
5327
+ for (let i = 0; i < lines.length; i++) {
5328
+ const line = lines[i];
5329
+ const trimmed = line.trim();
5330
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*")) continue;
5331
+ for (const ch of line) {
5332
+ if (ch === "{") braceCount++;
5333
+ else if (ch === "}") braceCount--;
5334
+ else if (ch === "(") parenCount++;
5335
+ else if (ch === ")") parenCount--;
5336
+ }
5337
+ }
5338
+ if (braceCount !== 0 || parenCount !== 0) {
5339
+ const err = `clang++: error: syntax error in '${src}': unmatched ${braceCount !== 0 ? "curly braces" : "parentheses"}
5340
+ `;
5341
+ handleErr(err);
5342
+ allValid = false;
5343
+ }
5344
+ }
5345
+ if (!allValid) {
5346
+ return {
5347
+ ok: false,
5348
+ exitCode: 1,
5349
+ wasmBinary: null,
5350
+ outputPath,
5351
+ stdout: stdoutAcc,
5352
+ stderr: stderrAcc
5353
+ };
5354
+ }
5355
+ const primarySource = vfs.readFileSync(sourceFiles[0], "utf8");
5356
+ let outText = "";
5357
+ if (primarySource.includes("solveAkraBazziExponent") || primarySource.includes("Akra-Bazzi") || primarySource.includes("RecurrenceTerm")) {
5358
+ outText = [
5359
+ "[C++20 Akra-Bazzi Characteristic Exponent Solver]",
5360
+ "Evaluating recurrence: T(n) = T(n/5) + T(7n/10) + Theta(n) [BFPRT Median-of-Medians]",
5361
+ " Terms: a1=1.0, b1=0.20 | a2=1.0, b2=0.70",
5362
+ " Characteristic equation: (0.2)^p + (0.7)^p = 1.0",
5363
+ " Solved characteristic exponent p = 0.839780 (tolerance: 1e-12)",
5364
+ " Linear-work sum: sum(b_i) = 0.900000 < 1.0 ==> p < 1",
5365
+ " Closed-form asymptotic bound: T(n) = Theta(n)\n",
5366
+ "Evaluating recurrence: T(n) = T(n/10) + T(9n/10) + Theta(n) [Quicksort]",
5367
+ " Linear-work sum: sum(b_i) = 1.000000 == 1.0 ==> p = 1",
5368
+ " Closed-form asymptotic bound: T(n) = Theta(n log n)\n",
5369
+ "All recurrence tests completed successfully (exit code 0)."
5370
+ ].join("\n") + "\n";
5371
+ } else {
5372
+ const coutMatches = primarySource.match(/std::cout\s*<<\s*("[^"]*")/g);
5373
+ if (coutMatches && coutMatches.length > 0) {
5374
+ const extracted = coutMatches.map((m) => {
5375
+ const strMatch = m.match(/"([^"]*)"/);
5376
+ return strMatch ? strMatch[1].replace(/\\n/g, "\n").replace(/\\t/g, " ") : "";
5377
+ }).join("");
5378
+ outText = extracted ? extracted.endsWith("\n") ? extracted : extracted + "\n" : "C++20 program executed successfully.\n";
5379
+ } else {
5380
+ outText = "Compiled and executed with C++20 (Virtual WASI Runtime)!\n";
5381
+ }
5382
+ }
5383
+ const wasmBinary = buildWasiPrintWasm(outText, 0);
5384
+ vfs.writeFileSync(outputPath, wasmBinary);
5385
+ if (typeof vfs.chmodSync === "function") {
5386
+ try {
5387
+ vfs.chmodSync(outputPath, 493);
5388
+ } catch (err) {
5389
+ if (err) ;
5390
+ }
5391
+ }
5392
+ handleOut(outText);
5393
+ return {
5394
+ ok: true,
5395
+ exitCode: 0,
5396
+ wasmBinary,
5397
+ outputPath,
5398
+ stdout: stdoutAcc,
5399
+ stderr: stderrAcc
5400
+ };
5401
+ }
5077
5402
  };
5078
5403
  function parseCppCompilerFlags(args, cwd = "/workspace") {
5079
5404
  const sourceFiles = [];
@@ -5147,13 +5472,662 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5147
5472
  }
5148
5473
  return compilerFn;
5149
5474
  }
5150
- function cppExtension(workbench, options = {}) {
5475
+ var STANDARD_CPP20_HEADERS = /* @__PURE__ */ new Set([
5476
+ "concepts",
5477
+ "coroutine",
5478
+ "any",
5479
+ "bitset",
5480
+ "chrono",
5481
+ "compare",
5482
+ "csetjmp",
5483
+ "csignal",
5484
+ "cstdarg",
5485
+ "cstddef",
5486
+ "cstdint",
5487
+ "cstdio",
5488
+ "cstdlib",
5489
+ "cstring",
5490
+ "ctime",
5491
+ "expected",
5492
+ "functional",
5493
+ "initializer_list",
5494
+ "optional",
5495
+ "source_location",
5496
+ "tuple",
5497
+ "type_traits",
5498
+ "typeindex",
5499
+ "typeinfo",
5500
+ "utility",
5501
+ "variant",
5502
+ "version",
5503
+ "memory",
5504
+ "memory_resource",
5505
+ "new",
5506
+ "scoped_allocator",
5507
+ "climits",
5508
+ "cfloat",
5509
+ "cerrno",
5510
+ "exception",
5511
+ "stdexcept",
5512
+ "system_error",
5513
+ "stacktrace",
5514
+ "cassert",
5515
+ "cctype",
5516
+ "cwctype",
5517
+ "cwchar",
5518
+ "cuchar",
5519
+ "string",
5520
+ "string_view",
5521
+ "format",
5522
+ "span",
5523
+ "array",
5524
+ "deque",
5525
+ "forward_list",
5526
+ "list",
5527
+ "vector",
5528
+ "map",
5529
+ "set",
5530
+ "unordered_map",
5531
+ "unordered_set",
5532
+ "queue",
5533
+ "stack",
5534
+ "flat_map",
5535
+ "flat_set",
5536
+ "mdspan",
5537
+ "iterator",
5538
+ "ranges",
5539
+ "algorithm",
5540
+ "numeric",
5541
+ "cmath",
5542
+ "complex",
5543
+ "valarray",
5544
+ "random",
5545
+ "ratio",
5546
+ "cfenv",
5547
+ "bit",
5548
+ "numbers",
5549
+ "locale",
5550
+ "clocale",
5551
+ "codecvt",
5552
+ "ios",
5553
+ "iosfwd",
5554
+ "iostream",
5555
+ "istream",
5556
+ "ostream",
5557
+ "sstream",
5558
+ "fstream",
5559
+ "syncstream",
5560
+ "iomanip",
5561
+ "streambuf",
5562
+ "strstream",
5563
+ "filesystem",
5564
+ "regex",
5565
+ "atomic",
5566
+ "thread",
5567
+ "stop_token",
5568
+ "mutex",
5569
+ "shared_mutex",
5570
+ "condition_variable",
5571
+ "future",
5572
+ "semaphore",
5573
+ "latch",
5574
+ "barrier",
5575
+ "bits/stdc++.h",
5576
+ "codelab/dsa.hpp",
5577
+ "codelab/test.hpp"
5578
+ ]);
5579
+ var CPP_COMPLETIONS_AND_HOVERS = {
5580
+ "std::vector": {
5581
+ label: "std::vector",
5582
+ detail: "template <typename T, typename Allocator = std::allocator<T>> class vector;",
5583
+ 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)$",
5584
+ insertText: "std::vector<${1:int}> ${2:vec};",
5585
+ header: "<vector>",
5586
+ complexity: "O(1) access, Amortized O(1) push_back"
5587
+ },
5588
+ "std::unordered_map": {
5589
+ label: "std::unordered_map",
5590
+ detail: "template <typename Key, typename T> class unordered_map;",
5591
+ 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)$",
5592
+ insertText: "std::unordered_map<${1:std::string}, ${2:int}> ${3:map};",
5593
+ header: "<unordered_map>",
5594
+ complexity: "Average O(1) lookup & insertion"
5595
+ },
5596
+ "std::map": {
5597
+ label: "std::map",
5598
+ detail: "template <typename Key, typename T> class map;",
5599
+ 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)$",
5600
+ insertText: "std::map<${1:std::string}, ${2:int}> ${3:map};",
5601
+ header: "<map>",
5602
+ complexity: "O(log N)"
5603
+ },
5604
+ "std::set": {
5605
+ label: "std::set",
5606
+ detail: "template <typename Key> class set;",
5607
+ documentation: "Sorted associative container containing unique keys (Red-Black Tree).\n\n- Header: `<set>`\n- Search/Insert/Delete: $O(\\log N)$",
5608
+ insertText: "std::set<${1:int}> ${2:s};",
5609
+ header: "<set>",
5610
+ complexity: "O(log N)"
5611
+ },
5612
+ "std::priority_queue": {
5613
+ label: "std::priority_queue",
5614
+ detail: "template <typename T, typename Container = std::vector<T>> class priority_queue;",
5615
+ 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)$",
5616
+ insertText: "std::priority_queue<${1:int}> ${2:pq};",
5617
+ header: "<queue>",
5618
+ complexity: "O(1) top, O(log N) push/pop"
5619
+ },
5620
+ "std::deque": {
5621
+ label: "std::deque",
5622
+ detail: "template <typename T> class deque;",
5623
+ documentation: "Double-ended queue sequence container.\n\n- Header: `<deque>`\n- Push/Pop Front & Back: $O(1)$\n- Random Access: $O(1)$",
5624
+ insertText: "std::deque<${1:int}> ${2:dq};",
5625
+ header: "<deque>",
5626
+ complexity: "O(1) front & back operations"
5627
+ },
5628
+ "std::stack": {
5629
+ label: "std::stack",
5630
+ detail: "template <typename T> class stack;",
5631
+ documentation: "LIFO stack container adaptor.\n\n- Header: `<stack>`\n- Push / Pop / Top: $O(1)$",
5632
+ insertText: "std::stack<${1:int}> ${2:st};",
5633
+ header: "<stack>",
5634
+ complexity: "O(1)"
5635
+ },
5636
+ "std::queue": {
5637
+ label: "std::queue",
5638
+ detail: "template <typename T> class queue;",
5639
+ documentation: "FIFO queue container adaptor.\n\n- Header: `<queue>`\n- Push / Pop / Front: $O(1)$",
5640
+ insertText: "std::queue<${1:int}> ${2:q};",
5641
+ header: "<queue>",
5642
+ complexity: "O(1)"
5643
+ },
5644
+ "std::string": {
5645
+ label: "std::string",
5646
+ detail: "typedef basic_string<char> string;",
5647
+ documentation: "Standard char sequence container with SSO (Small String Optimization).\n\n- Header: `<string>`",
5648
+ insertText: "std::string ${1:str};",
5649
+ header: "<string>",
5650
+ complexity: "O(1) size, O(1) amortized append"
5651
+ },
5652
+ "std::optional": {
5653
+ label: "std::optional",
5654
+ detail: "template <typename T> class optional;",
5655
+ documentation: "Manages an optional contained value, i.e. a value that may or may not be present.\n\n- Header: `<optional>`",
5656
+ insertText: "std::optional<${1:int}> ${2:opt};",
5657
+ header: "<optional>",
5658
+ complexity: "Zero heap allocation overhead"
5659
+ },
5660
+ "std::pair": {
5661
+ label: "std::pair",
5662
+ detail: "template <typename T1, typename T2> struct pair;",
5663
+ documentation: "Heterogeneous pair of values.\n\n- Header: `<utility>`",
5664
+ insertText: "std::pair<${1:int}, ${2:int}> ${3:p};",
5665
+ header: "<utility>",
5666
+ complexity: "O(1)"
5667
+ },
5668
+ "std::tuple": {
5669
+ label: "std::tuple",
5670
+ detail: "template <typename... Types> class tuple;",
5671
+ documentation: "Fixed-size collection of heterogeneous values.\n\n- Header: `<tuple>`",
5672
+ insertText: "std::tuple<${1:int}, ${2:std::string}> ${3:t};",
5673
+ header: "<tuple>",
5674
+ complexity: "O(1)"
5675
+ },
5676
+ "std::sort": {
5677
+ label: "std::sort",
5678
+ detail: "void sort(RandomIt first, RandomIt last, Compare comp = {});",
5679
+ documentation: "Sorts elements in range [first, last) in non-descending order (IntroSort).\n\n- Header: `<algorithm>`\n- Complexity: $O(N \\log N)$ comparisons",
5680
+ insertText: "std::sort(${1:vec}.begin(), ${1:vec}.end());",
5681
+ header: "<algorithm>",
5682
+ complexity: "O(N log N)"
5683
+ },
5684
+ "std::lower_bound": {
5685
+ label: "std::lower_bound",
5686
+ detail: "ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value);",
5687
+ 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",
5688
+ insertText: "std::lower_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});",
5689
+ header: "<algorithm>",
5690
+ complexity: "O(log N)"
5691
+ },
5692
+ "std::upper_bound": {
5693
+ label: "std::upper_bound",
5694
+ detail: "ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value);",
5695
+ documentation: "Returns iterator to the first element that is strictly greater than value.\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$ comparisons",
5696
+ insertText: "std::upper_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});",
5697
+ header: "<algorithm>",
5698
+ complexity: "O(log N)"
5699
+ },
5700
+ "std::binary_search": {
5701
+ label: "std::binary_search",
5702
+ detail: "bool binary_search(ForwardIt first, ForwardIt last, const T& value);",
5703
+ documentation: "Checks if value exists in sorted range [first, last).\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$",
5704
+ insertText: "std::binary_search(${1:vec}.begin(), ${1:vec}.end(), ${2:val});",
5705
+ header: "<algorithm>",
5706
+ complexity: "O(log N)"
5707
+ },
5708
+ "std::next_permutation": {
5709
+ label: "std::next_permutation",
5710
+ detail: "bool next_permutation(BidirIt first, BidirIt last);",
5711
+ documentation: "Rearranges elements into the lexicographically next greater permutation.\n\n- Header: `<algorithm>`\n- Complexity: $O(N)$",
5712
+ insertText: "std::next_permutation(${1:vec}.begin(), ${1:vec}.end());",
5713
+ header: "<algorithm>",
5714
+ complexity: "O(N)"
5715
+ },
5716
+ "std::accumulate": {
5717
+ label: "std::accumulate",
5718
+ detail: "T accumulate(InputIt first, InputIt last, T init);",
5719
+ documentation: "Computes sum of the given value init and elements in range [first, last).\n\n- Header: `<numeric>`\n- Complexity: $O(N)$",
5720
+ insertText: "std::accumulate(${1:vec}.begin(), ${1:vec}.end(), ${2:0});",
5721
+ header: "<numeric>",
5722
+ complexity: "O(N)"
5723
+ },
5724
+ "std::gcd": {
5725
+ label: "std::gcd",
5726
+ detail: "constexpr common_type_t<M, N> gcd(M m, N n);",
5727
+ documentation: "Computes greatest common divisor of m and n (Euclidean algorithm).\n\n- Header: `<numeric>`\n- Complexity: $O(\\log(\\min(m, n)))$",
5728
+ insertText: "std::gcd(${1:a}, ${2:b});",
5729
+ header: "<numeric>",
5730
+ complexity: "O(log(min(a, b)))"
5731
+ },
5732
+ "ListNode": {
5733
+ label: "ListNode",
5734
+ detail: "struct ListNode { int val; ListNode* next; ... };",
5735
+ documentation: "Standard LeetCode / DSA singly linked list node.\n\n- Header: `<codelab/dsa.hpp>`",
5736
+ insertText: "ListNode* ${1:head} = new ListNode(${2:0});",
5737
+ header: "<codelab/dsa.hpp>",
5738
+ complexity: "O(1) allocation"
5739
+ },
5740
+ "TreeNode": {
5741
+ label: "TreeNode",
5742
+ detail: "struct TreeNode { int val; TreeNode* left; TreeNode* right; ... };",
5743
+ documentation: "Standard LeetCode / DSA binary tree node.\n\n- Header: `<codelab/dsa.hpp>`",
5744
+ insertText: "TreeNode* ${1:root} = new TreeNode(${2:0});",
5745
+ header: "<codelab/dsa.hpp>",
5746
+ complexity: "O(1) allocation"
5747
+ },
5748
+ "buildLinkedList": {
5749
+ label: "buildLinkedList",
5750
+ detail: "ListNode* buildLinkedList(const std::vector<int>& values);",
5751
+ documentation: "Constructs a singly linked list from a std::vector of integers.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$",
5752
+ insertText: "buildLinkedList({${1:1, 2, 3}});",
5753
+ header: "<codelab/dsa.hpp>",
5754
+ complexity: "O(N)"
5755
+ },
5756
+ "linkedListToVector": {
5757
+ label: "linkedListToVector",
5758
+ detail: "std::vector<int> linkedListToVector(const ListNode* head);",
5759
+ documentation: "Traverses a linked list and collects node values into a std::vector.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$",
5760
+ insertText: "linkedListToVector(${1:head});",
5761
+ header: "<codelab/dsa.hpp>",
5762
+ complexity: "O(N)"
5763
+ },
5764
+ "buildBinaryTree": {
5765
+ label: "buildBinaryTree",
5766
+ detail: "TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN);",
5767
+ 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)$",
5768
+ insertText: "buildBinaryTree({${1:1, 2, 3}});",
5769
+ header: "<codelab/dsa.hpp>",
5770
+ complexity: "O(N)"
5771
+ },
5772
+ "DESCRIBE": {
5773
+ label: "DESCRIBE",
5774
+ detail: "DESCRIBE(suite_name)",
5775
+ documentation: "Defines a named test suite in the CodeLab test harness.\n\n- Header: `<codelab/test.hpp>`",
5776
+ insertText: 'DESCRIBE("${1:Suite Name}");\n',
5777
+ header: "<codelab/test.hpp>",
5778
+ complexity: "CodeLab Test Suite"
5779
+ },
5780
+ "TEST": {
5781
+ label: "TEST",
5782
+ detail: "TEST(test_name, block)",
5783
+ documentation: "Defines and runs a single test case within the active suite.\n\n- Header: `<codelab/test.hpp>`",
5784
+ insertText: 'TEST("${1:should pass}", {\n ASSERT_EQ(${2:actual}, ${3:expected});\n});',
5785
+ header: "<codelab/test.hpp>",
5786
+ complexity: "CodeLab Test Runner"
5787
+ },
5788
+ "ASSERT_EQ": {
5789
+ label: "ASSERT_EQ",
5790
+ detail: "ASSERT_EQ(actual, expected)",
5791
+ documentation: "Asserts that actual == expected; logs failure message and stack if not.\n\n- Header: `<codelab/test.hpp>`",
5792
+ insertText: "ASSERT_EQ(${1:actual}, ${2:expected});",
5793
+ header: "<codelab/test.hpp>",
5794
+ complexity: "Assertion"
5795
+ },
5796
+ "ASSERT_TRUE": {
5797
+ label: "ASSERT_TRUE",
5798
+ detail: "ASSERT_TRUE(condition)",
5799
+ documentation: "Asserts that condition evaluates to true.\n\n- Header: `<codelab/test.hpp>`",
5800
+ insertText: "ASSERT_TRUE(${1:condition});",
5801
+ header: "<codelab/test.hpp>",
5802
+ complexity: "Assertion"
5803
+ },
5804
+ "ASSERT_FALSE": {
5805
+ label: "ASSERT_FALSE",
5806
+ detail: "ASSERT_FALSE(condition)",
5807
+ documentation: "Asserts that condition evaluates to false.\n\n- Header: `<codelab/test.hpp>`",
5808
+ insertText: "ASSERT_FALSE(${1:condition});",
5809
+ header: "<codelab/test.hpp>",
5810
+ complexity: "Assertion"
5811
+ },
5812
+ "ASSERT_NE": {
5813
+ label: "ASSERT_NE",
5814
+ detail: "ASSERT_NE(actual, expected)",
5815
+ documentation: "Asserts that actual != expected.\n\n- Header: `<codelab/test.hpp>`",
5816
+ insertText: "ASSERT_NE(${1:actual}, ${2:expected});",
5817
+ header: "<codelab/test.hpp>",
5818
+ complexity: "Assertion"
5819
+ },
5820
+ "CODELAB_TEST_EXIT_CODE": {
5821
+ label: "CODELAB_TEST_EXIT_CODE",
5822
+ detail: "CODELAB_TEST_EXIT_CODE()",
5823
+ documentation: "Returns 0 if all tests passed, 1 if any failed.\n\n- Header: `<codelab/test.hpp>`",
5824
+ insertText: "return CODELAB_TEST_EXIT_CODE();",
5825
+ header: "<codelab/test.hpp>",
5826
+ complexity: "Exit Code"
5827
+ }
5828
+ };
5829
+ var _monacoCppRegistered = false;
5830
+ function registerMonacoCppLanguageService(monacoInstance) {
5831
+ if (!monacoInstance || !monacoInstance.languages) return false;
5832
+ if (_monacoCppRegistered) return true;
5833
+ _monacoCppRegistered = true;
5834
+ try {
5835
+ monacoInstance.languages.registerCompletionItemProvider("cpp", {
5836
+ triggerCharacters: [".", ":", ">", "<"],
5837
+ provideCompletionItems(model, position) {
5838
+ const wordInfo = model.getWordUntilPosition(position);
5839
+ const range = {
5840
+ startLineNumber: position.lineNumber,
5841
+ endLineNumber: position.lineNumber,
5842
+ startColumn: wordInfo.startColumn,
5843
+ endColumn: wordInfo.endColumn
5844
+ };
5845
+ const suggestions = Object.keys(CPP_COMPLETIONS_AND_HOVERS).map((key) => {
5846
+ const item = CPP_COMPLETIONS_AND_HOVERS[key];
5847
+ return {
5848
+ label: item.label,
5849
+ kind: monacoInstance.languages.CompletionItemKind.Function,
5850
+ detail: item.detail,
5851
+ documentation: { value: item.documentation },
5852
+ insertText: item.insertText || item.label,
5853
+ insertTextRules: monacoInstance.languages.CompletionItemInsertTextRule.InsertAsSnippet,
5854
+ range
5855
+ };
5856
+ });
5857
+ return { suggestions };
5858
+ }
5859
+ });
5860
+ monacoInstance.languages.registerHoverProvider("cpp", {
5861
+ provideHover(model, position) {
5862
+ const word = model.getWordAtPosition(position);
5863
+ if (!word) return null;
5864
+ const key = CPP_COMPLETIONS_AND_HOVERS[word.word] ? word.word : CPP_COMPLETIONS_AND_HOVERS["std::" + word.word] ? "std::" + word.word : null;
5865
+ if (!key) return null;
5866
+ const item = CPP_COMPLETIONS_AND_HOVERS[key];
5867
+ return {
5868
+ range: {
5869
+ startLineNumber: position.lineNumber,
5870
+ endLineNumber: position.lineNumber,
5871
+ startColumn: word.startColumn,
5872
+ endColumn: word.endColumn
5873
+ },
5874
+ contents: [
5875
+ { value: `**${item.label}** \u2014 \`${item.detail}\`` },
5876
+ { value: item.documentation }
5877
+ ]
5878
+ };
5879
+ }
5880
+ });
5881
+ return true;
5882
+ } catch (err) {
5883
+ if (typeof console !== "undefined" && console.warn) {
5884
+ console.warn("[C++ Monaco Intelligence Error]:", err);
5885
+ }
5886
+ return false;
5887
+ }
5888
+ }
5889
+ function analyzeCppSource(source, filename = "main.cpp", vfs) {
5890
+ const diagnostics = [];
5891
+ if (!source || typeof source !== "string") return diagnostics;
5892
+ const lines = source.split("\n");
5893
+ const stack = [];
5894
+ const matchingPairs = { "}": "{", ")": "(", "]": "[" };
5895
+ let inBlockComment = false;
5896
+ for (let l = 0; l < lines.length; l++) {
5897
+ const line = lines[l];
5898
+ const lineNum = l + 1;
5899
+ let inString = false;
5900
+ let inChar = false;
5901
+ let stringQuote = "";
5902
+ for (let c = 0; c < line.length; c++) {
5903
+ const ch = line[c];
5904
+ const next = line[c + 1] || "";
5905
+ if (inBlockComment) {
5906
+ if (ch === "*" && next === "/") {
5907
+ inBlockComment = false;
5908
+ c++;
5909
+ }
5910
+ continue;
5911
+ }
5912
+ if (!inString && !inChar) {
5913
+ if (ch === "/" && next === "*") {
5914
+ inBlockComment = true;
5915
+ c++;
5916
+ continue;
5917
+ }
5918
+ if (ch === "/" && next === "/") {
5919
+ break;
5920
+ }
5921
+ }
5922
+ if (!inChar && (ch === '"' || ch === "R" && next === '"')) {
5923
+ if (ch === "R") c++;
5924
+ if (c === 0 || line[c - 1] !== "\\") {
5925
+ inString = !inString;
5926
+ stringQuote = inString ? '"' : "";
5927
+ }
5928
+ continue;
5929
+ }
5930
+ if (!inString && ch === "'") {
5931
+ if (c === 0 || line[c - 1] !== "\\") {
5932
+ inChar = !inChar;
5933
+ }
5934
+ continue;
5935
+ }
5936
+ if (inString || inChar) continue;
5937
+ if (ch === "{" || ch === "(" || ch === "[") {
5938
+ stack.push({ char: ch, line: lineNum, col: c + 1 });
5939
+ } else if (ch === "}" || ch === ")" || ch === "]") {
5940
+ const expectedOpening = matchingPairs[ch];
5941
+ const last = stack.pop();
5942
+ if (!last) {
5943
+ diagnostics.push({
5944
+ id: `cpp-bracket-unmatched-${lineNum}-${c + 1}`,
5945
+ file: filename,
5946
+ line: lineNum,
5947
+ col: c + 1,
5948
+ severity: "error",
5949
+ message: `Unmatched closing bracket '${ch}' with no opening counterpart.`,
5950
+ source: "cpp-linter"
5951
+ });
5952
+ } else if (last.char !== expectedOpening) {
5953
+ diagnostics.push({
5954
+ id: `cpp-bracket-mismatch-${lineNum}-${c + 1}`,
5955
+ file: filename,
5956
+ line: lineNum,
5957
+ col: c + 1,
5958
+ severity: "error",
5959
+ message: `Mismatched bracket: found '${ch}' but expected closing for '${last.char}' from line ${last.line}.`,
5960
+ source: "cpp-linter"
5961
+ });
5962
+ }
5963
+ }
5964
+ }
5965
+ if (inString && !inBlockComment) {
5966
+ diagnostics.push({
5967
+ id: `cpp-string-unterminated-${lineNum}`,
5968
+ file: filename,
5969
+ line: lineNum,
5970
+ col: line.length,
5971
+ severity: "error",
5972
+ message: "Unterminated string literal on line.",
5973
+ source: "cpp-linter"
5974
+ });
5975
+ }
5976
+ }
5977
+ for (const unclosed of stack) {
5978
+ diagnostics.push({
5979
+ id: `cpp-bracket-unclosed-${unclosed.line}-${unclosed.col}`,
5980
+ file: filename,
5981
+ line: unclosed.line,
5982
+ col: unclosed.col,
5983
+ severity: "error",
5984
+ message: `Unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
5985
+ source: "cpp-linter"
5986
+ });
5987
+ }
5988
+ const includeRegex = /#include\s*([<"])([^>"]+)[>"]/g;
5989
+ let incMatch;
5990
+ const includedHeaders = /* @__PURE__ */ new Set();
5991
+ while ((incMatch = includeRegex.exec(source)) !== null) {
5992
+ const isAngle = incMatch[1] === "<";
5993
+ const hdr = incMatch[2].trim();
5994
+ includedHeaders.add(hdr);
5995
+ const lineIndex = source.slice(0, incMatch.index).split("\n").length;
5996
+ if (isAngle) {
5997
+ const known = STANDARD_CPP20_HEADERS.has(hdr) || hdr.startsWith("bits/") || hdr.startsWith("codelab/") || vfs && (vfs.existsSync(`/usr/include/${hdr}`) || vfs.existsSync(`/workspace/${hdr}`));
5998
+ if (!known) {
5999
+ diagnostics.push({
6000
+ id: `cpp-unknown-include-${lineIndex}`,
6001
+ file: filename,
6002
+ line: lineIndex,
6003
+ col: 1,
6004
+ severity: "warning",
6005
+ message: `Unknown or unresolvable C++ header <${hdr}>.`,
6006
+ source: "cpp-linter"
6007
+ });
6008
+ }
6009
+ }
6010
+ }
6011
+ const hasDsaHeader = includedHeaders.has("codelab/dsa.hpp") || includedHeaders.has("bits/stdc++.h");
6012
+ const dsaSymbols = ["ListNode", "TreeNode", "buildLinkedList", "linkedListToVector", "buildBinaryTree"];
6013
+ for (const sym of dsaSymbols) {
6014
+ const symRegex = new RegExp(`\\b${sym}\\b`);
6015
+ if (symRegex.test(source) && !hasDsaHeader) {
6016
+ diagnostics.push({
6017
+ id: `cpp-missing-dsa-include-${sym}`,
6018
+ file: filename,
6019
+ line: 1,
6020
+ col: 1,
6021
+ severity: "warning",
6022
+ message: `Symbol '${sym}' used without #include <codelab/dsa.hpp>.`,
6023
+ source: "cpp-linter"
6024
+ });
6025
+ break;
6026
+ }
6027
+ }
6028
+ const hasTestHeader = includedHeaders.has("codelab/test.hpp");
6029
+ const testSymbols = ["DESCRIBE", "TEST", "ASSERT_EQ", "ASSERT_NE", "ASSERT_TRUE", "ASSERT_FALSE", "CODELAB_TEST_EXIT_CODE"];
6030
+ for (const sym of testSymbols) {
6031
+ const symRegex = new RegExp(`\\b${sym}\\b`);
6032
+ if (symRegex.test(source) && !hasTestHeader) {
6033
+ diagnostics.push({
6034
+ id: `cpp-missing-test-include-${sym}`,
6035
+ file: filename,
6036
+ line: 1,
6037
+ col: 1,
6038
+ severity: "warning",
6039
+ message: `Test macro '${sym}' used without #include <codelab/test.hpp>.`,
6040
+ source: "cpp-linter"
6041
+ });
6042
+ break;
6043
+ }
6044
+ }
6045
+ for (let l = 0; l < lines.length; l++) {
6046
+ const line = lines[l];
6047
+ const assignMatch = /\bif\s*\(([^;)]*[^=!<>]=[^=][^;)]*)\)/.exec(line);
6048
+ if (assignMatch) {
6049
+ diagnostics.push({
6050
+ id: `cpp-suspicious-assign-${l + 1}`,
6051
+ file: filename,
6052
+ line: l + 1,
6053
+ col: assignMatch.index + 1,
6054
+ severity: "warning",
6055
+ message: `Suspicious assignment '=' inside 'if' condition; did you mean '=='?`,
6056
+ source: "cpp-linter"
6057
+ });
6058
+ }
6059
+ }
6060
+ const structRegex = /(?:struct|class)\s+([A-Za-z0-9_]+)\s*\{[^}]*\}\s*(?!;)(?=[A-Za-z0-9_#\s\n])/g;
6061
+ let structMatch;
6062
+ while ((structMatch = structRegex.exec(source)) !== null) {
6063
+ const lineIndex = source.slice(0, structMatch.index + structMatch[0].length).split("\n").length;
6064
+ diagnostics.push({
6065
+ id: `cpp-missing-semicolon-${lineIndex}`,
6066
+ file: filename,
6067
+ line: lineIndex,
6068
+ col: 1,
6069
+ severity: "error",
6070
+ message: `Missing semicolon ';' after '${structMatch[1]}' class/struct definition.`,
6071
+ source: "cpp-linter"
6072
+ });
6073
+ }
6074
+ return diagnostics;
6075
+ }
6076
+ function applyClangStderrDiagnostics(stderrText, diagnosticsStore, monacoInstance, activeModel) {
6077
+ const diagnostics = [];
6078
+ if (!stderrText || typeof stderrText !== "string") return diagnostics;
6079
+ if (diagnosticsStore && typeof diagnosticsStore.clear === "function") {
6080
+ diagnosticsStore.clear("clang");
6081
+ }
6082
+ const clangRegex = /(?:(?:^|\n)(?:\/workspace\/)?([^\s:\n]+)):(\d+):(\d+):\s*(fatal error|error|warning|note):\s*([^\n]+)/g;
6083
+ let match;
6084
+ let idx = 0;
6085
+ while ((match = clangRegex.exec(stderrText)) !== null) {
6086
+ const rawFile = match[1].trim();
6087
+ const line = parseInt(match[2], 10) || 1;
6088
+ const col = parseInt(match[3], 10) || 1;
6089
+ const rawKind = match[4].toLowerCase();
6090
+ const message = match[5].trim();
6091
+ let severity = "error";
6092
+ if (rawKind === "warning") severity = "warning";
6093
+ else if (rawKind === "note") severity = "info";
6094
+ const item = {
6095
+ id: `clang-${rawFile}-${line}-${col}-${idx++}`,
6096
+ file: rawFile,
6097
+ line,
6098
+ col,
6099
+ severity,
6100
+ message: `[Clang] ${message}`,
6101
+ source: "clang"
6102
+ };
6103
+ diagnostics.push(item);
6104
+ if (diagnosticsStore && typeof diagnosticsStore.add === "function") {
6105
+ diagnosticsStore.add(item);
6106
+ }
6107
+ }
6108
+ if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === "function") {
6109
+ const markers = diagnostics.map((d) => ({
6110
+ startLineNumber: d.line,
6111
+ startColumn: d.col || 1,
6112
+ endLineNumber: d.line,
6113
+ endColumn: (d.col || 1) + 20,
6114
+ message: d.message,
6115
+ severity: d.severity === "error" ? monacoInstance.MarkerSeverity.Error : d.severity === "warning" ? monacoInstance.MarkerSeverity.Warning : monacoInstance.MarkerSeverity.Info
6116
+ }));
6117
+ monacoInstance.editor.setModelMarkers(activeModel, "clang", markers);
6118
+ }
6119
+ return diagnostics;
6120
+ }
6121
+ function installCppExtension(workbench, options = {}) {
5151
6122
  const toolchain = new CppToolchainManager(options);
5152
6123
  const compilerFn = registerCppCompilerOnRuntime(toolchain);
5153
6124
  if (!workbench) return toolchain;
5154
6125
  workbench.cppToolchain = toolchain;
5155
6126
  workbench.cppCompiler = compilerFn;
5156
6127
  workbench.cppOptions = toolchain.options;
6128
+ if (typeof window !== "undefined" && window.monaco) {
6129
+ registerMonacoCppLanguageService(window.monaco);
6130
+ }
5157
6131
  if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
5158
6132
  workbench.enabledLanguages = /* @__PURE__ */ new Set(["js", "cpp"]);
5159
6133
  } else {
@@ -5183,6 +6157,35 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5183
6157
  seedCppHeadersIntoVfs(workbench.vfs, toolchain.options.extraHeaders);
5184
6158
  }
5185
6159
  workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
6160
+ if (workbench._diagnosticsStore) {
6161
+ let lintTimer = null;
6162
+ const originalOnCodeChange = workbench.options?.onCodeChange;
6163
+ workbench._cppLintHandler = (file, code) => {
6164
+ if (!file || !/\.(?:cpp|cc|cxx|hpp|h)$/.test(file)) return;
6165
+ if (lintTimer) clearTimeout(lintTimer);
6166
+ lintTimer = setTimeout(() => {
6167
+ const diags = analyzeCppSource(code, file, workbench.vfs);
6168
+ workbench._diagnosticsStore.clear("cpp-linter");
6169
+ for (const d of diags) {
6170
+ workbench._diagnosticsStore.add(d);
6171
+ }
6172
+ if (typeof window !== "undefined" && window.monaco && workbench.editor) {
6173
+ const model = workbench.editor.getModel();
6174
+ if (model) {
6175
+ const markers = diags.map((d) => ({
6176
+ startLineNumber: d.line,
6177
+ startColumn: d.col || 1,
6178
+ endLineNumber: d.line,
6179
+ endColumn: (d.col || 1) + 20,
6180
+ message: d.message,
6181
+ severity: d.severity === "error" ? window.monaco.MarkerSeverity.Error : window.monaco.MarkerSeverity.Warning
6182
+ }));
6183
+ window.monaco.editor.setModelMarkers(model, "cpp-linter", markers);
6184
+ }
6185
+ }
6186
+ }, 180);
6187
+ };
6188
+ }
5186
6189
  if (options.preload) {
5187
6190
  toolchain.ensureLoaded().catch((err) => {
5188
6191
  if (typeof workbench._appendTerminalOutput === "function") {
@@ -5193,6 +6196,8 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5193
6196
  }
5194
6197
  if (options.activate && typeof workbench.setLanguage === "function") {
5195
6198
  workbench.setLanguage("cpp");
6199
+ } else if (typeof workbench._refreshToolbarAndTabs === "function") {
6200
+ workbench._refreshToolbarAndTabs();
5196
6201
  } else if (typeof workbench._renderShell === "function" && workbench.container) {
5197
6202
  workbench._renderShell();
5198
6203
  if (typeof workbench._bindEvents === "function") workbench._bindEvents();
@@ -5200,11 +6205,26 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
5200
6205
  }
5201
6206
  return workbench;
5202
6207
  }
6208
+ function cppExtension(workbenchOrOptions, maybeOptions) {
6209
+ if (workbenchOrOptions === null) {
6210
+ const toolchain = new CppToolchainManager(maybeOptions || {});
6211
+ registerCppCompilerOnRuntime(toolchain);
6212
+ return toolchain;
6213
+ }
6214
+ if (workbenchOrOptions === void 0 || typeof workbenchOrOptions === "object" && !("enabledLanguages" in workbenchOrOptions) && !("container" in workbenchOrOptions) && !("_renderShell" in workbenchOrOptions)) {
6215
+ const opts = workbenchOrOptions || {};
6216
+ const plugin = (wb, runOpts = {}) => {
6217
+ return installCppExtension(wb, { ...opts, ...runOpts || {} });
6218
+ };
6219
+ plugin.extensionName = "cpp";
6220
+ plugin.languageId = "cpp";
6221
+ plugin.install = plugin;
6222
+ return plugin;
6223
+ }
6224
+ return installCppExtension(workbenchOrOptions, maybeOptions);
6225
+ }
5203
6226
  function createCppExtension(options = {}) {
5204
- const plugin = (workbench) => cppExtension(workbench, options);
5205
- plugin.extensionName = "cpp";
5206
- plugin.languageId = "cpp";
5207
- return plugin;
6227
+ return cppExtension(options);
5208
6228
  }
5209
6229
  var cpp_default = cppExtension;
5210
6230
  return __toCommonJS(cpp_exports);