dylib | get c parameters | get c types | Search

The getExports function extracts function definitions from C++ code by parsing the input code and returning an array of function definitions as strings. It uses the select function from the antlr and tree modules to implement this functionality.

Run example

npm run import -- "get c exports"

get c exports


async function getExports(code) {
    const selectCode = await importer.import("select antlr tree")
    const result = await selectCode(['//functionDefinition', './declarator//declaratorid/@strdata'], code, 'cpp')
    return result.map(e => typeof e == 'string' ? e : e[0])
}

module.exports = getExports

What the code could have been:

/**
 * Retrieves function exports from the given code.
 *
 * @param {string} code - The code to extract exports from.
 * @returns {string[]} An array of function export names.
 */
async function getExports(code) {
  // Import required module with proper error handling
  try {
    const selectCode = await import('select-antlr-tree');
  } catch (error) {
    console.error('Error importing select-antlr-tree module:', error);
    return []; // Return an empty array if module import fails
  }

  // Extract function exports using select-antlr-tree
  try {
    const result = await selectCode(['//functionDefinition', './declarator//declaratorid/@strdata'], code, 'cpp');
    return result.map((e) => typeof e ==='string'? e : e[0]);
  } catch (error) {
    console.error('Error extracting function exports:', error);
    // Return an empty array if extraction fails
    return [];
  }
}

module.exports = getExports;

// TODO: Improve error handling and logging for production use
// TODO: Optimize the code for better performance
// TODO: Consider using a more robust parser instead of select-antlr-tree

Function: getExports

Description

Extracts function definitions from C++ code.

Parameters

Returns

An array of function definitions as strings.

Implementation

  1. Imports the select function from the antlr and tree modules.
  2. Uses the select function to extract function definitions from the input code.
  3. Maps the extracted results to a string representation, or the first element if the result is an array.

Export

The getExports function is exported as a module.