File size: 8,091 Bytes
e1847c0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
class OpenCodeAI {
constructor() {
this.supportedLanguages = [
'javascript', 'python', 'java', 'cpp', 'c', 'csharp',
'go', 'rust', 'php', 'typescript', 'html', 'css'
];
}
// 分析代码质量
async analyzeCode(code, language) {
const analysis = {
language: this.detectLanguage(code, language),
issues: [],
suggestions: [],
metrics: this.calculateMetrics(code)
};
// 基本语法检查
analysis.issues = this.checkSyntax(code, analysis.language);
// 生成改进建议
analysis.suggestions = this.generateSuggestions(code, analysis.language);
return analysis;
}
// 检测编程语言
detectLanguage(code, hintedLanguage) {
if (hintedLanguage && this.supportedLanguages.includes(hintedLanguage)) {
return hintedLanguage;
}
// 简单的语言检测
if (code.includes('def ') && code.includes(':')) return 'python';
if (code.includes('function ') || code.includes('const ')) return 'javascript';
if (code.includes('public class ')) return 'java';
if (code.includes('#include')) return 'cpp';
if (code.includes('<!DOCTYPE')) return 'html';
if (code.includes('{') && code.includes('}')) return 'css';
return 'javascript'; // 默认
}
// 检查语法问题
checkSyntax(code, language) {
const issues = [];
// 通用检查
const lines = code.split('\n');
lines.forEach((line, index) => {
// 检查未闭合的括号
if (line.includes('{') || line.includes('(') || line.includes('[')) {
const openBrackets = (line.match(/[({[]/g) || []).length;
const closeBrackets = (line.match(/[)}\]]/g) || []).length;
if (openBrackets !== closeBrackets) {
issues.push({
line: index + 1,
type: 'syntax',
message: '可能存在未闭合的括号',
severity: 'warning'
});
}
}
// 检查过长的行
if (line.length > 120) {
issues.push({
line: index + 1,
type: 'style',
message: '行长度过长 (>120字符)',
severity: 'info'
});
}
});
// 语言特定检查
switch (language) {
case 'javascript':
issues.push(...this.checkJavaScript(code));
break;
case 'python':
issues.push(...this.checkPython(code));
break;
case 'java':
issues.push(...this.checkJava(code));
break;
}
return issues;
}
// JavaScript 特定检查
checkJavaScript(code) {
const issues = [];
// 检查var关键字
if (code.includes('var ')) {
issues.push({
line: null,
type: 'style',
message: '建议使用 let 或 const 替代 var',
severity: 'warning'
});
}
// 检查分号缺失
const statements = code.split('\n').filter(line =>
line.trim() && !line.trim().startsWith('//') &&
!line.trim().startsWith('/*') &&
!line.includes('{') && !line.includes('}') &&
!line.endsWith(';') && !line.endsWith(',') &&
!line.includes('if ') && !line.includes('for ') &&
!line.includes('while ') && !line.includes('function ')
);
if (statements.length > 0) {
issues.push({
line: null,
type: 'style',
message: '可能缺少分号',
severity: 'info'
});
}
return issues;
}
// Python 特定检查
checkPython(code) {
const issues = [];
// 检查PEP 8缩进
const lines = code.split('\n');
lines.forEach((line, index) => {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#')) {
const leadingSpaces = line.length - line.trimStart().length;
if (leadingSpaces % 4 !== 0) {
issues.push({
line: index + 1,
type: 'style',
message: '缩进应该使用4个空格',
severity: 'warning'
});
}
}
});
return issues;
}
// Java 特定检查
checkJava(code) {
const issues = [];
// 检查类名
const classMatch = code.match(/class\s+(\w+)/);
if (classMatch && !/^[A-Z]/.test(classMatch[1])) {
issues.push({
line: null,
type: 'style',
message: '类名应该以大写字母开头',
severity: 'warning'
});
}
return issues;
}
// 生成代码改进建议
generateSuggestions(code, language) {
const suggestions = [];
// 性能建议
if (code.includes('for (')) {
suggestions.push({
type: 'performance',
message: '考虑使用更高效的循环方式,如 forEach 或 map',
code_example: '// 替代方案\narray.forEach(item => { /* ... */ });'
});
}
// 可读性建议
if (code.includes('TODO') || code.includes('FIXME')) {
suggestions.push({
type: 'maintenance',
message: '发现待办事项,建议及时处理'
});
}
// 安全建议
if (code.includes('eval(')) {
suggestions.push({
type: 'security',
message: '避免使用 eval(),存在安全风险',
severity: 'high'
});
}
return suggestions;
}
// 计算代码指标
calculateMetrics(code) {
const lines = code.split('\n');
const totalLines = lines.length;
const codeLines = lines.filter(line =>
line.trim() && !line.trim().startsWith('//') &&
!line.trim().startsWith('#') && !line.trim().startsWith('/*')
).length;
return {
total_lines: totalLines,
code_lines: codeLines,
comment_lines: totalLines - codeLines,
complexity: this.calculateComplexity(code)
};
}
// 计算圈复杂度
calculateComplexity(code) {
let complexity = 1; // 基础复杂度
const complexityKeywords = ['if', 'else', 'for', 'while', 'switch', 'case', 'catch', '&&', '||'];
complexityKeywords.forEach(keyword => {
const regex = new RegExp(`\\b${keyword}\\b`, 'g');
const matches = code.match(regex);
if (matches) complexity += matches.length;
});
return complexity;
}
// 代码补全
async getCodeCompletion(partialCode, position) {
// 简单的代码补全逻辑
const suggestions = [];
const line = partialCode.split('\n')[position.line - 1] || '';
const currentWord = line.substring(0, position.character).split(' ').pop();
const language = this.detectLanguage(partialCode);
switch (language) {
case 'javascript':
suggestions.push(...this.getJavaScriptCompletions(currentWord));
break;
case 'python':
suggestions.push(...this.getPythonCompletions(currentWord));
break;
default:
suggestions.push(...this.getGenericCompletions(currentWord));
}
return suggestions;
}
getJavaScriptCompletions(currentWord) {
const jsKeywords = [
'function', 'const', 'let', 'var', 'if', 'else', 'for', 'while',
'return', 'class', 'extends', 'import', 'export', 'async', 'await',
'map', 'filter', 'reduce', 'forEach', 'find', 'some', 'every'
];
return jsKeywords
.filter(keyword => keyword.startsWith(currentWord))
.map(keyword => ({
text: keyword,
type: 'keyword',
description: `JavaScript keyword: ${keyword}`
}));
}
getPythonCompletions(currentWord) {
const pythonKeywords = [
'def', 'class', 'if', 'elif', 'else', 'for', 'while',
'return', 'import', 'from', 'as', 'try', 'except', 'with',
'len', 'range', 'list', 'dict', 'set', 'tuple', 'str'
];
return pythonKeywords
.filter(keyword => keyword.startsWith(currentWord))
.map(keyword => ({
text: keyword,
type: 'keyword',
description: `Python keyword: ${keyword}`
}));
}
getGenericCompletions(currentWord) {
return [
{ text: currentWord, type: 'variable', description: 'Current variable' }
];
}
}
export default OpenCodeAI; |