Refactor symbol definition and reference retrieval

- Improved error handling and validation in symbol definition and reference retrieval functions.
- Enhanced the logic for finding the smallest symbol definition that contains the target range.
- Updated the function descriptions to provide more detailed information about their purpose, input, output, and error handling.
- Added 'ref_line' to the output of the symbol reference retrieval function.
This commit is contained in:
bobo.yang 2023-07-27 12:48:18 +08:00
parent 63fa9b1bd2
commit cd8f99405a
2 changed files with 247 additions and 180 deletions

View File

@ -24,7 +24,7 @@ async function findSymbolInWorkspace(symbolName: string, symbolline: number, sym
} }
// get definition of symbol // get definition of symbol
const refLocations = await vscode.commands.executeCommand<vscode.LocationLink[]>( const refLocations = await vscode.commands.executeCommand<vscode.Location[] | vscode.LocationLink[]>(
'vscode.executeDefinitionProvider', 'vscode.executeDefinitionProvider',
vscode.Uri.file(symbolFile), vscode.Uri.file(symbolFile),
symbolPosition symbolPosition
@ -34,59 +34,63 @@ async function findSymbolInWorkspace(symbolName: string, symbolline: number, sym
} }
// get related source lines // get related source lines
let contextList: Set<string> = new Set(); const contextListPromises = refLocations.map(async (refLocation) => {
for (const refLocation of refLocations) { let refLocationFile: string;
const refLocationFile = refLocation.targetUri.fsPath; let targetRange: vscode.Range;
if (refLocation instanceof vscode.Location) {
refLocationFile = refLocation.uri.fsPath;
targetRange = refLocation.range;
// get symbols in file
const symbols = await vscode.commands.executeCommand<vscode.DocumentSymbol[]>(
'vscode.executeDocumentSymbolProvider',
vscode.Uri.file(refLocationFile)
);
// find the smallest symbol definition that contains the target range
let smallestSymbol: vscode.DocumentSymbol | undefined;
for (const symbol of symbols) {
smallestSymbol = findSmallestSymbol(symbol, targetRange, smallestSymbol);
}
if (smallestSymbol) {
targetRange = smallestSymbol.range;
}
} else {
refLocationFile = refLocation.targetUri.fsPath;
targetRange = refLocation.targetRange;
}
const documentNew = await vscode.workspace.openTextDocument(refLocationFile); const documentNew = await vscode.workspace.openTextDocument(refLocationFile);
const data = { const data = {
path: refLocation.targetUri.fsPath, path: refLocationFile,
start_line: refLocation.targetRange.start.line, start_line: targetRange.start.line,
end_line: refLocation.targetRange.end.line, end_line: targetRange.end.line,
content: documentNew.getText(refLocation.targetRange) content: documentNew.getText(targetRange)
}; };
contextList.add(JSON.stringify(data)); return JSON.stringify(data);
});
// // get symbol define in symbolFile const contextList = await Promise.all(contextListPromises);
// const symbolsT: vscode.DocumentSymbol[] = await vscode.commands.executeCommand<vscode.DocumentSymbol[]>(
// 'vscode.executeDocumentSymbolProvider',
// refLocation.targetUri
// );
// if (!symbolsT) {
// continue;
// }
// let symbolsList: vscode.DocumentSymbol[] = [];
// const visitSymbol = (symbol: vscode.DocumentSymbol) => {
// symbolsList.push(symbol);
// if (symbol.children) {
// for (const child of symbol.children) {
// visitSymbol(child);
// }
// }
// };
// for (const symbol of symbolsT) {
// visitSymbol(symbol);
// }
// let symbol: vscode.DocumentSymbol | undefined = undefined; return contextList;
// for (const symbolT of symbolsList.reverse()) {
// if (symbolT.range.contains(refLocation.) && symbolT.name === symbolName) {
// symbol = symbolT;
// break;
// }
// }
// if (symbol) {
// const data = {
// path: refLocation.uri,
// start_line: symbol.range.start.line,
// content: documentNew.getText(symbol.range)
// };
// contextList.add(JSON.stringify(data));
// }
} }
return Array.from(contextList); function findSmallestSymbol(symbol: vscode.DocumentSymbol, targetRange: vscode.Range, smallestSymbol: vscode.DocumentSymbol | undefined): vscode.DocumentSymbol | undefined {
if (symbol.range.contains(targetRange) &&
(!smallestSymbol || smallestSymbol.range.contains(symbol.range))) {
smallestSymbol = symbol;
} }
for (const child of symbol.children) {
smallestSymbol = findSmallestSymbol(child, targetRange, smallestSymbol);
}
return smallestSymbol;
}
export class SymbolDefAction implements Action { export class SymbolDefAction implements Action {
name: string; name: string;
description: string; description: string;
@ -97,7 +101,18 @@ export class SymbolDefAction implements Action {
constructor() { constructor() {
this.name = 'symbol_def'; this.name = 'symbol_def';
this.description = 'Retrieve the definition of symbol.'; this.description = `
Function Purpose: This function retrieves the definition information for a given symbol.
Input: The symbol should not be in string format or in 'a.b' format. To find the definition of 'a.b', simply refer to 'b'.
Output: The function returns a dictionary with the following keys:
'exitCode': If 'exitCode' is 0, the function execution was successful. If 'exitCode' is not 0, the function execution failed.
'stdout': If the function executes successfully, 'stdout' is a list of JSON strings. Each JSON string contains:
'path': The file path.
'start_line': The start line of the content.
'end_line': The end line of the content.
'content': The source code related to the definition.
'stderr': Error output if any.
Error Handling: If the function execution fails, 'exitCode' will not be 0 and 'stderr' will contain the error information.`;
this.type = ['symbol']; this.type = ['symbol'];
this.action = 'symbol_def'; this.action = 'symbol_def';
this.handler = []; this.handler = [];
@ -130,6 +145,21 @@ export class SymbolDefAction implements Action {
const symbolLine = args.line; const symbolLine = args.line;
let symbolFile = args.file; let symbolFile = args.file;
// Check if the symbol name is valid
if (!symbolName || typeof symbolName !== 'string') {
throw new Error('Invalid symbol name. It should be a non-empty string.');
}
// Check if the symbol line is valid
if (!symbolLine || typeof symbolLine !== 'number' || symbolLine < 0) {
throw new Error('Invalid symbol line. It should be a non-negative number.');
}
// Check if the symbol file is valid
if (!symbolFile || typeof symbolFile !== 'string') {
throw new Error('Invalid symbol file. It should be a non-empty string.');
}
// if symbolFile is not absolute path, then get it's absolute path // if symbolFile is not absolute path, then get it's absolute path
if (!path.isAbsolute(symbolFile)) { if (!path.isAbsolute(symbolFile)) {
const basePath = UiUtilWrapper.workspaceFoldersFirstPath(); const basePath = UiUtilWrapper.workspaceFoldersFirstPath();

View File

@ -16,11 +16,20 @@ const readFile = util.promisify(fs.readFile);
async function isCorrectIndexSymbol(filename: string, position: vscode.Position, symbolName: string): Promise< boolean > { async function isCorrectIndexSymbol(filename: string, position: vscode.Position, symbolName: string): Promise< boolean > {
const defLocations = await vscode.commands.executeCommand<any[]>( let defLocations = await vscode.commands.executeCommand<any[]>(
'vscode.executeDefinitionProvider', 'vscode.executeDefinitionProvider',
vscode.Uri.file(filename), vscode.Uri.file(filename),
position position
); );
if (!defLocations || defLocations.length === 0) {
defLocations = await vscode.commands.executeCommand<any[]>(
'vscode.executeReferenceProvider',
vscode.Uri.file(filename),
position
);
}
if (!defLocations) { if (!defLocations) {
return false; return false;
} }
@ -89,17 +98,19 @@ export async function getSymbolPosition(symbolName: string, symbolLine: number,
async function findSymbolInWorkspace(symbolName: string, symbolline: number, symbolFile: string): Promise<string[]> { async function findSymbolInWorkspace(symbolName: string, symbolline: number, symbolFile: string): Promise<string[]> {
const symbolPosition = await getSymbolPosition(symbolName, symbolline, symbolFile); const symbolPosition = await getSymbolPosition(symbolName, symbolline, symbolFile);
if (!symbolPosition) { if (!symbolPosition) {
return []; throw new Error(`Symbol "${symbolName}" not found in file "${symbolFile}" at line ${symbolline}.`);
} }
logger.channel()?.info(`symbol position: ${symbolPosition.line}:${symbolPosition.character}`);
// get all references of symbol // get all references of symbol
const refLocations = await vscode.commands.executeCommand<vscode.Location[]>( const refLocations = await vscode.commands.executeCommand<vscode.Location[]>(
'vscode.executeReferenceProvider', 'vscode.executeReferenceProvider',
vscode.Uri.file(symbolFile), vscode.Uri.file(symbolFile),
symbolPosition symbolPosition
); );
if (!refLocations) { if (!refLocations || refLocations.length === 0) {
return []; throw new Error(`No references found for symbol "${symbolName}" in file "${symbolFile}" at line ${symbolline}.`);
} }
// get related source lines // get related source lines
@ -118,10 +129,6 @@ async function findSymbolInWorkspace(symbolName: string, symbolline: number, sym
'vscode.executeDocumentSymbolProvider', 'vscode.executeDocumentSymbolProvider',
refLocation.uri refLocation.uri
); );
if (!symbolsT) {
logger.channel()?.info(`Symbol ref continue...`);
continue;
}
let symbolsList: vscode.DocumentSymbol[] = []; let symbolsList: vscode.DocumentSymbol[] = [];
const visitSymbol = (symbol: vscode.DocumentSymbol) => { const visitSymbol = (symbol: vscode.DocumentSymbol) => {
symbolsList.push(symbol); symbolsList.push(symbol);
@ -131,9 +138,11 @@ async function findSymbolInWorkspace(symbolName: string, symbolline: number, sym
} }
} }
}; };
if (symbolsT) {
for (const symbol of symbolsT) { for (const symbol of symbolsT) {
visitSymbol(symbol); visitSymbol(symbol);
} }
}
let symbol: vscode.DocumentSymbol | undefined = undefined; let symbol: vscode.DocumentSymbol | undefined = undefined;
for (const symbolT of symbolsList.reverse()) { for (const symbolT of symbolsList.reverse()) {
@ -149,6 +158,7 @@ async function findSymbolInWorkspace(symbolName: string, symbolline: number, sym
const data = { const data = {
path: refLocationFile, path: refLocationFile,
start_line: startLine, start_line: startLine,
ref_line: refLocation.range.start.line,
content: documentNew.getText(rangeNew), content: documentNew.getText(rangeNew),
parentDefine: symbolName, parentDefine: symbolName,
parentDefineStartLine: symbolLine parentDefineStartLine: symbolLine
@ -168,7 +178,19 @@ export class SymbolRefAction implements Action {
constructor() { constructor() {
this.name = 'symbol_ref'; this.name = 'symbol_ref';
this.description = 'Retrieve the reference information related to the symbol'; this.description = `
Function Purpose: This function retrieves the reference information for a given symbol.
Input: The symbol should not be in string format or in 'a.b' format. To find the reference of 'a.b', simply refer to 'b'.
Output: The function returns a dictionary with the following keys:
'exitCode': If 'exitCode' is 0, the function execution was successful. If 'exitCode' is not 0, the function execution failed.
'stdout': If the function executes successfully, 'stdout' is a list of JSON strings. Each JSON string contains:
'path': The file path.
'ref_line': The ref line of the symbol.
'content': The source code related to the reference.
'parentDefine': The parent symbol name of the reference, which is always a function name or class name.
'parentDefineStartLine': The start line of the parent symbol name of the reference.
'stderr': Error output if any.
Error Handling: If the function execution fails, 'exitCode' will not be 0 and 'stderr' will contain the error information.`;
this.type = ['symbol']; this.type = ['symbol'];
this.action = 'symbol_ref'; this.action = 'symbol_ref';
this.handler = []; this.handler = [];
@ -201,6 +223,21 @@ export class SymbolRefAction implements Action {
const symbolLine = args.line; const symbolLine = args.line;
let symbolFile = args.file; let symbolFile = args.file;
// Check if the symbol name is valid
if (!symbolName || typeof symbolName !== 'string') {
throw new Error('Invalid symbol name. It should be a non-empty string.');
}
// Check if the symbol line is valid
if (!symbolLine || typeof symbolLine !== 'number' || symbolLine < 0) {
throw new Error('Invalid symbol line. It should be a non-negative number.');
}
// Check if the symbol file is valid
if (!symbolFile || typeof symbolFile !== 'string') {
throw new Error('Invalid symbol file. It should be a non-empty string.');
}
// if symbolFile is not absolute path, then get it's absolute path // if symbolFile is not absolute path, then get it's absolute path
if (!path.isAbsolute(symbolFile)) { if (!path.isAbsolute(symbolFile)) {
const basePath = UiUtilWrapper.workspaceFoldersFirstPath(); const basePath = UiUtilWrapper.workspaceFoldersFirstPath();