The getNamespacesBySize
function parses C# code and retrieves namespaces based on their size, sorting them in descending order. It is exported as a module and takes a string of C# code as input, returning an array of namespace names.
npm run import -- "list csharp namespaces"
async function getNamespacesBySize(code) {
const selectCode = await importer.import("select antlr tree")
const result = await selectCode(['//namespace_declaration', {
start: './@start',
stop: './@stop',
name: '(./qualified_identifier/@strdata)[1]'
}], code, 'csharp')
result.sort((a, b) => (b.stop - b.start) - (a.stop - a.start))
return result.map(r => r.name)
}
module.exports = getNamespacesBySize
const { importAntlrTree } = require('./importer'); // assume importer is a custom module
/**
* Retrieves namespaces by size from C# code using ANTLR tree.
*
* @param {string} code - The C# code to parse.
* @returns {Promise} An array of namespace names in descending order of namespace size.
*/
async function getNamespacesBySize(code) {
// TODO: Consider caching ANTLR tree imports for performance
const antlrTree = await importAntlrTree('select');
// Extract namespace declarations from the code
const namespaceDeclarations = antlrTree(['//namespace_declaration'], code, 'csharp');
// Filter out namespace declarations with empty names
const namedDeclarations = namespaceDeclarations.filter(decl => decl.name);
// Sort namespace declarations by size in descending order
namedDeclarations.sort((a, b) => (b.stop - b.start) - (a.stop - a.start));
// Return an array of namespace names
return namedDeclarations.map(decl => decl.name);
}
module.exports = getNamespacesBySize;
getNamespacesBySize
Purpose: Retrieves namespaces from C# code based on their size.
Parameters:
code
: The C# code to parse.importer.import
function is used to load the 'select antlr tree'
module asynchronously.selectCode
function, now referencing the loaded module, is called with the following parameters:
//namespace_declaration
to target namespace declarations in the code.start
: The start position of the namespace declaration, specified as ./@start
.stop
: The stop position of the namespace declaration, specified as ./@stop
.name
: The namespace name, extracted from the first element of the qualified identifier within the namespace declaration.code
to parse.csharp
.The getNamespacesBySize
function is exported as a module.