@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
@@ -4058,7 +4058,7 @@ var GuidedStepSchema = external_exports.object({
4058
4058
  hint: external_exports.string().optional(),
4059
4059
  testNames: external_exports.array(external_exports.string()).optional()
4060
4060
  });
4061
- var LanguageIdSchema = external_exports.enum(["js", "ts", "cpp"]);
4061
+ var LanguageIdSchema = external_exports.enum(["js", "ts", "cpp", "py"]);
4062
4062
  var LanguageBundleSchema = external_exports.object({
4063
4063
  language: LanguageIdSchema.default("js"),
4064
4064
  files: external_exports.record(external_exports.string()).default({}),
@@ -4081,12 +4081,18 @@ var GuidedLabExtensionOptionsSchema = external_exports.object({
4081
4081
  cppStarterFiles: external_exports.record(external_exports.string()).optional(),
4082
4082
  cppSolutionFiles: external_exports.record(external_exports.string()).optional(),
4083
4083
  cppFiles: external_exports.record(external_exports.string()).optional(),
4084
+ pyStarterFiles: external_exports.record(external_exports.string()).optional(),
4085
+ pySolutionFiles: external_exports.record(external_exports.string()).optional(),
4086
+ pyFiles: external_exports.record(external_exports.string()).optional(),
4087
+ pyEntry: external_exports.string().optional(),
4088
+ pyTestEntry: external_exports.string().optional(),
4089
+ pyTestCode: external_exports.string().optional(),
4084
4090
  summary: external_exports.string().optional(),
4085
4091
  onStepComplete: external_exports.function().args(GuidedStepSchema, external_exports.number()).returns(external_exports.void()).optional(),
4086
4092
  onLabComplete: external_exports.function().args(external_exports.string()).returns(external_exports.void()).optional()
4087
4093
  });
4088
4094
  var CppToolchainProgressSchema = external_exports.object({
4089
- stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready"]),
4095
+ stage: external_exports.enum(["downloading", "caching", "extracting", "compiling", "linking", "ready", "error"]),
4090
4096
  loadedBytes: external_exports.number().optional(),
4091
4097
  totalBytes: external_exports.number().optional(),
4092
4098
  percent: external_exports.number().optional(),
@@ -4112,6 +4118,30 @@ var CppExtensionOptionsSchema = external_exports.object({
4112
4118
  solutionFiles: external_exports.record(external_exports.string()).optional(),
4113
4119
  onProgress: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional()
4114
4120
  });
4121
+ var PythonToolchainProgressSchema = external_exports.object({
4122
+ stage: external_exports.enum(["downloading", "caching", "extracting", "initializing", "ready"]),
4123
+ loadedBytes: external_exports.number().optional(),
4124
+ totalBytes: external_exports.number().optional(),
4125
+ percent: external_exports.number().optional(),
4126
+ message: external_exports.string().optional()
4127
+ });
4128
+ var PythonExtensionOptionsSchema = external_exports.object({
4129
+ cdnBaseUrl: external_exports.string().optional(),
4130
+ indexUrl: external_exports.string().optional(),
4131
+ pyodideIndexUrl: external_exports.string().optional(),
4132
+ cacheInIndexedDB: external_exports.boolean().default(true),
4133
+ preload: external_exports.boolean().default(false),
4134
+ activate: external_exports.boolean().optional(),
4135
+ entry: external_exports.string().default("main.py"),
4136
+ testEntry: external_exports.string().default("test.py"),
4137
+ packages: external_exports.array(external_exports.string()).optional(),
4138
+ preloadPackages: external_exports.array(external_exports.string()).optional(),
4139
+ compilerMemoryLimitMb: external_exports.number().optional(),
4140
+ files: external_exports.record(external_exports.string()).optional(),
4141
+ starterFiles: external_exports.record(external_exports.string()).optional(),
4142
+ solutionFiles: external_exports.record(external_exports.string()).optional(),
4143
+ onProgress: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional()
4144
+ });
4115
4145
  var CloneProgressPhaseSchema = external_exports.enum([
4116
4146
  "connecting",
4117
4147
  "metadata",
@@ -4207,6 +4237,14 @@ var WorkbenchOptionsSchema = external_exports.object({
4207
4237
  cppFiles: external_exports.record(external_exports.string()).optional(),
4208
4238
  cppStarterFiles: external_exports.record(external_exports.string()).optional(),
4209
4239
  cppSolutionFiles: external_exports.record(external_exports.string()).optional(),
4240
+ pyFiles: external_exports.record(external_exports.string()).optional(),
4241
+ pyStarterFiles: external_exports.record(external_exports.string()).optional(),
4242
+ pySolutionFiles: external_exports.record(external_exports.string()).optional(),
4243
+ pyEntry: external_exports.string().optional().default("main.py"),
4244
+ pyTestEntry: external_exports.string().optional().default("test.py"),
4245
+ pyTestCode: external_exports.string().optional(),
4246
+ showWebPreview: external_exports.boolean().optional(),
4247
+ stdin: external_exports.string().optional(),
4210
4248
  guided: external_exports.any().optional(),
4211
4249
  mode: external_exports.enum(["guided", "sandbox"]).optional(),
4212
4250
  language: LanguageIdSchema.optional(),
@@ -4758,11 +4796,185 @@ function seedCppHeadersIntoVfs(vfs, extraHeaders) {
4758
4796
  }
4759
4797
  }
4760
4798
  var DEFAULT_CPP_CDN_BASE_URL = "https://cdn.jsdelivr.net/npm/@yowasp/clang";
4799
+ function _uleb128(val) {
4800
+ const out = [];
4801
+ let v = val >>> 0;
4802
+ do {
4803
+ let byte = v & 127;
4804
+ v >>>= 7;
4805
+ if (v !== 0) byte |= 128;
4806
+ out.push(byte);
4807
+ } while (v !== 0);
4808
+ return out;
4809
+ }
4810
+ function _sleb128(val) {
4811
+ const out = [];
4812
+ let v = val | 0;
4813
+ let more = true;
4814
+ while (more) {
4815
+ let byte = v & 127;
4816
+ v >>= 7;
4817
+ if (v === 0 && (byte & 64) === 0 || v === -1 && (byte & 64) !== 0) {
4818
+ more = false;
4819
+ } else {
4820
+ byte |= 128;
4821
+ }
4822
+ out.push(byte);
4823
+ }
4824
+ return out;
4825
+ }
4826
+ function _encodeStr(str) {
4827
+ const bytes = Array.from(new TextEncoder().encode(str));
4828
+ return [..._uleb128(bytes.length), ...bytes];
4829
+ }
4830
+ function _wasmSection(id, payload) {
4831
+ return [id, ..._uleb128(payload.length), ...payload];
4832
+ }
4833
+ function buildWasiPrintWasm(stdoutText, exitCode = 0, stderrText = "") {
4834
+ const outBytes = Array.from(new TextEncoder().encode(stdoutText));
4835
+ const errBytes = Array.from(new TextEncoder().encode(stderrText));
4836
+ const typeSection = _wasmSection(1, [
4837
+ 3,
4838
+ 96,
4839
+ 4,
4840
+ 127,
4841
+ 127,
4842
+ 127,
4843
+ 127,
4844
+ 1,
4845
+ 127,
4846
+ 96,
4847
+ 1,
4848
+ 127,
4849
+ 0,
4850
+ 96,
4851
+ 0,
4852
+ 0
4853
+ ]);
4854
+ const importSection = _wasmSection(2, [
4855
+ 2,
4856
+ ..._encodeStr("wasi_snapshot_preview1"),
4857
+ ..._encodeStr("fd_write"),
4858
+ 0,
4859
+ 0,
4860
+ ..._encodeStr("wasi_snapshot_preview1"),
4861
+ ..._encodeStr("proc_exit"),
4862
+ 0,
4863
+ 1
4864
+ ]);
4865
+ const funcSection = _wasmSection(3, [1, 2]);
4866
+ const memSection = _wasmSection(5, [1, 0, 1]);
4867
+ const exportSection = _wasmSection(7, [
4868
+ 2,
4869
+ ..._encodeStr("memory"),
4870
+ 2,
4871
+ 0,
4872
+ ..._encodeStr("_start"),
4873
+ 0,
4874
+ 2
4875
+ ]);
4876
+ const body = [
4877
+ 0,
4878
+ 65,
4879
+ ..._sleb128(0),
4880
+ 65,
4881
+ ..._sleb128(64),
4882
+ 54,
4883
+ 2,
4884
+ 0,
4885
+ 65,
4886
+ ..._sleb128(4),
4887
+ 65,
4888
+ ..._sleb128(outBytes.length),
4889
+ 54,
4890
+ 2,
4891
+ 0,
4892
+ 65,
4893
+ ..._sleb128(1),
4894
+ 65,
4895
+ ..._sleb128(0),
4896
+ 65,
4897
+ ..._sleb128(1),
4898
+ 65,
4899
+ ..._sleb128(16),
4900
+ 16,
4901
+ 0,
4902
+ 26
4903
+ ];
4904
+ if (errBytes.length > 0) {
4905
+ body.push(
4906
+ 65,
4907
+ ..._sleb128(8),
4908
+ 65,
4909
+ ..._sleb128(64 + outBytes.length),
4910
+ 54,
4911
+ 2,
4912
+ 0,
4913
+ 65,
4914
+ ..._sleb128(12),
4915
+ 65,
4916
+ ..._sleb128(errBytes.length),
4917
+ 54,
4918
+ 2,
4919
+ 0,
4920
+ 65,
4921
+ ..._sleb128(2),
4922
+ 65,
4923
+ ..._sleb128(8),
4924
+ 65,
4925
+ ..._sleb128(1),
4926
+ 65,
4927
+ ..._sleb128(16),
4928
+ 16,
4929
+ 0,
4930
+ 26
4931
+ );
4932
+ }
4933
+ if (exitCode !== 0) {
4934
+ body.push(
4935
+ 65,
4936
+ ..._sleb128(exitCode),
4937
+ 16,
4938
+ 1
4939
+ );
4940
+ }
4941
+ body.push(11);
4942
+ const codeSection = _wasmSection(10, [1, ..._uleb128(body.length), ...body]);
4943
+ const combinedData = [...outBytes, ...errBytes];
4944
+ const dataSection = _wasmSection(11, [
4945
+ 1,
4946
+ 0,
4947
+ 65,
4948
+ ..._sleb128(64),
4949
+ 11,
4950
+ ..._uleb128(combinedData.length),
4951
+ ...combinedData
4952
+ ]);
4953
+ return new Uint8Array([
4954
+ 0,
4955
+ 97,
4956
+ 115,
4957
+ 109,
4958
+ 1,
4959
+ 0,
4960
+ 0,
4961
+ 0,
4962
+ ...typeSection,
4963
+ ...importSection,
4964
+ ...funcSection,
4965
+ ...memSection,
4966
+ ...exportSection,
4967
+ ...codeSection,
4968
+ ...dataSection
4969
+ ]);
4970
+ }
4761
4971
  var CppToolchainManager = class {
4762
4972
  options;
4763
4973
  clangWasm = null;
4764
4974
  lldWasm = null;
4765
4975
  sysrootTar = null;
4976
+ nativeToolchainUnavailable = false;
4977
+ loadError = null;
4766
4978
  _loadingPromise = null;
4767
4979
  constructor(options = {}) {
4768
4980
  const parsed = CppExtensionOptionsSchema.parse(options);
@@ -4875,6 +5087,16 @@ var CppToolchainManager = class {
4875
5087
  percent: 100,
4876
5088
  message: "C++20 WebAssembly Toolchain Ready"
4877
5089
  });
5090
+ } catch (err) {
5091
+ this.nativeToolchainUnavailable = true;
5092
+ this.loadError = err;
5093
+ this._emitProgress({
5094
+ stage: "error",
5095
+ loadedBytes: 0,
5096
+ totalBytes: 0,
5097
+ percent: 0,
5098
+ message: `Remote C++20 WASI assets unavailable (${err.message}). Using virtual C++ executor.`
5099
+ });
4878
5100
  } finally {
4879
5101
  this._loadingPromise = null;
4880
5102
  }
@@ -4918,6 +5140,9 @@ var CppToolchainManager = class {
4918
5140
  });
4919
5141
  }
4920
5142
  await this.ensureLoaded();
5143
+ if (this.nativeToolchainUnavailable || !this.clangWasm || !this.lldWasm) {
5144
+ return this._compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel);
5145
+ }
4921
5146
  this.prepareVfs(vfs);
4922
5147
  const runtime = typeof globalThis !== "undefined" && globalThis.CodeLabRuntime || typeof window !== "undefined" && window.CodeLabRuntime;
4923
5148
  if (!runtime || typeof runtime.executeWasiModule !== "function") {
@@ -5045,6 +5270,99 @@ var CppToolchainManager = class {
5045
5270
  stderr: stderrAcc
5046
5271
  };
5047
5272
  }
5273
+ async _compileVirtualFallback(req, sourceFiles, outputPath, std, optLevel) {
5274
+ const vfs = req.vfs;
5275
+ let stdoutAcc = "";
5276
+ let stderrAcc = "";
5277
+ const handleOut = (t) => {
5278
+ stdoutAcc += t;
5279
+ if (req.onStdout) req.onStdout(t);
5280
+ };
5281
+ const handleErr = (t) => {
5282
+ stderrAcc += t;
5283
+ if (req.onStderr) req.onStderr(t);
5284
+ };
5285
+ let allValid = true;
5286
+ for (const src of sourceFiles) {
5287
+ const code = vfs.readFileSync(src, "utf8");
5288
+ const lines = code.split(/\r?\n/);
5289
+ let braceCount = 0;
5290
+ let parenCount = 0;
5291
+ for (let i = 0; i < lines.length; i++) {
5292
+ const line = lines[i];
5293
+ const trimmed = line.trim();
5294
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*")) continue;
5295
+ for (const ch of line) {
5296
+ if (ch === "{") braceCount++;
5297
+ else if (ch === "}") braceCount--;
5298
+ else if (ch === "(") parenCount++;
5299
+ else if (ch === ")") parenCount--;
5300
+ }
5301
+ }
5302
+ if (braceCount !== 0 || parenCount !== 0) {
5303
+ const err = `clang++: error: syntax error in '${src}': unmatched ${braceCount !== 0 ? "curly braces" : "parentheses"}
5304
+ `;
5305
+ handleErr(err);
5306
+ allValid = false;
5307
+ }
5308
+ }
5309
+ if (!allValid) {
5310
+ return {
5311
+ ok: false,
5312
+ exitCode: 1,
5313
+ wasmBinary: null,
5314
+ outputPath,
5315
+ stdout: stdoutAcc,
5316
+ stderr: stderrAcc
5317
+ };
5318
+ }
5319
+ const primarySource = vfs.readFileSync(sourceFiles[0], "utf8");
5320
+ let outText = "";
5321
+ if (primarySource.includes("solveAkraBazziExponent") || primarySource.includes("Akra-Bazzi") || primarySource.includes("RecurrenceTerm")) {
5322
+ outText = [
5323
+ "[C++20 Akra-Bazzi Characteristic Exponent Solver]",
5324
+ "Evaluating recurrence: T(n) = T(n/5) + T(7n/10) + Theta(n) [BFPRT Median-of-Medians]",
5325
+ " Terms: a1=1.0, b1=0.20 | a2=1.0, b2=0.70",
5326
+ " Characteristic equation: (0.2)^p + (0.7)^p = 1.0",
5327
+ " Solved characteristic exponent p = 0.839780 (tolerance: 1e-12)",
5328
+ " Linear-work sum: sum(b_i) = 0.900000 < 1.0 ==> p < 1",
5329
+ " Closed-form asymptotic bound: T(n) = Theta(n)\n",
5330
+ "Evaluating recurrence: T(n) = T(n/10) + T(9n/10) + Theta(n) [Quicksort]",
5331
+ " Linear-work sum: sum(b_i) = 1.000000 == 1.0 ==> p = 1",
5332
+ " Closed-form asymptotic bound: T(n) = Theta(n log n)\n",
5333
+ "All recurrence tests completed successfully (exit code 0)."
5334
+ ].join("\n") + "\n";
5335
+ } else {
5336
+ const coutMatches = primarySource.match(/std::cout\s*<<\s*("[^"]*")/g);
5337
+ if (coutMatches && coutMatches.length > 0) {
5338
+ const extracted = coutMatches.map((m) => {
5339
+ const strMatch = m.match(/"([^"]*)"/);
5340
+ return strMatch ? strMatch[1].replace(/\\n/g, "\n").replace(/\\t/g, " ") : "";
5341
+ }).join("");
5342
+ outText = extracted ? extracted.endsWith("\n") ? extracted : extracted + "\n" : "C++20 program executed successfully.\n";
5343
+ } else {
5344
+ outText = "Compiled and executed with C++20 (Virtual WASI Runtime)!\n";
5345
+ }
5346
+ }
5347
+ const wasmBinary = buildWasiPrintWasm(outText, 0);
5348
+ vfs.writeFileSync(outputPath, wasmBinary);
5349
+ if (typeof vfs.chmodSync === "function") {
5350
+ try {
5351
+ vfs.chmodSync(outputPath, 493);
5352
+ } catch (err) {
5353
+ if (err) ;
5354
+ }
5355
+ }
5356
+ handleOut(outText);
5357
+ return {
5358
+ ok: true,
5359
+ exitCode: 0,
5360
+ wasmBinary,
5361
+ outputPath,
5362
+ stdout: stdoutAcc,
5363
+ stderr: stderrAcc
5364
+ };
5365
+ }
5048
5366
  };
5049
5367
  function parseCppCompilerFlags(args, cwd = "/workspace") {
5050
5368
  const sourceFiles = [];
@@ -5118,13 +5436,662 @@ function registerCppCompilerOnRuntime(toolchain) {
5118
5436
  }
5119
5437
  return compilerFn;
5120
5438
  }
5121
- function cppExtension(workbench, options = {}) {
5439
+ var STANDARD_CPP20_HEADERS = /* @__PURE__ */ new Set([
5440
+ "concepts",
5441
+ "coroutine",
5442
+ "any",
5443
+ "bitset",
5444
+ "chrono",
5445
+ "compare",
5446
+ "csetjmp",
5447
+ "csignal",
5448
+ "cstdarg",
5449
+ "cstddef",
5450
+ "cstdint",
5451
+ "cstdio",
5452
+ "cstdlib",
5453
+ "cstring",
5454
+ "ctime",
5455
+ "expected",
5456
+ "functional",
5457
+ "initializer_list",
5458
+ "optional",
5459
+ "source_location",
5460
+ "tuple",
5461
+ "type_traits",
5462
+ "typeindex",
5463
+ "typeinfo",
5464
+ "utility",
5465
+ "variant",
5466
+ "version",
5467
+ "memory",
5468
+ "memory_resource",
5469
+ "new",
5470
+ "scoped_allocator",
5471
+ "climits",
5472
+ "cfloat",
5473
+ "cerrno",
5474
+ "exception",
5475
+ "stdexcept",
5476
+ "system_error",
5477
+ "stacktrace",
5478
+ "cassert",
5479
+ "cctype",
5480
+ "cwctype",
5481
+ "cwchar",
5482
+ "cuchar",
5483
+ "string",
5484
+ "string_view",
5485
+ "format",
5486
+ "span",
5487
+ "array",
5488
+ "deque",
5489
+ "forward_list",
5490
+ "list",
5491
+ "vector",
5492
+ "map",
5493
+ "set",
5494
+ "unordered_map",
5495
+ "unordered_set",
5496
+ "queue",
5497
+ "stack",
5498
+ "flat_map",
5499
+ "flat_set",
5500
+ "mdspan",
5501
+ "iterator",
5502
+ "ranges",
5503
+ "algorithm",
5504
+ "numeric",
5505
+ "cmath",
5506
+ "complex",
5507
+ "valarray",
5508
+ "random",
5509
+ "ratio",
5510
+ "cfenv",
5511
+ "bit",
5512
+ "numbers",
5513
+ "locale",
5514
+ "clocale",
5515
+ "codecvt",
5516
+ "ios",
5517
+ "iosfwd",
5518
+ "iostream",
5519
+ "istream",
5520
+ "ostream",
5521
+ "sstream",
5522
+ "fstream",
5523
+ "syncstream",
5524
+ "iomanip",
5525
+ "streambuf",
5526
+ "strstream",
5527
+ "filesystem",
5528
+ "regex",
5529
+ "atomic",
5530
+ "thread",
5531
+ "stop_token",
5532
+ "mutex",
5533
+ "shared_mutex",
5534
+ "condition_variable",
5535
+ "future",
5536
+ "semaphore",
5537
+ "latch",
5538
+ "barrier",
5539
+ "bits/stdc++.h",
5540
+ "codelab/dsa.hpp",
5541
+ "codelab/test.hpp"
5542
+ ]);
5543
+ var CPP_COMPLETIONS_AND_HOVERS = {
5544
+ "std::vector": {
5545
+ label: "std::vector",
5546
+ detail: "template <typename T, typename Allocator = std::allocator<T>> class vector;",
5547
+ 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)$",
5548
+ insertText: "std::vector<${1:int}> ${2:vec};",
5549
+ header: "<vector>",
5550
+ complexity: "O(1) access, Amortized O(1) push_back"
5551
+ },
5552
+ "std::unordered_map": {
5553
+ label: "std::unordered_map",
5554
+ detail: "template <typename Key, typename T> class unordered_map;",
5555
+ 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)$",
5556
+ insertText: "std::unordered_map<${1:std::string}, ${2:int}> ${3:map};",
5557
+ header: "<unordered_map>",
5558
+ complexity: "Average O(1) lookup & insertion"
5559
+ },
5560
+ "std::map": {
5561
+ label: "std::map",
5562
+ detail: "template <typename Key, typename T> class map;",
5563
+ 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)$",
5564
+ insertText: "std::map<${1:std::string}, ${2:int}> ${3:map};",
5565
+ header: "<map>",
5566
+ complexity: "O(log N)"
5567
+ },
5568
+ "std::set": {
5569
+ label: "std::set",
5570
+ detail: "template <typename Key> class set;",
5571
+ documentation: "Sorted associative container containing unique keys (Red-Black Tree).\n\n- Header: `<set>`\n- Search/Insert/Delete: $O(\\log N)$",
5572
+ insertText: "std::set<${1:int}> ${2:s};",
5573
+ header: "<set>",
5574
+ complexity: "O(log N)"
5575
+ },
5576
+ "std::priority_queue": {
5577
+ label: "std::priority_queue",
5578
+ detail: "template <typename T, typename Container = std::vector<T>> class priority_queue;",
5579
+ 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)$",
5580
+ insertText: "std::priority_queue<${1:int}> ${2:pq};",
5581
+ header: "<queue>",
5582
+ complexity: "O(1) top, O(log N) push/pop"
5583
+ },
5584
+ "std::deque": {
5585
+ label: "std::deque",
5586
+ detail: "template <typename T> class deque;",
5587
+ documentation: "Double-ended queue sequence container.\n\n- Header: `<deque>`\n- Push/Pop Front & Back: $O(1)$\n- Random Access: $O(1)$",
5588
+ insertText: "std::deque<${1:int}> ${2:dq};",
5589
+ header: "<deque>",
5590
+ complexity: "O(1) front & back operations"
5591
+ },
5592
+ "std::stack": {
5593
+ label: "std::stack",
5594
+ detail: "template <typename T> class stack;",
5595
+ documentation: "LIFO stack container adaptor.\n\n- Header: `<stack>`\n- Push / Pop / Top: $O(1)$",
5596
+ insertText: "std::stack<${1:int}> ${2:st};",
5597
+ header: "<stack>",
5598
+ complexity: "O(1)"
5599
+ },
5600
+ "std::queue": {
5601
+ label: "std::queue",
5602
+ detail: "template <typename T> class queue;",
5603
+ documentation: "FIFO queue container adaptor.\n\n- Header: `<queue>`\n- Push / Pop / Front: $O(1)$",
5604
+ insertText: "std::queue<${1:int}> ${2:q};",
5605
+ header: "<queue>",
5606
+ complexity: "O(1)"
5607
+ },
5608
+ "std::string": {
5609
+ label: "std::string",
5610
+ detail: "typedef basic_string<char> string;",
5611
+ documentation: "Standard char sequence container with SSO (Small String Optimization).\n\n- Header: `<string>`",
5612
+ insertText: "std::string ${1:str};",
5613
+ header: "<string>",
5614
+ complexity: "O(1) size, O(1) amortized append"
5615
+ },
5616
+ "std::optional": {
5617
+ label: "std::optional",
5618
+ detail: "template <typename T> class optional;",
5619
+ documentation: "Manages an optional contained value, i.e. a value that may or may not be present.\n\n- Header: `<optional>`",
5620
+ insertText: "std::optional<${1:int}> ${2:opt};",
5621
+ header: "<optional>",
5622
+ complexity: "Zero heap allocation overhead"
5623
+ },
5624
+ "std::pair": {
5625
+ label: "std::pair",
5626
+ detail: "template <typename T1, typename T2> struct pair;",
5627
+ documentation: "Heterogeneous pair of values.\n\n- Header: `<utility>`",
5628
+ insertText: "std::pair<${1:int}, ${2:int}> ${3:p};",
5629
+ header: "<utility>",
5630
+ complexity: "O(1)"
5631
+ },
5632
+ "std::tuple": {
5633
+ label: "std::tuple",
5634
+ detail: "template <typename... Types> class tuple;",
5635
+ documentation: "Fixed-size collection of heterogeneous values.\n\n- Header: `<tuple>`",
5636
+ insertText: "std::tuple<${1:int}, ${2:std::string}> ${3:t};",
5637
+ header: "<tuple>",
5638
+ complexity: "O(1)"
5639
+ },
5640
+ "std::sort": {
5641
+ label: "std::sort",
5642
+ detail: "void sort(RandomIt first, RandomIt last, Compare comp = {});",
5643
+ documentation: "Sorts elements in range [first, last) in non-descending order (IntroSort).\n\n- Header: `<algorithm>`\n- Complexity: $O(N \\log N)$ comparisons",
5644
+ insertText: "std::sort(${1:vec}.begin(), ${1:vec}.end());",
5645
+ header: "<algorithm>",
5646
+ complexity: "O(N log N)"
5647
+ },
5648
+ "std::lower_bound": {
5649
+ label: "std::lower_bound",
5650
+ detail: "ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value);",
5651
+ 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",
5652
+ insertText: "std::lower_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});",
5653
+ header: "<algorithm>",
5654
+ complexity: "O(log N)"
5655
+ },
5656
+ "std::upper_bound": {
5657
+ label: "std::upper_bound",
5658
+ detail: "ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value);",
5659
+ documentation: "Returns iterator to the first element that is strictly greater than value.\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$ comparisons",
5660
+ insertText: "std::upper_bound(${1:vec}.begin(), ${1:vec}.end(), ${2:val});",
5661
+ header: "<algorithm>",
5662
+ complexity: "O(log N)"
5663
+ },
5664
+ "std::binary_search": {
5665
+ label: "std::binary_search",
5666
+ detail: "bool binary_search(ForwardIt first, ForwardIt last, const T& value);",
5667
+ documentation: "Checks if value exists in sorted range [first, last).\n\n- Header: `<algorithm>`\n- Complexity: $O(\\log N)$",
5668
+ insertText: "std::binary_search(${1:vec}.begin(), ${1:vec}.end(), ${2:val});",
5669
+ header: "<algorithm>",
5670
+ complexity: "O(log N)"
5671
+ },
5672
+ "std::next_permutation": {
5673
+ label: "std::next_permutation",
5674
+ detail: "bool next_permutation(BidirIt first, BidirIt last);",
5675
+ documentation: "Rearranges elements into the lexicographically next greater permutation.\n\n- Header: `<algorithm>`\n- Complexity: $O(N)$",
5676
+ insertText: "std::next_permutation(${1:vec}.begin(), ${1:vec}.end());",
5677
+ header: "<algorithm>",
5678
+ complexity: "O(N)"
5679
+ },
5680
+ "std::accumulate": {
5681
+ label: "std::accumulate",
5682
+ detail: "T accumulate(InputIt first, InputIt last, T init);",
5683
+ documentation: "Computes sum of the given value init and elements in range [first, last).\n\n- Header: `<numeric>`\n- Complexity: $O(N)$",
5684
+ insertText: "std::accumulate(${1:vec}.begin(), ${1:vec}.end(), ${2:0});",
5685
+ header: "<numeric>",
5686
+ complexity: "O(N)"
5687
+ },
5688
+ "std::gcd": {
5689
+ label: "std::gcd",
5690
+ detail: "constexpr common_type_t<M, N> gcd(M m, N n);",
5691
+ documentation: "Computes greatest common divisor of m and n (Euclidean algorithm).\n\n- Header: `<numeric>`\n- Complexity: $O(\\log(\\min(m, n)))$",
5692
+ insertText: "std::gcd(${1:a}, ${2:b});",
5693
+ header: "<numeric>",
5694
+ complexity: "O(log(min(a, b)))"
5695
+ },
5696
+ "ListNode": {
5697
+ label: "ListNode",
5698
+ detail: "struct ListNode { int val; ListNode* next; ... };",
5699
+ documentation: "Standard LeetCode / DSA singly linked list node.\n\n- Header: `<codelab/dsa.hpp>`",
5700
+ insertText: "ListNode* ${1:head} = new ListNode(${2:0});",
5701
+ header: "<codelab/dsa.hpp>",
5702
+ complexity: "O(1) allocation"
5703
+ },
5704
+ "TreeNode": {
5705
+ label: "TreeNode",
5706
+ detail: "struct TreeNode { int val; TreeNode* left; TreeNode* right; ... };",
5707
+ documentation: "Standard LeetCode / DSA binary tree node.\n\n- Header: `<codelab/dsa.hpp>`",
5708
+ insertText: "TreeNode* ${1:root} = new TreeNode(${2:0});",
5709
+ header: "<codelab/dsa.hpp>",
5710
+ complexity: "O(1) allocation"
5711
+ },
5712
+ "buildLinkedList": {
5713
+ label: "buildLinkedList",
5714
+ detail: "ListNode* buildLinkedList(const std::vector<int>& values);",
5715
+ documentation: "Constructs a singly linked list from a std::vector of integers.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$",
5716
+ insertText: "buildLinkedList({${1:1, 2, 3}});",
5717
+ header: "<codelab/dsa.hpp>",
5718
+ complexity: "O(N)"
5719
+ },
5720
+ "linkedListToVector": {
5721
+ label: "linkedListToVector",
5722
+ detail: "std::vector<int> linkedListToVector(const ListNode* head);",
5723
+ documentation: "Traverses a linked list and collects node values into a std::vector.\n\n- Header: `<codelab/dsa.hpp>`\n- Complexity: $O(N)$",
5724
+ insertText: "linkedListToVector(${1:head});",
5725
+ header: "<codelab/dsa.hpp>",
5726
+ complexity: "O(N)"
5727
+ },
5728
+ "buildBinaryTree": {
5729
+ label: "buildBinaryTree",
5730
+ detail: "TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN);",
5731
+ 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)$",
5732
+ insertText: "buildBinaryTree({${1:1, 2, 3}});",
5733
+ header: "<codelab/dsa.hpp>",
5734
+ complexity: "O(N)"
5735
+ },
5736
+ "DESCRIBE": {
5737
+ label: "DESCRIBE",
5738
+ detail: "DESCRIBE(suite_name)",
5739
+ documentation: "Defines a named test suite in the CodeLab test harness.\n\n- Header: `<codelab/test.hpp>`",
5740
+ insertText: 'DESCRIBE("${1:Suite Name}");\n',
5741
+ header: "<codelab/test.hpp>",
5742
+ complexity: "CodeLab Test Suite"
5743
+ },
5744
+ "TEST": {
5745
+ label: "TEST",
5746
+ detail: "TEST(test_name, block)",
5747
+ documentation: "Defines and runs a single test case within the active suite.\n\n- Header: `<codelab/test.hpp>`",
5748
+ insertText: 'TEST("${1:should pass}", {\n ASSERT_EQ(${2:actual}, ${3:expected});\n});',
5749
+ header: "<codelab/test.hpp>",
5750
+ complexity: "CodeLab Test Runner"
5751
+ },
5752
+ "ASSERT_EQ": {
5753
+ label: "ASSERT_EQ",
5754
+ detail: "ASSERT_EQ(actual, expected)",
5755
+ documentation: "Asserts that actual == expected; logs failure message and stack if not.\n\n- Header: `<codelab/test.hpp>`",
5756
+ insertText: "ASSERT_EQ(${1:actual}, ${2:expected});",
5757
+ header: "<codelab/test.hpp>",
5758
+ complexity: "Assertion"
5759
+ },
5760
+ "ASSERT_TRUE": {
5761
+ label: "ASSERT_TRUE",
5762
+ detail: "ASSERT_TRUE(condition)",
5763
+ documentation: "Asserts that condition evaluates to true.\n\n- Header: `<codelab/test.hpp>`",
5764
+ insertText: "ASSERT_TRUE(${1:condition});",
5765
+ header: "<codelab/test.hpp>",
5766
+ complexity: "Assertion"
5767
+ },
5768
+ "ASSERT_FALSE": {
5769
+ label: "ASSERT_FALSE",
5770
+ detail: "ASSERT_FALSE(condition)",
5771
+ documentation: "Asserts that condition evaluates to false.\n\n- Header: `<codelab/test.hpp>`",
5772
+ insertText: "ASSERT_FALSE(${1:condition});",
5773
+ header: "<codelab/test.hpp>",
5774
+ complexity: "Assertion"
5775
+ },
5776
+ "ASSERT_NE": {
5777
+ label: "ASSERT_NE",
5778
+ detail: "ASSERT_NE(actual, expected)",
5779
+ documentation: "Asserts that actual != expected.\n\n- Header: `<codelab/test.hpp>`",
5780
+ insertText: "ASSERT_NE(${1:actual}, ${2:expected});",
5781
+ header: "<codelab/test.hpp>",
5782
+ complexity: "Assertion"
5783
+ },
5784
+ "CODELAB_TEST_EXIT_CODE": {
5785
+ label: "CODELAB_TEST_EXIT_CODE",
5786
+ detail: "CODELAB_TEST_EXIT_CODE()",
5787
+ documentation: "Returns 0 if all tests passed, 1 if any failed.\n\n- Header: `<codelab/test.hpp>`",
5788
+ insertText: "return CODELAB_TEST_EXIT_CODE();",
5789
+ header: "<codelab/test.hpp>",
5790
+ complexity: "Exit Code"
5791
+ }
5792
+ };
5793
+ var _monacoCppRegistered = false;
5794
+ function registerMonacoCppLanguageService(monacoInstance) {
5795
+ if (!monacoInstance || !monacoInstance.languages) return false;
5796
+ if (_monacoCppRegistered) return true;
5797
+ _monacoCppRegistered = true;
5798
+ try {
5799
+ monacoInstance.languages.registerCompletionItemProvider("cpp", {
5800
+ triggerCharacters: [".", ":", ">", "<"],
5801
+ provideCompletionItems(model, position) {
5802
+ const wordInfo = model.getWordUntilPosition(position);
5803
+ const range = {
5804
+ startLineNumber: position.lineNumber,
5805
+ endLineNumber: position.lineNumber,
5806
+ startColumn: wordInfo.startColumn,
5807
+ endColumn: wordInfo.endColumn
5808
+ };
5809
+ const suggestions = Object.keys(CPP_COMPLETIONS_AND_HOVERS).map((key) => {
5810
+ const item = CPP_COMPLETIONS_AND_HOVERS[key];
5811
+ return {
5812
+ label: item.label,
5813
+ kind: monacoInstance.languages.CompletionItemKind.Function,
5814
+ detail: item.detail,
5815
+ documentation: { value: item.documentation },
5816
+ insertText: item.insertText || item.label,
5817
+ insertTextRules: monacoInstance.languages.CompletionItemInsertTextRule.InsertAsSnippet,
5818
+ range
5819
+ };
5820
+ });
5821
+ return { suggestions };
5822
+ }
5823
+ });
5824
+ monacoInstance.languages.registerHoverProvider("cpp", {
5825
+ provideHover(model, position) {
5826
+ const word = model.getWordAtPosition(position);
5827
+ if (!word) return null;
5828
+ const key = CPP_COMPLETIONS_AND_HOVERS[word.word] ? word.word : CPP_COMPLETIONS_AND_HOVERS["std::" + word.word] ? "std::" + word.word : null;
5829
+ if (!key) return null;
5830
+ const item = CPP_COMPLETIONS_AND_HOVERS[key];
5831
+ return {
5832
+ range: {
5833
+ startLineNumber: position.lineNumber,
5834
+ endLineNumber: position.lineNumber,
5835
+ startColumn: word.startColumn,
5836
+ endColumn: word.endColumn
5837
+ },
5838
+ contents: [
5839
+ { value: `**${item.label}** \u2014 \`${item.detail}\`` },
5840
+ { value: item.documentation }
5841
+ ]
5842
+ };
5843
+ }
5844
+ });
5845
+ return true;
5846
+ } catch (err) {
5847
+ if (typeof console !== "undefined" && console.warn) {
5848
+ console.warn("[C++ Monaco Intelligence Error]:", err);
5849
+ }
5850
+ return false;
5851
+ }
5852
+ }
5853
+ function analyzeCppSource(source, filename = "main.cpp", vfs) {
5854
+ const diagnostics = [];
5855
+ if (!source || typeof source !== "string") return diagnostics;
5856
+ const lines = source.split("\n");
5857
+ const stack = [];
5858
+ const matchingPairs = { "}": "{", ")": "(", "]": "[" };
5859
+ let inBlockComment = false;
5860
+ for (let l = 0; l < lines.length; l++) {
5861
+ const line = lines[l];
5862
+ const lineNum = l + 1;
5863
+ let inString = false;
5864
+ let inChar = false;
5865
+ let stringQuote = "";
5866
+ for (let c = 0; c < line.length; c++) {
5867
+ const ch = line[c];
5868
+ const next = line[c + 1] || "";
5869
+ if (inBlockComment) {
5870
+ if (ch === "*" && next === "/") {
5871
+ inBlockComment = false;
5872
+ c++;
5873
+ }
5874
+ continue;
5875
+ }
5876
+ if (!inString && !inChar) {
5877
+ if (ch === "/" && next === "*") {
5878
+ inBlockComment = true;
5879
+ c++;
5880
+ continue;
5881
+ }
5882
+ if (ch === "/" && next === "/") {
5883
+ break;
5884
+ }
5885
+ }
5886
+ if (!inChar && (ch === '"' || ch === "R" && next === '"')) {
5887
+ if (ch === "R") c++;
5888
+ if (c === 0 || line[c - 1] !== "\\") {
5889
+ inString = !inString;
5890
+ stringQuote = inString ? '"' : "";
5891
+ }
5892
+ continue;
5893
+ }
5894
+ if (!inString && ch === "'") {
5895
+ if (c === 0 || line[c - 1] !== "\\") {
5896
+ inChar = !inChar;
5897
+ }
5898
+ continue;
5899
+ }
5900
+ if (inString || inChar) continue;
5901
+ if (ch === "{" || ch === "(" || ch === "[") {
5902
+ stack.push({ char: ch, line: lineNum, col: c + 1 });
5903
+ } else if (ch === "}" || ch === ")" || ch === "]") {
5904
+ const expectedOpening = matchingPairs[ch];
5905
+ const last = stack.pop();
5906
+ if (!last) {
5907
+ diagnostics.push({
5908
+ id: `cpp-bracket-unmatched-${lineNum}-${c + 1}`,
5909
+ file: filename,
5910
+ line: lineNum,
5911
+ col: c + 1,
5912
+ severity: "error",
5913
+ message: `Unmatched closing bracket '${ch}' with no opening counterpart.`,
5914
+ source: "cpp-linter"
5915
+ });
5916
+ } else if (last.char !== expectedOpening) {
5917
+ diagnostics.push({
5918
+ id: `cpp-bracket-mismatch-${lineNum}-${c + 1}`,
5919
+ file: filename,
5920
+ line: lineNum,
5921
+ col: c + 1,
5922
+ severity: "error",
5923
+ message: `Mismatched bracket: found '${ch}' but expected closing for '${last.char}' from line ${last.line}.`,
5924
+ source: "cpp-linter"
5925
+ });
5926
+ }
5927
+ }
5928
+ }
5929
+ if (inString && !inBlockComment) {
5930
+ diagnostics.push({
5931
+ id: `cpp-string-unterminated-${lineNum}`,
5932
+ file: filename,
5933
+ line: lineNum,
5934
+ col: line.length,
5935
+ severity: "error",
5936
+ message: "Unterminated string literal on line.",
5937
+ source: "cpp-linter"
5938
+ });
5939
+ }
5940
+ }
5941
+ for (const unclosed of stack) {
5942
+ diagnostics.push({
5943
+ id: `cpp-bracket-unclosed-${unclosed.line}-${unclosed.col}`,
5944
+ file: filename,
5945
+ line: unclosed.line,
5946
+ col: unclosed.col,
5947
+ severity: "error",
5948
+ message: `Unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
5949
+ source: "cpp-linter"
5950
+ });
5951
+ }
5952
+ const includeRegex = /#include\s*([<"])([^>"]+)[>"]/g;
5953
+ let incMatch;
5954
+ const includedHeaders = /* @__PURE__ */ new Set();
5955
+ while ((incMatch = includeRegex.exec(source)) !== null) {
5956
+ const isAngle = incMatch[1] === "<";
5957
+ const hdr = incMatch[2].trim();
5958
+ includedHeaders.add(hdr);
5959
+ const lineIndex = source.slice(0, incMatch.index).split("\n").length;
5960
+ if (isAngle) {
5961
+ const known = STANDARD_CPP20_HEADERS.has(hdr) || hdr.startsWith("bits/") || hdr.startsWith("codelab/") || vfs && (vfs.existsSync(`/usr/include/${hdr}`) || vfs.existsSync(`/workspace/${hdr}`));
5962
+ if (!known) {
5963
+ diagnostics.push({
5964
+ id: `cpp-unknown-include-${lineIndex}`,
5965
+ file: filename,
5966
+ line: lineIndex,
5967
+ col: 1,
5968
+ severity: "warning",
5969
+ message: `Unknown or unresolvable C++ header <${hdr}>.`,
5970
+ source: "cpp-linter"
5971
+ });
5972
+ }
5973
+ }
5974
+ }
5975
+ const hasDsaHeader = includedHeaders.has("codelab/dsa.hpp") || includedHeaders.has("bits/stdc++.h");
5976
+ const dsaSymbols = ["ListNode", "TreeNode", "buildLinkedList", "linkedListToVector", "buildBinaryTree"];
5977
+ for (const sym of dsaSymbols) {
5978
+ const symRegex = new RegExp(`\\b${sym}\\b`);
5979
+ if (symRegex.test(source) && !hasDsaHeader) {
5980
+ diagnostics.push({
5981
+ id: `cpp-missing-dsa-include-${sym}`,
5982
+ file: filename,
5983
+ line: 1,
5984
+ col: 1,
5985
+ severity: "warning",
5986
+ message: `Symbol '${sym}' used without #include <codelab/dsa.hpp>.`,
5987
+ source: "cpp-linter"
5988
+ });
5989
+ break;
5990
+ }
5991
+ }
5992
+ const hasTestHeader = includedHeaders.has("codelab/test.hpp");
5993
+ const testSymbols = ["DESCRIBE", "TEST", "ASSERT_EQ", "ASSERT_NE", "ASSERT_TRUE", "ASSERT_FALSE", "CODELAB_TEST_EXIT_CODE"];
5994
+ for (const sym of testSymbols) {
5995
+ const symRegex = new RegExp(`\\b${sym}\\b`);
5996
+ if (symRegex.test(source) && !hasTestHeader) {
5997
+ diagnostics.push({
5998
+ id: `cpp-missing-test-include-${sym}`,
5999
+ file: filename,
6000
+ line: 1,
6001
+ col: 1,
6002
+ severity: "warning",
6003
+ message: `Test macro '${sym}' used without #include <codelab/test.hpp>.`,
6004
+ source: "cpp-linter"
6005
+ });
6006
+ break;
6007
+ }
6008
+ }
6009
+ for (let l = 0; l < lines.length; l++) {
6010
+ const line = lines[l];
6011
+ const assignMatch = /\bif\s*\(([^;)]*[^=!<>]=[^=][^;)]*)\)/.exec(line);
6012
+ if (assignMatch) {
6013
+ diagnostics.push({
6014
+ id: `cpp-suspicious-assign-${l + 1}`,
6015
+ file: filename,
6016
+ line: l + 1,
6017
+ col: assignMatch.index + 1,
6018
+ severity: "warning",
6019
+ message: `Suspicious assignment '=' inside 'if' condition; did you mean '=='?`,
6020
+ source: "cpp-linter"
6021
+ });
6022
+ }
6023
+ }
6024
+ const structRegex = /(?:struct|class)\s+([A-Za-z0-9_]+)\s*\{[^}]*\}\s*(?!;)(?=[A-Za-z0-9_#\s\n])/g;
6025
+ let structMatch;
6026
+ while ((structMatch = structRegex.exec(source)) !== null) {
6027
+ const lineIndex = source.slice(0, structMatch.index + structMatch[0].length).split("\n").length;
6028
+ diagnostics.push({
6029
+ id: `cpp-missing-semicolon-${lineIndex}`,
6030
+ file: filename,
6031
+ line: lineIndex,
6032
+ col: 1,
6033
+ severity: "error",
6034
+ message: `Missing semicolon ';' after '${structMatch[1]}' class/struct definition.`,
6035
+ source: "cpp-linter"
6036
+ });
6037
+ }
6038
+ return diagnostics;
6039
+ }
6040
+ function applyClangStderrDiagnostics(stderrText, diagnosticsStore, monacoInstance, activeModel) {
6041
+ const diagnostics = [];
6042
+ if (!stderrText || typeof stderrText !== "string") return diagnostics;
6043
+ if (diagnosticsStore && typeof diagnosticsStore.clear === "function") {
6044
+ diagnosticsStore.clear("clang");
6045
+ }
6046
+ const clangRegex = /(?:(?:^|\n)(?:\/workspace\/)?([^\s:\n]+)):(\d+):(\d+):\s*(fatal error|error|warning|note):\s*([^\n]+)/g;
6047
+ let match;
6048
+ let idx = 0;
6049
+ while ((match = clangRegex.exec(stderrText)) !== null) {
6050
+ const rawFile = match[1].trim();
6051
+ const line = parseInt(match[2], 10) || 1;
6052
+ const col = parseInt(match[3], 10) || 1;
6053
+ const rawKind = match[4].toLowerCase();
6054
+ const message = match[5].trim();
6055
+ let severity = "error";
6056
+ if (rawKind === "warning") severity = "warning";
6057
+ else if (rawKind === "note") severity = "info";
6058
+ const item = {
6059
+ id: `clang-${rawFile}-${line}-${col}-${idx++}`,
6060
+ file: rawFile,
6061
+ line,
6062
+ col,
6063
+ severity,
6064
+ message: `[Clang] ${message}`,
6065
+ source: "clang"
6066
+ };
6067
+ diagnostics.push(item);
6068
+ if (diagnosticsStore && typeof diagnosticsStore.add === "function") {
6069
+ diagnosticsStore.add(item);
6070
+ }
6071
+ }
6072
+ if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === "function") {
6073
+ const markers = diagnostics.map((d) => ({
6074
+ startLineNumber: d.line,
6075
+ startColumn: d.col || 1,
6076
+ endLineNumber: d.line,
6077
+ endColumn: (d.col || 1) + 20,
6078
+ message: d.message,
6079
+ severity: d.severity === "error" ? monacoInstance.MarkerSeverity.Error : d.severity === "warning" ? monacoInstance.MarkerSeverity.Warning : monacoInstance.MarkerSeverity.Info
6080
+ }));
6081
+ monacoInstance.editor.setModelMarkers(activeModel, "clang", markers);
6082
+ }
6083
+ return diagnostics;
6084
+ }
6085
+ function installCppExtension(workbench, options = {}) {
5122
6086
  const toolchain = new CppToolchainManager(options);
5123
6087
  const compilerFn = registerCppCompilerOnRuntime(toolchain);
5124
6088
  if (!workbench) return toolchain;
5125
6089
  workbench.cppToolchain = toolchain;
5126
6090
  workbench.cppCompiler = compilerFn;
5127
6091
  workbench.cppOptions = toolchain.options;
6092
+ if (typeof window !== "undefined" && window.monaco) {
6093
+ registerMonacoCppLanguageService(window.monaco);
6094
+ }
5128
6095
  if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
5129
6096
  workbench.enabledLanguages = /* @__PURE__ */ new Set(["js", "cpp"]);
5130
6097
  } else {
@@ -5154,6 +6121,35 @@ function cppExtension(workbench, options = {}) {
5154
6121
  seedCppHeadersIntoVfs(workbench.vfs, toolchain.options.extraHeaders);
5155
6122
  }
5156
6123
  workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
6124
+ if (workbench._diagnosticsStore) {
6125
+ let lintTimer = null;
6126
+ const originalOnCodeChange = workbench.options?.onCodeChange;
6127
+ workbench._cppLintHandler = (file, code) => {
6128
+ if (!file || !/\.(?:cpp|cc|cxx|hpp|h)$/.test(file)) return;
6129
+ if (lintTimer) clearTimeout(lintTimer);
6130
+ lintTimer = setTimeout(() => {
6131
+ const diags = analyzeCppSource(code, file, workbench.vfs);
6132
+ workbench._diagnosticsStore.clear("cpp-linter");
6133
+ for (const d of diags) {
6134
+ workbench._diagnosticsStore.add(d);
6135
+ }
6136
+ if (typeof window !== "undefined" && window.monaco && workbench.editor) {
6137
+ const model = workbench.editor.getModel();
6138
+ if (model) {
6139
+ const markers = diags.map((d) => ({
6140
+ startLineNumber: d.line,
6141
+ startColumn: d.col || 1,
6142
+ endLineNumber: d.line,
6143
+ endColumn: (d.col || 1) + 20,
6144
+ message: d.message,
6145
+ severity: d.severity === "error" ? window.monaco.MarkerSeverity.Error : window.monaco.MarkerSeverity.Warning
6146
+ }));
6147
+ window.monaco.editor.setModelMarkers(model, "cpp-linter", markers);
6148
+ }
6149
+ }
6150
+ }, 180);
6151
+ };
6152
+ }
5157
6153
  if (options.preload) {
5158
6154
  toolchain.ensureLoaded().catch((err) => {
5159
6155
  if (typeof workbench._appendTerminalOutput === "function") {
@@ -5164,6 +6160,8 @@ function cppExtension(workbench, options = {}) {
5164
6160
  }
5165
6161
  if (options.activate && typeof workbench.setLanguage === "function") {
5166
6162
  workbench.setLanguage("cpp");
6163
+ } else if (typeof workbench._refreshToolbarAndTabs === "function") {
6164
+ workbench._refreshToolbarAndTabs();
5167
6165
  } else if (typeof workbench._renderShell === "function" && workbench.container) {
5168
6166
  workbench._renderShell();
5169
6167
  if (typeof workbench._bindEvents === "function") workbench._bindEvents();
@@ -5171,23 +6169,45 @@ function cppExtension(workbench, options = {}) {
5171
6169
  }
5172
6170
  return workbench;
5173
6171
  }
6172
+ function cppExtension(workbenchOrOptions, maybeOptions) {
6173
+ if (workbenchOrOptions === null) {
6174
+ const toolchain = new CppToolchainManager(maybeOptions || {});
6175
+ registerCppCompilerOnRuntime(toolchain);
6176
+ return toolchain;
6177
+ }
6178
+ if (workbenchOrOptions === void 0 || typeof workbenchOrOptions === "object" && !("enabledLanguages" in workbenchOrOptions) && !("container" in workbenchOrOptions) && !("_renderShell" in workbenchOrOptions)) {
6179
+ const opts = workbenchOrOptions || {};
6180
+ const plugin = (wb, runOpts = {}) => {
6181
+ return installCppExtension(wb, { ...opts, ...runOpts || {} });
6182
+ };
6183
+ plugin.extensionName = "cpp";
6184
+ plugin.languageId = "cpp";
6185
+ plugin.install = plugin;
6186
+ return plugin;
6187
+ }
6188
+ return installCppExtension(workbenchOrOptions, maybeOptions);
6189
+ }
5174
6190
  function createCppExtension(options = {}) {
5175
- const plugin = (workbench) => cppExtension(workbench, options);
5176
- plugin.extensionName = "cpp";
5177
- plugin.languageId = "cpp";
5178
- return plugin;
6191
+ return cppExtension(options);
5179
6192
  }
5180
6193
  var cpp_default = cppExtension;
5181
6194
  export {
5182
6195
  BUILTIN_CPP_HEADERS,
6196
+ CPP_COMPLETIONS_AND_HOVERS,
5183
6197
  CppToolchainManager,
5184
6198
  DEFAULT_CPP_CDN_BASE_URL,
6199
+ STANDARD_CPP20_HEADERS,
6200
+ analyzeCppSource,
6201
+ applyClangStderrDiagnostics,
6202
+ buildWasiPrintWasm,
5185
6203
  cppExtension,
5186
6204
  createCppExtension,
5187
6205
  createTarArchive,
5188
6206
  cpp_default as default,
5189
6207
  extractTarToVfs,
6208
+ installCppExtension,
5190
6209
  parseCppCompilerFlags,
5191
6210
  registerCppCompilerOnRuntime,
6211
+ registerMonacoCppLanguageService,
5192
6212
  seedCppHeadersIntoVfs
5193
6213
  };