Skip to content

Commit e707c70

Browse files
committed
git commit -m "feat(cpp-templates): Smart C++ debug template generation
- Auto-parse test data from markdown - Detect types (vector<string>, vector<int>, etc.) - Extract real method names - Match parameter counts - Decode HTML entities - Updated docs and dependencies"
1 parent 3e0e203 commit e707c70

File tree

4 files changed

+213
-24
lines changed

4 files changed

+213
-24
lines changed

README.md

Lines changed: 173 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,25 @@
44
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
55
[![Daily Challenges](https://img.shields.io/badge/feature-Daily%20Challenges-orange.svg)](#-daily-challenges-feature)
66

7-
> **Enhanced fork of the official LeetCode VS Code extension with Daily Challenges support and improved functionality.**
7+
> **Enhanced fork of the LeetCode VS Code extension with Daily Challenges support and C++ Debug Templates.**
8+
9+
## 🚀 Quick Start
10+
11+
```bash
12+
# Install and try the new features
13+
git clone https://github.com/su-mt/vscode-leetcode.git
14+
cd vscode-leetcode
15+
npm run compile
16+
vsce package
17+
code --install-extension vscode-leetcode-0.18.5.vsix
18+
19+
```
20+
21+
**✨ What's immediately available:**
22+
- 📅 **Daily Challenges** in Explorer panel
23+
- 🔧 **Auto-generated C++ debug templates** with real method names ([📹 See Demo](docs/gifs/output.gif))
24+
-**Smart caching** for faster loading
25+
- 🎯 **Type-aware variable generation** (`vector<string>`, `vector<int>`, etc.)
826

927
## 🎯 What's New in This Fork
1028

@@ -16,7 +34,7 @@ This fork extends the original [LeetCode VS Code Extension](https://github.com/L
1634
|---------|-------------|--------|
1735
| 📅 **Daily Challenges** | View and solve daily coding challenges directly in Explorer |**NEW** |
1836
|**Smart Caching** | 30-minute intelligent cache for optimal performance |**NEW** |
19-
| 🔧 **Enhanced C++ Templates** | Auto-generated headers and improved code templates |**NEW** |
37+
| 🔧 **Enhanced C++ Debug Templates** | Auto-generated debug code with smart type detection and real method names ([📹 Demo](docs/gifs/output.gif)) |**NEW** |
2038
| 🌍 **Multi-endpoint Support** | Full support for both LeetCode.com and LeetCode.cn |**ENHANCED** |
2139
| 📊 **Historical Tracking** | Access to 30 days of daily challenge history |**NEW** |
2240
| 🌐 **Translation Support** | Localized content support for daily challenges |**NEW** |
@@ -69,6 +87,116 @@ LeetCode Explorer
6987

7088
---
7189

90+
## 🔧 Enhanced C++ Debug Templates
91+
92+
### 🎯 What It Does
93+
The **Enhanced C++ Debug Templates** feature provides intelligent auto-generation of debug code for C++ problems, making testing and debugging significantly easier.
94+
95+
### ✨ Key Features
96+
97+
| Feature | Description | Example |
98+
|---------|-------------|---------|
99+
| 🧠 **Smart Type Detection** | Automatically detects `vector<int>`, `vector<string>`, `string`, `int`, `bool`, `double` | `vector<string> arr1 = {"flower", "flow", "flight"};` |
100+
| 🎯 **Method Name Extraction** | Extracts real method names from problem code | `auto result = sol.twoSum(arr1, num2);` instead of `someMethod` |
101+
| 📊 **Parameter Count Matching** | Uses only the required number of parameters based on function signature | Function expects 2 params → uses first 2 from test data |
102+
| 🔄 **HTML Entity Decoding** | Properly handles `&quot;``"` and other HTML entities | Clean string values without encoding artifacts |
103+
| 🎨 **Deduplication** | Removes duplicate test data while preserving order | No repeated values in generated template |
104+
| 📝 **Markdown Parsing** | Extracts test data from problem descriptions automatically | Parses `Input: nums = [2,7,11,15], target = 9` |
105+
106+
### 🖼️ Before vs After
107+
108+
#### Before (Original Extension):
109+
```cpp
110+
// @lc code=start
111+
class Solution {
112+
public:
113+
vector<int> twoSum(vector<int>& nums, int target) {
114+
115+
}
116+
};
117+
// @lc code=end
118+
```
119+
120+
#### After (Enhanced Fork):
121+
```cpp
122+
#include <iostream>
123+
...<headers>...
124+
using namespace std;
125+
126+
/*
127+
* @lc app=leetcode id=1 lang=cpp
128+
*
129+
* [1] Two Sum
130+
*/
131+
132+
// @lc code=start
133+
class Solution {
134+
public:
135+
vector<int> twoSum(vector<int>& nums, int target) {
136+
137+
}
138+
};
139+
// @lc code=end
140+
141+
int main()
142+
{
143+
Solution sol;
144+
145+
// Тестовые данные:
146+
vector<int> arr1 = {2, 7, 11, 15};
147+
int num2 = 9;
148+
vector<int> arr3 = {3, 2, 4};
149+
int num4 = 6;
150+
vector<int> arr5 = {3, 3};
151+
152+
auto result = sol.twoSum(arr1, num2);
153+
154+
155+
return 0;
156+
}
157+
158+
```
159+
160+
### 🎬 Live Demo
161+
162+
**Watch the Enhanced C++ Debug Templates in action:**
163+
164+
![C++ Debug Templates Demo](docs/gifs/output.gif)
165+
166+
*The demo shows:*
167+
- 🔍 **Automatic parsing** of Input examples from problem description
168+
- 🧠 **Smart type detection** (`vector<string>`, `vector<int>`, `int`, etc.)
169+
- 🎯 **Real method name extraction** (`twoSum`, `longestCommonPrefix`, etc.)
170+
-**Instant template generation** with properly typed variables
171+
- 🔧 **Parameter count matching** (only uses required number of params)
172+
173+
### 🚀 How It Works
174+
175+
1. **Extract Test Data**: Parses problem description for `Input:` examples
176+
2. **Decode HTML**: Converts HTML entities (`&quot;``"`) to clean values
177+
3. **Detect Types**: Analyzes values to determine C++ types
178+
4. **Extract Method**: Finds real method name and parameter count from code
179+
5. **Generate Template**: Creates properly typed variables and method call
180+
181+
### 🎯 Supported Data Types
182+
183+
```cpp
184+
// Arrays
185+
vector<int> nums = {1, 2, 3}; // from [1,2,3]
186+
vector<string> strs = {"a", "b", "c"}; // from ["a","b","c"]
187+
188+
// Primitives
189+
string s = "hello"; // from "hello"
190+
int target = 42; // from 42
191+
double rate = 3.14; // from 3.14
192+
bool flag = true; // from true
193+
194+
// Method calls with correct parameter count
195+
auto result = sol.twoSum(nums, target); // Only uses required params
196+
```
197+
198+
---
199+
72200
## 🔧 Technical Implementation
73201
74202
### 📊 Architecture Overview
@@ -91,7 +219,9 @@ graph TD
91219
| **API Methods** | `src/leetCodeExecutor.ts` | GraphQL integration for daily challenges |
92220
| **Cache Manager** | `src/explorer/explorerNodeManager.ts` | Smart caching and data management |
93221
| **UI Integration** | `src/explorer/LeetCodeTreeDataProvider.ts` | Explorer tree integration |
94-
| **C++ Templates** | `src/leetCodeExecutor.ts` | Enhanced code template generation |
222+
| **Enhanced C++ Parser** | `src/leetCodeExecutor.ts` | Intelligent test data extraction and debug template generation |
223+
| **Method Name Extraction** | `src/leetCodeExecutor.ts` | Real method name detection from C++ code |
224+
| **Type Detection System** | `src/leetCodeExecutor.ts` | Smart C++ type inference for variables |
95225

96226
### 🌐 API Integration
97227

@@ -104,7 +234,7 @@ graph TD
104234

105235
## 📦 Installation & Setup
106236

107-
### 🔄 Option 1: Install from VSIX (Recommended)
237+
### Install from VSIX (Recommended)
108238

109239
```bash
110240
# Clone this repository
@@ -124,18 +254,45 @@ npm run build
124254
code --install-extension vscode-leetcode-fork-0.18.5.vsix
125255
```
126256

127-
### 🔗 Option 2: Development Mode
257+
### 📦 Required Extensions (Auto-installed)
258+
259+
When you install this extension, the following extensions will be **automatically installed** as part of the extension pack:
260+
261+
| Extension | Purpose | Auto-install |
262+
|-----------|---------|--------------|
263+
| **C/C++ Extension** (`ms-vscode.cpptools`) | C++ IntelliSense, debugging, and code browsing |**Automatic** |
264+
| **Python Extension** (`ms-python.python`) | Python language support and debugging |**Automatic** |
265+
266+
> **✨ Note**: These extensions are included in our extension pack, so you don't need to install them manually!
267+
268+
### 🔧 Optional Extensions (Recommended)
269+
270+
For an enhanced coding experience, consider installing these optional extensions:
128271

129272
```bash
130-
# Clone and open in VS Code
131-
git clone https://github.com/su-mt/vscode-leetcode.git
132-
cd vscode-leetcode
133-
code .
273+
# Enhanced C++ support
274+
code --install-extension ms-vscode.cmake-tools
275+
276+
# Git integration
277+
code --install-extension eamodio.gitlens
134278

135-
# Press F5 to launch Extension Development Host
136-
# The enhanced extension will be available in the new window
279+
# Code formatting
280+
code --install-extension ms-vscode.vscode-clangd
137281
```
138282

283+
### ⚡ Quick Verification
284+
285+
After installation, verify everything is working:
286+
287+
1. **Open VS Code**
288+
2. **Check Extensions**: Go to Extensions view (`Ctrl+Shift+X`) and verify:
289+
- ✅ LeetCode Enhanced Fork is installed
290+
- ✅ C/C++ extension is installed
291+
- ✅ Python extension is installed
292+
3. **Open LeetCode Explorer**: Look for the LeetCode icon in the Activity Bar
293+
4. **Find Daily Challenges**: Check for the "📅 Daily Challenges" section
294+
295+
139296
---
140297

141298
## 🆚 Comparison with Original
@@ -144,11 +301,15 @@ code .
144301
|---------|-------------------|-----------|
145302
| Basic LeetCode Integration |||
146303
| Problem Explorer |||
147-
| Code Templates | | ✅ Enhanced |
304+
| Code Templates | |**Enhanced** |
148305
| Submit & Test |||
149306
| **Daily Challenges** ||**NEW** |
150307
| **Smart Caching** ||**NEW** |
151308
| **C++ Auto-headers** ||**NEW** |
309+
| **C++ Debug Templates** ||**NEW** |
310+
| **Smart Type Detection** ||**NEW** |
311+
| **Method Name Extraction** ||**NEW** |
312+
| **HTML Entity Decoding** ||**NEW** |
152313
| **Historical Tracking** ||**NEW** |
153314
| Multi-language Support || ✅ Enhanced |
154315

docs/gifs/output.gif

759 KB
Loading

package.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -743,5 +743,10 @@
743743
"require-from-string": "^2.0.2",
744744
"unescape-js": "^1.1.4",
745745
"vsc-leetcode-cli": "2.8.1"
746-
}
746+
},
747+
"extensionDependencies": [],
748+
"extensionPack": [
749+
"ms-vscode.cpptools",
750+
"ms-python.python"
751+
]
747752
}

src/leetCodeExecutor.ts

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -826,27 +826,33 @@ using namespace std;
826826
return elements;
827827
}
828828

829-
private extractMethodName(codeTemplate: string): string {
829+
private extractMethodName(codeTemplate: string): { name: string, paramCount: number } {
830830
// Ищем публичный метод в классе Solution
831-
const methodPattern = /public:\s*[\w\s<>*&:\[\]]*\s+(\w+)\s*\(/;
831+
const methodPattern = /public:\s*[\w\s<>*&:\[\]]*\s+(\w+)\s*\(([^)]*)\)/;
832832
const match = codeTemplate.match(methodPattern);
833833

834834
if (match && match[1]) {
835-
console.log('🔧 Найден метод:', match[1]);
836-
return match[1];
835+
const methodName = match[1];
836+
const params = match[2].trim();
837+
const paramCount = params === '' ? 0 : params.split(',').length;
838+
console.log('🔧 Найден метод:', methodName, 'с', paramCount, 'параметрами');
839+
return { name: methodName, paramCount };
837840
}
838841

839842
// Если не найден паттерн public:, ищем любой метод после класса Solution
840-
const anyMethodPattern = /class\s+Solution\s*{[^}]*?[\w\s<>*&:\[\]]*\s+(\w+)\s*\(/;
843+
const anyMethodPattern = /class\s+Solution\s*{[^}]*?[\w\s<>*&:\[\]]*\s+(\w+)\s*\(([^)]*)\)/;
841844
const anyMatch = codeTemplate.match(anyMethodPattern);
842845

843846
if (anyMatch && anyMatch[1] && anyMatch[1] !== 'Solution') {
844-
console.log('🔧 Найден метод (альтернативный поиск):', anyMatch[1]);
845-
return anyMatch[1];
847+
const methodName = anyMatch[1];
848+
const params = anyMatch[2].trim();
849+
const paramCount = params === '' ? 0 : params.split(',').length;
850+
console.log('🔧 Найден метод (альтернативный поиск):', methodName, 'с', paramCount, 'параметрами');
851+
return { name: methodName, paramCount };
846852
}
847853

848854
console.log('⚠️ Метод не найден, используем someMethod');
849-
return 'someMethod';
855+
return { name: 'someMethod', paramCount: 0 };
850856
}
851857

852858
private generateCppDebugTemplate(parsedArgs: { args: string[] }, codeTemplate?: string): string {
@@ -922,11 +928,28 @@ int main()
922928
}
923929
});
924930

925-
// Извлекаем название метода из кода
926-
const methodName = codeTemplate ? this.extractMethodName(codeTemplate) : 'someMethod';
931+
// Извлекаем название метода и количество параметров из кода
932+
const methodInfo = codeTemplate ? this.extractMethodName(codeTemplate) : { name: 'someMethod', paramCount: 0 };
933+
const methodName = methodInfo.name;
934+
const expectedParamCount = methodInfo.paramCount;
927935

928936
if (paramNames.length > 0) {
929-
methodCall = ` auto result = sol.${methodName}(${paramNames.join(', ')});`;
937+
// Используем только необходимое количество параметров
938+
const actualParams = paramNames.slice(0, expectedParamCount);
939+
940+
if (actualParams.length === expectedParamCount) {
941+
methodCall = ` auto result = sol.${methodName}(${actualParams.join(', ')});`;
942+
} else if (actualParams.length < expectedParamCount) {
943+
// Не хватает параметров
944+
const missingCount = expectedParamCount - actualParams.length;
945+
const placeholders = Array(missingCount).fill('/* param */');
946+
methodCall = ` auto result = sol.${methodName}(${[...actualParams, ...placeholders].join(', ')});`;
947+
} else {
948+
// Слишком много параметров (не должно происходить с slice)
949+
methodCall = ` auto result = sol.${methodName}(${actualParams.join(', ')});`;
950+
}
951+
952+
console.log(`🎯 Метод ${methodName} ожидает ${expectedParamCount} параметров, используем ${actualParams.length}`);
930953
} else {
931954
methodCall = ` // auto result = sol.${methodName}(/* укажите нужные параметры */);`;
932955
}

0 commit comments

Comments
 (0)