From 27e2677a2aa4d7ab911535ea5a8b512a51df33d7 Mon Sep 17 00:00:00 2001 From: FunToHard Date: Sat, 7 Nov 2026 19:03:12 +0530 Subject: [PATCH] docs: add dedicated wiki documentation pages and apply audit fixes Resolves issue #2 by creating standalone wiki articles for Compiler & Toolchain Setup, Visual Studio Solution Support, Static CMake Integration, Debugging Guide, and Memory Layout Inspector. Updates wiki/Home.md navigation and README.md section links. Also applies repo audit improvements: resolves Rust Clippy warnings, aligns native crate version to 0.4.2, and enables production minification in packaging. Closes #2 --- Cargo.lock | 2 +- README.md | 26 ++++-- crates/c-cpp-pro-native/Cargo.toml | 2 +- crates/c-cpp-pro-native/src/cmake.rs | 84 +++++++---------- crates/c-cpp-pro-native/src/memory_layout.rs | 2 +- crates/c-cpp-pro-native/src/solution.rs | 2 +- crates/c-cpp-pro-native/src/time_trace.rs | 15 ++- esbuild.js | 3 +- package.json | 3 +- wiki/Compiler-Toolchain-Setup.md | 92 +++++++++++++++++++ wiki/Debugging-Guide.md | 97 ++++++++++++++++++++ wiki/Home.md | 18 ++-- wiki/Memory-Layout-Inspector.md | 86 +++++++++++++++++ wiki/Static-CMake-Integration.md | 74 +++++++++++++++ wiki/Visual-Studio-Solution-Support.md | 71 ++++++++++++++ 15 files changed, 499 insertions(+), 78 deletions(-) create mode 100644 wiki/Compiler-Toolchain-Setup.md create mode 100644 wiki/Debugging-Guide.md create mode 100644 wiki/Memory-Layout-Inspector.md create mode 100644 wiki/Static-CMake-Integration.md create mode 100644 wiki/Visual-Studio-Solution-Support.md diff --git a/Cargo.lock b/Cargo.lock index 7e45f06..36814dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,7 +19,7 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "c-cpp-pro-native" -version = "0.4.0" +version = "0.4.2" dependencies = [ "napi", "napi-build", diff --git a/README.md b/README.md index 179dbc2..6e70bdb 100644 --- a/README.md +++ b/README.md @@ -47,30 +47,40 @@ C/C++ Pro combines the blazing index and AST completion speed of LLVM's **`clang - **Boost C++ Libraries** (`C:\local\boost_*`, `/usr/include/boost`) - **SDL2 / SDL3** - **vcpkg** and **Node-API** (`node-addon-api`, `nan`) includes +- Detailed documentation: [Compiler & Toolchain Setup Wiki](https://github.com/CinderLuna/c-cpp-pro/wiki/Compiler-Toolchain-Setup). ### 3. Visual Studio Solution & Project Integration - **Solution Formats**: First-class support for traditional `.sln` and the modern XML-based `.slnx` solution formats. - **Project Parsing**: Extracts include directories, preprocessor definitions, language standards, and forced includes from `.vcxproj` files across all configurations (Debug/Release, x64/x86/ARM64). - **Compilation Database Generation**: Generates a unified `compile_commands.json` covering all C++ source files in the active solution. - **MSBuild Task Provider**: Generates build, rebuild, clean, and per-project tasks automatically accessible via VS Code's Task runner. +- Detailed documentation: [Visual Studio Solution Support Wiki](https://github.com/CinderLuna/c-cpp-pro/wiki/Visual-Studio-Solution-Support). -### 4. Integrated DAP Debugging & Run Controller +### 4. Static CMake Intelligence +- **In-Memory CMake Parsing**: Tokenizes and parses `CMakeLists.txt` files and `.cmake` modules statically without invoking CMake CLI binaries. +- **Transitive Include Resolution**: Models `target_include_directories`, `target_compile_definitions`, and `target_link_libraries` transitive property propagation. +- **Compilation Database Generation**: Synthesizes `compile_commands.json` on-demand with isolated target private includes and per-file C/C++ language standards. +- Detailed documentation: [Static CMake Integration Wiki](https://github.com/CinderLuna/c-cpp-pro/wiki/Static-CMake-Integration). + +### 5. Integrated DAP Debugging & Run Controller - **Zero-Setup Debugging**: Seamlessly hooks into `lldb-dap`, GDB (`--interpreter=dap`), or MSVC for native C/C++ debugging. - **Automatic Launch Generation**: Pre-configured launch configurations with dynamic workspace variable resolution (`${fileBasenameNoExtension}`, `${workspaceFolder}`). - **Interactive Process Picker**: Select running processes to attach with cross-platform PID and name resolution. - **Evaluatable Expression Provider**: Evaluate nested member accesses (`a->b.c`), indexed arrays (`arr[i]`), and pointers when hovering during debug breaks. - **Run & Debug Editor Title Actions**: One-click play and debug buttons in the editor title bar with automated Visual Studio Developer Shell (`vcvarsall`) environment injection on Windows. +- Detailed documentation: [Debugging Guide Wiki](https://github.com/CinderLuna/c-cpp-pro/wiki/Debugging-Guide). -### 5. Type & Memory Layout Inspector +### 6. Type & Memory Layout Inspector - Inspect struct and class memory layouts directly inside the editor (`c-cpp-pro.inspectMemoryLayout`). - Visualize field byte offsets, member sizes, struct alignment, and wasted memory from padding holes. - Visual indicators for 64-byte CPU cache line boundaries to optimize data structures for cache locality. +- Detailed documentation: [Memory Layout Inspector Wiki](https://github.com/CinderLuna/c-cpp-pro/wiki/Memory-Layout-Inspector). -### 6. Include Tree & Build Bottleneck Visualizer +### 7. Include Tree & Build Bottleneck Visualizer - **Header Dependency Hierarchy**: Analyze `#include` trees, detect circular inclusion cycles, and receive optimization tips for heavy headers (`c-cpp-pro.analyzeIncludes`). - **Clang `-ftime-trace` Profiling**: Inspect Chrome tracing JSON files to pinpoint slow template instantiations and expensive header parse times (`c-cpp-pro.visualizeTimeTrace`). -### 7. Modern C++ Test Explorer +### 8. Modern C++ Test Explorer - Native VS Code Test Explorer integration for modern C++ testing frameworks. - Automatically discovers tests, suites, and scenarios for: - **GoogleTest** (`TEST`, `TEST_F`, `TEST_P`) @@ -78,18 +88,18 @@ C/C++ Pro combines the blazing index and AST completion speed of LLVM's **`clang - **doctest** (`TEST_CASE`) - **Boost.Test** (`BOOST_AUTO_TEST_CASE`) -### 8. Macro Expansion & Compile-Time Evaluation +### 9. Macro Expansion & Compile-Time Evaluation - **Step-by-Step Macro Expansion**: Preview complex object-like and function-like macro expansions directly at cursor position (`c-cpp-pro.expandMacro`). - **`constexpr` Evaluation**: Preview compile-time evaluations and constant folding results (`c-cpp-pro.evaluateConstexpr`). -### 9. Inline Disassembly & Compiler Explorer +### 10. Inline Disassembly & Compiler Explorer - Open inline assembly output alongside your C++ code (`c-cpp-pro.viewDisassembly`). - Filter compiler directives, labels, and comments with customizable optimization flags (`-O0`, `-O1`, `-O2`, `-O3`, `-Os`, `-Oz`). -### 10. Semantic Symbol Hierarchy Graphs +### 11. Semantic Symbol Hierarchy Graphs - Generate Mermaid diagrams visualizing class inheritance and symbol relationships (`c-cpp-pro.showTypeHierarchy`). -### 11. Configuration Editor & Multi-Target Profiles +### 12. Configuration Editor & Multi-Target Profiles - Modern graphical Webview editor (`c-cpp-pro.openSettings`) to configure include paths, preprocessor defines, compiler paths, and C/C++ language standards. - Supports `.vscode/c_cpp_properties.json` and Linux/RTOS Kconfig (`.config`) files. - Visual Studio Developer Environment switcher (`c-cpp-pro.setVsDeveloperEnvironment`) to quickly initialize compiler environments. diff --git a/crates/c-cpp-pro-native/Cargo.toml b/crates/c-cpp-pro-native/Cargo.toml index b911670..1dd19ac 100644 --- a/crates/c-cpp-pro-native/Cargo.toml +++ b/crates/c-cpp-pro-native/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "c-cpp-pro-native" -version = "0.4.0" +version = "0.4.2" edition = "2021" [lib] diff --git a/crates/c-cpp-pro-native/src/cmake.rs b/crates/c-cpp-pro-native/src/cmake.rs index b0e79e0..ed14e01 100644 --- a/crates/c-cpp-pro-native/src/cmake.rs +++ b/crates/c-cpp-pro-native/src/cmake.rs @@ -290,8 +290,8 @@ pub fn parse_cmake_file_internal( for cmd in commands { match cmd.name.as_str() { - "set" => { - if cmd.args.len() >= 2 { + "set" + if cmd.args.len() >= 2 => { let var_name = cmd.args[0].clone(); let val_joined = cmd.args[1..].join(" "); let resolved_val = resolve_variables(&val_joined, &variables); @@ -309,37 +309,34 @@ pub fn parse_cmake_file_internal( } } } - } "include_directories" => { for arg in &cmd.args { add_include(arg, &variables, ¤t_dir, None, &mut result); } } - "target_include_directories" => { - if cmd.args.len() >= 2 { + "target_include_directories" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for arg in &cmd.args[1..] { add_include(arg, &variables, ¤t_dir, Some(target_idx), &mut result); } } - } "add_definitions" => { for arg in &cmd.args { add_define(arg, &variables, None, &mut result); } } - "target_compile_definitions" => { - if cmd.args.len() >= 2 { + "target_compile_definitions" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for arg in &cmd.args[1..] { add_define(arg, &variables, Some(target_idx), &mut result); } } - } - "add_executable" => { - if !cmd.args.is_empty() { + "add_executable" + if !cmd.args.is_empty() => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "executable", &mut result.targets); result.targets[target_idx].target_type = "executable".to_string(); @@ -363,9 +360,8 @@ pub fn parse_cmake_file_internal( } } } - } - "add_library" => { - if !cmd.args.is_empty() { + "add_library" + if !cmd.args.is_empty() => { let target_name = &cmd.args[0]; let mut target_type = "library".to_string(); let mut src_start = 1; @@ -415,9 +411,8 @@ pub fn parse_cmake_file_internal( } } } - } - "target_sources" => { - if cmd.args.len() >= 2 { + "target_sources" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for s in &cmd.args[1..] { @@ -430,9 +425,8 @@ pub fn parse_cmake_file_internal( result.targets[target_idx].source_files.push(full); } } - } - "target_link_libraries" => { - if cmd.args.len() >= 2 { + "target_link_libraries" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for arg in &cmd.args[1..] { @@ -459,9 +453,8 @@ pub fn parse_cmake_file_internal( } } } - } - "add_subdirectory" => { - if !cmd.args.is_empty() { + "add_subdirectory" + if !cmd.args.is_empty() => { let sub_name = resolve_variables(&cmd.args[0], &variables); result.subdirectories.push(sub_name.clone()); @@ -527,9 +520,8 @@ pub fn parse_cmake_file_internal( } } } - } - "include" => { - if !cmd.args.is_empty() { + "include" + if !cmd.args.is_empty() => { let file_arg = resolve_variables(&cmd.args[0], &variables); let candidates = vec![ resolve_path(¤t_dir, &file_arg), @@ -565,7 +557,6 @@ pub fn parse_cmake_file_internal( } } } - } _ => {} } } @@ -580,7 +571,7 @@ pub fn parse_cmake_file_internal( } pub fn resolve_linked_target_properties( - targets: &mut Vec, + targets: &mut [CMakeTargetInfoNative], global_includes: &mut Vec, global_defs: &mut Vec, ) { @@ -596,7 +587,7 @@ pub fn resolve_linked_target_properties( None => continue, }; for dep_name in deps { - if let Some(dep_idx) = targets.iter().position(|t| &t.name == &dep_name) { + if let Some(dep_idx) = targets.iter().position(|t| t.name == dep_name) { let dep_incs = targets[dep_idx].include_directories.clone(); let dep_defs = targets[dep_idx].compile_definitions.clone(); @@ -748,8 +739,8 @@ pub fn parse_cmake_content_native( for cmd in commands { match cmd.name.as_str() { - "set" => { - if cmd.args.len() >= 2 { + "set" + if cmd.args.len() >= 2 => { let var_name = cmd.args[0].clone(); let val_joined = cmd.args[1..].join(" "); let resolved_val = resolve_variables(&val_joined, &variables); @@ -767,37 +758,34 @@ pub fn parse_cmake_content_native( } } } - } "include_directories" => { for arg in &cmd.args { add_include(arg, &variables, ¤t_dir, None, &mut result); } } - "target_include_directories" => { - if cmd.args.len() >= 2 { + "target_include_directories" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for arg in &cmd.args[1..] { add_include(arg, &variables, ¤t_dir, Some(target_idx), &mut result); } } - } "add_definitions" => { for arg in &cmd.args { add_define(arg, &variables, None, &mut result); } } - "target_compile_definitions" => { - if cmd.args.len() >= 2 { + "target_compile_definitions" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for arg in &cmd.args[1..] { add_define(arg, &variables, Some(target_idx), &mut result); } } - } - "add_executable" => { - if !cmd.args.is_empty() { + "add_executable" + if !cmd.args.is_empty() => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "executable", &mut result.targets); result.targets[target_idx].target_type = "executable".to_string(); @@ -821,9 +809,8 @@ pub fn parse_cmake_content_native( } } } - } - "add_library" => { - if !cmd.args.is_empty() { + "add_library" + if !cmd.args.is_empty() => { let target_name = &cmd.args[0]; let mut target_type = "library".to_string(); let mut src_start = 1; @@ -873,9 +860,8 @@ pub fn parse_cmake_content_native( } } } - } - "target_sources" => { - if cmd.args.len() >= 2 { + "target_sources" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for s in &cmd.args[1..] { @@ -888,9 +874,8 @@ pub fn parse_cmake_content_native( result.targets[target_idx].source_files.push(full); } } - } - "target_link_libraries" => { - if cmd.args.len() >= 2 { + "target_link_libraries" + if cmd.args.len() >= 2 => { let target_name = &cmd.args[0]; let target_idx = get_or_create_target(target_name, "custom", &mut result.targets); for arg in &cmd.args[1..] { @@ -917,7 +902,6 @@ pub fn parse_cmake_content_native( } } } - } _ => {} } } diff --git a/crates/c-cpp-pro-native/src/memory_layout.rs b/crates/c-cpp-pro-native/src/memory_layout.rs index 29e7618..fdec065 100644 --- a/crates/c-cpp-pro-native/src/memory_layout.rs +++ b/crates/c-cpp-pro-native/src/memory_layout.rs @@ -173,7 +173,7 @@ pub fn calculate_struct_layout_native( let is_packed = opts.is_packed.unwrap_or(false); let pack_max = opts .max_pack_alignment - .unwrap_or_else(|| if is_packed { 1 } else { 8 }); + .unwrap_or(if is_packed { 1 } else { 8 }); let data_model = opts .data_model .as_deref() diff --git a/crates/c-cpp-pro-native/src/solution.rs b/crates/c-cpp-pro-native/src/solution.rs index 326c4b6..5eb0039 100644 --- a/crates/c-cpp-pro-native/src/solution.rs +++ b/crates/c-cpp-pro-native/src/solution.rs @@ -503,7 +503,7 @@ pub fn parse_vcxproj_content_native( continue; } if trimmed.starts_with('\"') && trimmed.ends_with('\"') && trimmed.len() >= 2 { - trimmed = &trimmed[1..trimmed.len() - 1].trim(); + trimmed = trimmed[1..trimmed.len() - 1].trim(); } let expanded = trimmed .replace("$(ProjectDir)", &(normalize_slash(&project_dir) + "/")) diff --git a/crates/c-cpp-pro-native/src/time_trace.rs b/crates/c-cpp-pro-native/src/time_trace.rs index 5661801..175160c 100644 --- a/crates/c-cpp-pro-native/src/time_trace.rs +++ b/crates/c-cpp-pro-native/src/time_trace.rs @@ -73,11 +73,10 @@ pub fn parse_trace_events(json_content: &str) -> Result total_duration_us { + if (name == "Total ExecuteCompiler" || name == "ExecuteCompiler") + && dur > total_duration_us { total_duration_us = dur; } - } if name == "Source" { if let Some(args) = &event.args { @@ -200,7 +199,7 @@ pub fn parse_trace_events(json_content: &str) -> Result = template_map @@ -210,7 +209,7 @@ pub fn parse_trace_events(json_content: &str) -> Result = function_map @@ -220,7 +219,7 @@ pub fn parse_trace_events(json_content: &str) -> Result Result napi::Result { - parse_trace_events(&content).map_err(|e| napi::Error::from_reason(e)) + parse_trace_events(&content).map_err(napi::Error::from_reason) } #[napi] @@ -245,7 +244,7 @@ pub async fn parse_ftime_trace_file(file_path: String) -> napi::Result fs.rmSync(d, { recursive: true, force: true })); fs.readdirSync('.').filter(f => f.endsWith('.vsix') || f.endsWith('.obj') || f.endsWith('.pdb') || f.endsWith('.ilk')).forEach(f => fs.rmSync(f, { force: true }));\"", diff --git a/wiki/Compiler-Toolchain-Setup.md b/wiki/Compiler-Toolchain-Setup.md new file mode 100644 index 0000000..d391056 --- /dev/null +++ b/wiki/Compiler-Toolchain-Setup.md @@ -0,0 +1,92 @@ +# Compiler & Toolchain Setup + +C/C++ Pro features a zero-configuration compiler and SDK discovery engine. It detects installed toolchains, locates system include directories, probes third-party libraries, and synthesizes IntelliSense flags without requiring manual path configuration. + +--- + +## 1. Supported Compilers & Discovery + +C/C++ Pro automatically discovers native and cross-compilation toolchains on the host operating system: + +| Compiler Family | Executables | Platform | Detection Mechanism | +| :--- | :--- | :--- | :--- | +| **MSVC** | `cl.exe` | Windows | `vswhere.exe`, Visual Studio 2017/2019/2022 installations, Build Tools | +| **LLVM Clang** | `clang++`, `clang`, `clang-cl` | Windows, Linux, macOS | `PATH`, standard LLVM directories (`C:\Program Files\LLVM\bin`, `/usr/bin`, Homebrew) | +| **GCC / MinGW** | `g++`, `gcc` | Windows, Linux, macOS | `PATH`, MinGW-w64, MSYS2 (`C:\msys64\mingw64\bin`), Linux system paths | +| **WSL Toolchains** | `wsl.exe g++`, `wsl.exe clang++` | Windows (WSL) | Discovered Linux distributions via WSL API | +| **Apple Clang** | `clang++`, `clang` | macOS | Xcode Command Line Tools (`/Library/Developer/CommandLineTools`) | + +To manually trigger a scan for installed compilers: +1. Open the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`). +2. Run **`C/C++ Pro: Scan for Installed Compilers`** (`c-cpp-pro.detectCompilers`). +3. Results are displayed in the Output panel under the **C/C++ Pro** channel. + +--- + +## 2. Compilation Flags Synthesis + +For projects without formal build configurations (single-file scripts, unstructured directories, or scratchpads), C/C++ Pro synthesizes IntelliSense flags on the fly. + +### Generating `compile_flags.txt` +1. Open the Command Palette. +2. Run **`C/C++ Pro: Generate compile_flags.txt`** (`c-cpp-pro.generateCompileFlags`). +3. C/C++ Pro writes a standard `compile_flags.txt` file into your workspace root configured with: + - Appropriate language standard (`-std=c++20` or `-std=c17` based on your settings). + - Resolved system include directories from the active compiler. + - Detected external SDK include paths. + +### Precedence Hierarchy +IntelliSense compilation flags are resolved in the following priority: +1. `compile_commands.json` (CMake, Visual Studio Solution, Bear, or Ninja). +2. `.clangd` configuration files (Workspace root or user home directory). +3. `compile_flags.txt` (Workspace root). +4. Auto-synthesized flags generated dynamically by C/C++ Pro. + +--- + +## 3. External SDK & Ecosystem Discovery + +C/C++ Pro automatically detects common system and graphics SDKs. To avoid flag pollution, C/C++ Pro verifies workspace source files via `ExternalSdkDetector.isSdkUsedInWorkspace` before injecting SDK include directories. + +| SDK | Environment Variables | Default Filesystem Search Paths | +| :--- | :--- | :--- | +| **Vulkan SDK** | `VULKAN_SDK` | `C:\VulkanSDK\*`, `/usr/include/vulkan`, `/usr/local/include/vulkan` | +| **raylib** | `RAYLIB_DIR`, `RAYLIB_PATH` | `C:\raylib`, `/usr/local/include/raylib`, Homebrew paths | +| **CUDA Toolkit** | `CUDA_PATH` | `C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\*`, `/usr/local/cuda` | +| **Boost C++** | `BOOST_ROOT`, `BOOST_DIR` | `C:\local\boost_*`, `/usr/include/boost`, Homebrew paths | +| **SDL2 / SDL3** | `SDL2_DIR`, `SDL3_DIR` | `C:\SDL*`, `/usr/include/SDL2`, `/usr/local/include/SDL2` | +| **Node-API** | — | Automatic inspection of `package.json` for `node-addon-api` or `nan` | +| **vcpkg** | `VCPKG_ROOT` | Automatic detection of active vcpkg installed directories | + +### Customizing SDK Probing +SDK auto-detection can be toggled in your VS Code settings: +```json +{ + "c-cpp-pro.discovery.detectExternalSdks": true +} +``` + +--- + +## 4. Visual Studio Developer Environment Injection (Windows) + +When compiling or debugging with MSVC on Windows, environment variables (`INCLUDE`, `LIB`, `PATH`) must be initialized for `cl.exe` to find Windows SDK and CRT headers. + +C/C++ Pro manages this environment automatically: +- **Set Environment**: Run **`C/C++ Pro: Set Visual Studio Developer Environment`** (`c-cpp-pro.setVsDeveloperEnvironment`) to choose an installed Visual Studio instance (x64, x86, or ARM64). +- **Environment Persistence**: Set `"c-cpp-pro.persistVsDeveloperEnvironment": true` to preserve the environment across editor sessions. +- **Terminal Overflow Protection**: C/C++ Pro de-duplicates PATH entries during injection to prevent Windows 32,767 character terminal buffer overflows. +- **Clear Environment**: Run **`C/C++ Pro: Clear Visual Studio Developer Environment`** (`c-cpp-pro.clearVsDeveloperEnvironment`) to reset back to system defaults. + +--- + +## 5. Configuration Settings Reference + +| Setting | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `c-cpp-pro.clangdPath` | `string` | `""` | Path to `clangd` executable. If empty, searches `PATH` and auto-installed binary. | +| `c-cpp-pro.clangdArgs` | `array` | `[]` | Extra arguments passed to the `clangd` background process. | +| `c-cpp-pro.cppStandard` | `string` | `"c++20"` | Default C++ standard for flag synthesis (`c++98` through `c++26`). | +| `c-cpp-pro.cStandard` | `string` | `"c17"` | Default C standard for flag synthesis (`c89` through `c23`). | +| `c-cpp-pro.default.forcedInclude` | `array` | `[]` | Headers to force-include before compilation (`/FI` on MSVC, `-include` on GCC/Clang). | +| `c-cpp-pro.discovery.detectExternalSdks` | `boolean` | `true` | Auto-detect common external SDKs for IntelliSense fallback flags. | diff --git a/wiki/Debugging-Guide.md b/wiki/Debugging-Guide.md new file mode 100644 index 0000000..d46e16a --- /dev/null +++ b/wiki/Debugging-Guide.md @@ -0,0 +1,97 @@ +# Debugging Guide + +C/C++ Pro includes a native Debug Adapter Protocol (DAP) debugging engine (`c-cpp-pro-debug`). It delivers zero-setup, open-standard C/C++ debugging across **Windows**, **Linux**, and **macOS** using modern backends without proprietary extensions or vendor lock-in. + +--- + +## 1. Supported Debugger Backends + +C/C++ Pro automatically detects, configures, and connects to installed debugging backends: + +| Backend | Platform | Protocol | Best Suited For | +| :--- | :--- | :--- | :--- | +| **`lldb-dap`** | Windows, Linux, macOS | Native DAP | LLVM Clang, Apple Clang, and modern cross-platform projects. | +| **GDB** | Linux, Windows (MinGW/WSL) | Native DAP (`--interpreter=dap`) | GCC, MinGW-w64, Linux kernel, and embedded projects. | +| **MSVC Native** | Windows | Win32 Debug API | Microsoft Visual C++ (`cl.exe`) binaries and PDB debugging. | + +--- + +## 2. Quick Run & Debug (Title Bar Actions) + +C/C++ Pro adds one-click Run and Debug actions to the editor title bar for active C and C++ source files: + +- **Run C/C++ File** (`c-cpp-pro.runFile`): Compiles the active file with detected compiler flags and launches the output in the integrated terminal. On Windows, automatically initializes the Visual Studio Developer Shell (`vcvarsall`) if MSVC is used. +- **Debug C/C++ File** (`c-cpp-pro.debugFile`): Builds the active file with debug symbols (`-g` or `/Zi`), scaffolds a launch configuration if missing, and immediately starts a debug session. + +--- + +## 3. Launch Configuration Reference + +To configure debugging, create or edit `.vscode/launch.json`. Set the `type` attribute to `"c-cpp-pro-debug"`. + +### Example `launch.json` +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "C/C++ Pro: Launch Active File", + "type": "c-cpp-pro-debug", + "request": "launch", + "program": "${workspaceFolder}/build/${fileBasenameNoExtension}", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + "debuggerType": "auto" + } + ] +} +``` + +### Configuration Attributes + +| Attribute | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `program` | `string` | *(Required)* | Full path to the compiled executable binary. Supports variables like `${workspaceFolder}` and `${fileBasenameNoExtension}`. | +| `args` | `array` | `[]` | Command-line arguments passed to the target process. | +| `cwd` | `string` | `${workspaceFolder}` | Working directory for the launched process. | +| `stopAtEntry` | `boolean` | `false` | Automatically break at program entry point (`main`). | +| `environment` | `array` | `[]` | Array of `{ "name": "KEY", "value": "VAL" }` objects to inject into the process environment. | +| `debuggerType` | `string` | `"auto"` | Debug backend selection: `"auto"`, `"lldb-dap"`, or `"gdb"`. | +| `debuggerPath` | `string` | `""` | Explicit filesystem path to custom debugger executable. Auto-detected if omitted. | + +--- + +## 4. Attaching to Running Processes + +C/C++ Pro provides an interactive process picker to attach the debugger to any running process: + +1. Open the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`). +2. Run **`C/C++ Pro: Pick Process to Attach`** (`c-cpp-pro.pickProcess`). +3. Search and select the target process by executable name or Process ID (PID). +4. C/C++ Pro attaches the debugger and breaks execution for inspection. + +--- + +## 5. Evaluatable Expression Hover Provider + +During active debug sessions, C/C++ Pro enriches cursor hovers using its AST Evaluatable Expression provider: +- **Member Access**: Automatically expands nested member expressions (`player->transform.position.x`). +- **Array Subscripts**: Selects full indexed lookups (`buffer[index]`). +- **Pointer Dereferences**: Evaluates dereferenced values (`*ptr`, `&variable`). + +--- + +## 6. Debugger Troubleshooting + +### `lldb-dap` Not Found +- Ensure LLVM is installed (`winget install LLVM.LLVM` on Windows, `brew install llvm` on macOS, or `apt install lldb` on Ubuntu/Debian). +- Set explicit path in settings: + ```json + { + "c-cpp-pro.debuggerPath": "C:\\Program Files\\LLVM\\bin\\lldb-dap.exe" + } + ``` + +### GDB DAP Mode +- Requires GDB version 14.1 or newer for native DAP support (`gdb --interpreter=dap`). diff --git a/wiki/Home.md b/wiki/Home.md index 9a2fcf8..44f4e34 100644 --- a/wiki/Home.md +++ b/wiki/Home.md @@ -8,11 +8,11 @@ Welcome to the **C/C++ Pro** documentation wiki. This wiki provides user manuals - **[Project Creation Guide](Project-Creation)**: Turnkey project scaffolding wizard for Windows, Linux, and macOS. - **[Command Palette Reference](Command-Palette)**: Complete catalog of all 43 commands with descriptions, shortcuts, and behaviors. -- **[Compiler & Toolchain Setup](https://github.com/CinderLuna/c-cpp-pro#2-zero-configuration-compiler--sdk-discovery)**: Automatic discovery of MSVC, Clang, GCC, and WSL compilers. -- **[Visual Studio Solution Support](https://github.com/CinderLuna/c-cpp-pro#3-visual-studio-solution--project-integration)**: Working with `.sln`, `.slnx`, and `.vcxproj` files without launching Visual Studio. -- **[Static CMake Integration](https://github.com/CinderLuna/c-cpp-pro#cmake-intelligence)**: Parsing `CMakeLists.txt` statically to build `compile_commands.json`. -- **[Debugging Guide](https://github.com/CinderLuna/c-cpp-pro#4-integrated-dap-debugging--run-controller)**: Using `lldb-dap`, GDB, and MSVC native debuggers. -- **[Memory Layout Inspector](https://github.com/CinderLuna/c-cpp-pro#5-memory-layout-inspector--build-profiling)**: Visualizing struct alignment, padding, and CPU cache lines. +- **[Compiler & Toolchain Setup](Compiler-Toolchain-Setup)**: Automatic discovery of MSVC, Clang, GCC, and WSL compilers. +- **[Visual Studio Solution Support](Visual-Studio-Solution-Support)**: Working with `.sln`, `.slnx`, and `.vcxproj` files without launching Visual Studio. +- **[Static CMake Integration](Static-CMake-Integration)**: Parsing `CMakeLists.txt` statically to build `compile_commands.json`. +- **[Debugging Guide](Debugging-Guide)**: Using `lldb-dap`, GDB, and MSVC native debuggers. +- **[Memory Layout Inspector](Memory-Layout-Inspector)**: Visualizing struct alignment, padding, and CPU cache lines. --- @@ -20,7 +20,13 @@ Welcome to the **C/C++ Pro** documentation wiki. This wiki provides user manuals | Topic | Link | | :--- | :--- | -| **All Commands** | [Command Palette Reference](Command-Palette) | +| **Project Creation** | [Project Creation Guide](Project-Creation) | +| **Command Palette** | [Command Palette Reference](Command-Palette) | +| **Compiler & Toolchains** | [Compiler & Toolchain Setup](Compiler-Toolchain-Setup) | +| **Visual Studio Solutions** | [Visual Studio Solution Support](Visual-Studio-Solution-Support) | +| **Static CMake** | [Static CMake Integration](Static-CMake-Integration) | +| **Debugging** | [Debugging Guide](Debugging-Guide) | +| **Memory Layout** | [Memory Layout Inspector](Memory-Layout-Inspector) | | **Issue Tracker** | [GitHub Issues](https://github.com/CinderLuna/c-cpp-pro/issues) | | **Repository** | [GitHub Repository](https://github.com/CinderLuna/c-cpp-pro) | | **VS Code Marketplace** | [Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=FunToHard.c-cpp-pro) | diff --git a/wiki/Memory-Layout-Inspector.md b/wiki/Memory-Layout-Inspector.md new file mode 100644 index 0000000..1fea5a6 --- /dev/null +++ b/wiki/Memory-Layout-Inspector.md @@ -0,0 +1,86 @@ +# Memory Layout Inspector + +C/C++ Pro includes an interactive struct and class memory layout inspector. It visualizes byte offsets, member field alignments, padding holes, and CPU cache line boundaries directly inside Visual Studio Code. + +--- + +## 1. Why Inspect Memory Layout? + +In performance-critical C and C++ software (game engines, embedded systems, high-frequency trading, and operating systems), memory layout directly affects cache locality and memory bandwidth: +- **Padding Holes**: Compilers insert alignment padding between struct members, creating wasted memory. +- **Cache Locality**: Accessing members that span across 64-byte CPU cache lines causes multiple memory fetches. +- **False Sharing**: Multi-threaded access to variables residing on the same cache line leads to CPU core invalidation stalls. + +C/C++ Pro calculates layout metrics accurately in real-time according to your target ABI. + +--- + +## 2. Using the Inspector + +### Launching the Inspector +There are two ways to inspect a struct or class layout: +1. **From Cursor Position**: Place your editor cursor inside any `struct`, `class`, or `union` declaration and run **`C/C++ Pro: Inspect Type & Memory Layout (Struct Padding / Alignment)`** (`c-cpp-pro.inspectMemoryLayout`). +2. **From Definition Hover**: Hover over a struct or class name. The rich hover card includes a direct link: **`Inspect Memory Layout`**. Click it to open the layout panel. +3. **From Usage Sites**: Hovering over a struct type or variable in a non-definition file automatically resolves the underlying declaration symbol and parameterizes the inspection link. + +--- + +## 3. Metrics & Visualizations + +The Memory Layout panel renders an interactive visual breakdown: + +| Metric | Description | Optimization Target | +| :--- | :--- | :--- | +| **Total Size** | Total size of the struct in bytes. | Minimize overall footprint to fit more instances in CPU cache. | +| **Alignment** | Struct alignment requirement (e.g. 4, 8, or 16 bytes). | Dictated by the largest scalar member. | +| **Padding (Wasted)** | Total bytes lost to internal alignment padding and tail padding. | Aim for 0 bytes or minimum possible wasted space. | +| **Field Offsets** | Byte offset (`0x00`, `0x08`, etc.) and size of every member field. | Inspect exact member placement in memory. | +| **Cache Line Boundaries** | Indicators marking each 64-byte CPU cache line boundary. | Ensure frequently accessed hot fields fit inside the first cache line (`0..63` bytes). | + +--- + +## 4. Platform Data Models & Packed Structs + +C/C++ Pro calculates layout rules tailored to standard ABIs: + +### Data Models +- **LLP64** (Windows x64): + - `int`: 4 bytes, `long`: 4 bytes, `long long`: 8 bytes, pointers: 8 bytes. +- **LP64** (Linux & macOS x64): + - `int`: 4 bytes, `long`: 8 bytes, `long long`: 8 bytes, pointers: 8 bytes. +- **ILP32** (32-bit platforms, x86, ARM32): + - `int`: 4 bytes, `long`: 4 bytes, pointers: 4 bytes. + +### Packed Structs +The inspector accurately handles packed struct directives: +- MSVC: `#pragma pack(push, 1)` / `#pragma pack(pop)` +- GCC / Clang: `__attribute__((packed))` + +When packed, alignment requirements are relaxed to 1 byte and padding holes are eliminated. + +--- + +## 5. Struct Reordering Example + +Consider an unoptimized struct with interleaved field sizes: + +```cpp +struct Unoptimized { + bool active; // 1 byte (+ 7 bytes padding) + double value; // 8 bytes (offset 8) + int count; // 4 bytes (+ 4 bytes padding) +}; // Total: 24 bytes (11 bytes wasted padding) +``` + +By reordering members from largest to smallest alignment requirements: + +```cpp +struct Optimized { + double value; // 8 bytes (offset 0) + int count; // 4 bytes (offset 8) + bool active; // 1 byte (offset 12) + // (+ 3 bytes tail padding) +}; // Total: 16 bytes (33% memory reduction) +``` + +C/C++ Pro immediately visualizes these padding differences, enabling rapid memory footprint optimization. diff --git a/wiki/Static-CMake-Integration.md b/wiki/Static-CMake-Integration.md new file mode 100644 index 0000000..526030b --- /dev/null +++ b/wiki/Static-CMake-Integration.md @@ -0,0 +1,74 @@ +# Static CMake Integration + +C/C++ Pro features a static CMake intelligence engine that parses `CMakeLists.txt` files and `.cmake` modules directly in memory without requiring the `cmake` binary, configuration directories, or build trees. + +--- + +## 1. Why Static CMake Parsing? + +Traditional CMake extensions require configuring and generating a complete build directory (`build/` or `out/`) before IntelliSense becomes functional. This requires installed dependencies, functional toolchain files, and significant disk and CPU overhead. + +C/C++ Pro's static CMake engine provides: +- **Instant IntelliSense**: Semantic autocomplete and error checking work the moment you open a CMake workspace. +- **No External Binaries**: Operates completely independently of the `cmake` executable or ninja/make generators. +- **Zero Disk Bloat**: Extracts compile flags, definitions, and include directories without generating build trees. +- **Native Performance**: Powered by a high-throughput Rust parser (`crates/c-cpp-pro-native/src/cmake.rs`) that processes thousands of lines in milliseconds. + +--- + +## 2. Supported CMake Commands & Semantics + +The static parser recognizes and models the core CMake target model: + +| Command | Modeling & Extraction | +| :--- | :--- | +| `project(...)` | Workspace naming and language configuration (`C`, `CXX`). | +| `set(VAR ...)` | Variable assignment and dynamic variable expansion (`${VAR}`). | +| `include_directories(...)` | Workspace-global include directories. | +| `add_definitions(...)` | Workspace-global preprocessor defines (`-DFOO`). | +| `add_executable(target ...)` | Executable target definition and source file association. | +| `add_library(target ...)` | Static, Shared, Module, and Interface library definitions. | +| `target_include_directories(...)` | Per-target include paths with `PUBLIC`, `PRIVATE`, or `INTERFACE` visibility. | +| `target_compile_definitions(...)` | Per-target preprocessor defines with visibility scoping. | +| `target_sources(...)` | Associating source files with existing targets. | +| `target_link_libraries(...)` | Dependency modeling and transitive include/define propagation. | +| `add_subdirectory(...)` | Recursive traversal and parsing of sub-projects. | +| `include(...)` | Inlining and parsing external `.cmake` modules. | + +### Generator Expression Handling +C/C++ Pro automatically evaluates build-time generator expressions: +- **Unwraps**: `$` is unwrapped and included in IntelliSense paths. +- **Discards**: `$` is ignored to reflect active in-source development paths. + +--- + +## 3. Automatic Compilation Database Synthesis + +C/C++ Pro can automatically synthesize a complete `compile_commands.json` compilation database directly from your CMake targets: + +1. Open the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`). +2. Run **`C/C++ Pro: Generate compile_commands.json from CMakeLists.txt`** (`c-cpp-pro.cmake.generateCompilationDatabase`). +3. C/C++ Pro compiles target sources and isolated private/public includes into a standards-compliant compilation database. +4. Language standards are tailored per source file: + - C files (`.c`) receive pure C standards (`-std=c17`, `clang`). + - C++ files (`.cpp`, `.cxx`, `.cc`) receive C++ standards (`-std=c++20`, `clang++`). + +--- + +## 4. CMake Commands Reference + +| Command | Identifier | Action | +| :--- | :--- | :--- | +| **CMake Intelligence Menu** | `c-cpp-pro.cmake.menu` | Opens a quick-pick popup with available CMake actions. | +| **Re-scan CMakeLists.txt Includes** | `c-cpp-pro.cmake.rescan` | Manually triggers a re-parse of all workspace `CMakeLists.txt` files. | +| **Generate Compilation Database** | `c-cpp-pro.cmake.generateCompilationDatabase` | Synthesizes `compile_commands.json` from parsed CMake targets. | + +--- + +## 5. Configuration Settings + +| Setting | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `c-cpp-pro.cmake.autoScan` | `boolean` | `true` | Automatically parse `CMakeLists.txt` on folder open and file save. | +| `c-cpp-pro.cppStandard` | `string` | `"c++20"` | C++ standard emitted for synthesized CMake compile commands. | +| `c-cpp-pro.cStandard` | `string` | `"c17"` | C standard emitted for synthesized CMake compile commands. | diff --git a/wiki/Visual-Studio-Solution-Support.md b/wiki/Visual-Studio-Solution-Support.md new file mode 100644 index 0000000..92e70af --- /dev/null +++ b/wiki/Visual-Studio-Solution-Support.md @@ -0,0 +1,71 @@ +# Visual Studio Solution Support + +C/C++ Pro delivers native, static support for Visual Studio solutions and project files on Windows, Linux, and macOS. You can navigate, configure, and build enterprise Visual Studio codebases directly within Visual Studio Code without requiring the full Visual Studio IDE to be running. + +--- + +## 1. Supported File Formats + +C/C++ Pro statically parses both legacy and modern Visual Studio project files: + +| Format | Extension | Description | Parser Implementation | +| :--- | :--- | :--- | :--- | +| **Traditional Solution** | `.sln` | Standard Visual Studio text format containing project GUIDs and configurations. | Native Rust parser (`crates/c-cpp-pro-native/src/solution.rs`) | +| **Modern Solution** | `.slnx` | Next-generation XML-based solution format introduced in Visual Studio 2022. | Native Rust parser (`quick-xml`) | +| **C++ Project** | `.vcxproj` | MSBuild XML project specification containing item groups, property sheets, and compile flags. | Native Rust parser (`quick-xml`) | + +--- + +## 2. Static Parsing & Metadata Extraction + +C/C++ Pro parses project definitions statically at native speeds without invoking `devenv.exe` or executing MSBuild: +- **Include Directories**: Resolves `AdditionalIncludeDirectories` across project properties and inherited property sheets (`.props`). +- **Preprocessor Definitions**: Extracts `PreprocessorDefinitions` per build configuration. +- **Language Standards**: Detects C++ standard (`/std:c++14`, `/std:c++17`, `/std:c++20`, `/std:c++latest`) and C standard (`/std:c11`, `/std:c17`). +- **Forced Includes**: Parses forced header dependencies (`/FI` or ``). +- **Configuration & Platform Matrix**: Fully supports `Debug`, `Release`, `MinSizeRel`, and custom configurations across `x64`, `x86`, `ARM64`, and `ARM` platforms. + +--- + +## 3. Compilation Database Generation + +To bridge Visual Studio projects into `clangd`'s language server, C/C++ Pro generates a unified `compile_commands.json` compilation database: + +1. Open the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`). +2. Run **`C/C++ Pro: Generate compile_commands.json from Solution`** (`c-cpp-pro.generateCompilationDbFromSolution`). +3. C/C++ Pro inspects all active `.vcxproj` project files and translates MSVC options into Clang driver mode flags (`--driver-mode=cl`, `/D`, `/I`, `/std:c++20`). +4. The synthesized compilation database is saved to the workspace root, immediately providing full semantic autocomplete, diagnostics, and navigation across the entire solution. + +--- + +## 4. Solution Management & MSBuild Tasks + +C/C++ Pro provides integrated commands and task runners to manage solutions: + +### Commands +- **`C/C++ Pro: Select Active Solution (.sln / .slnx)`** (`c-cpp-pro.selectSolution`): Switch between multiple solution files present in the workspace. +- **`C/C++ Pro: Select Solution Configuration`** (`c-cpp-pro.selectSolutionConfiguration`): Switch active build configuration (e.g. `Debug|x64` to `Release|x64`). +- **`C/C++ Pro: Solution Actions Menu`** (`c-cpp-pro.solutionMenu`): Quick pick menu to build, clean, rebuild, or re-generate compilation databases. +- **`C/C++ Pro: Build Solution (MSBuild)`** (`c-cpp-pro.buildSolution`): Build the active solution using MSBuild. +- **`C/C++ Pro: Rebuild Solution (MSBuild)`** (`c-cpp-pro.rebuildSolution`): Clean and recompile all projects in the solution. +- **`C/C++ Pro: Clean Solution (MSBuild)`** (`c-cpp-pro.cleanSolution`): Remove build artifacts and intermediate files. + +### MSBuild Task Provider +C/C++ Pro automatically registers an `msbuild` task definition for VS Code's Task runner (`Ctrl+Shift+B`): + +```json +{ + "type": "msbuild", + "solution": "${workspaceFolder}/MyProject.slnx", + "configuration": "Debug", + "platform": "x64", + "target": "Build", + "problemMatcher": "$msCompile" +} +``` + +--- + +## 5. Cross-Platform Solution Exploration + +Because parsing is implemented natively without reliance on Windows COM APIs or the MSBuild executable, solution structure, include graphs, and `compile_commands.json` generation work seamlessly on **Linux** and **macOS**, allowing cross-compiling or remote inspection of Windows C++ projects.