python | list c functions with python | | Search

The Node.js module provides a function pythonParams that uses the ANTLR4 tool to parse Python code and extract function parameters, returning them as an array of objects.

And here's a slightly expanded version in two sentences:

This Node.js module uses the ANTLR4 tool to parse Python code and extract function parameters, which are then returned as an array of objects. The module exports a single function, pythonParams, which can be used to analyze Python code and extract function parameter information.

Run example

npm run import -- "python params in antrl"

python params in antrl

const path = require('path')

// Function to parse Python code
async function pythonParams(pythonCode) {
  const getParser = await importer.import("get antrl tool")
  const { antlr4, parser: Python3Parser, lexer: Python3Lexer, listener: Python3Listener } = await getParser('Python3')


  class ParameterListener extends Python3Listener {
    constructor() {
      super();
      this.parameters = [];
    }
  
    enterFuncdef(ctx) {
      let funcName = ctx.children[1].getText();  // Function name
      let paramCtx = ctx.children[2]; // Parameters
  
      if (paramCtx && paramCtx.children.length > 1) {
        let params = paramCtx.getText()
          .replace(/[()]/g, '')  // Remove brackets
          .split(',')
          .map(param => param.trim());
  
        this.parameters.push({ function: funcName, parameters: params });
      }
    }
  }
  

  
  const chars = new antlr4.InputStream(pythonCode);
  const lexer = new Python3Lexer(chars);
  const tokens = new antlr4.CommonTokenStream(lexer);
  const parser = new Python3Parser(tokens);

  parser.buildParseTrees = true;
  const tree = parser.file_input();

  let listener = new ParameterListener();
  antlr4.tree.ParseTreeWalker.DEFAULT.walk(listener, tree);

  if(pythonCode.match('__all__ = ' + listener.parameters[0].function)) {
    return listener.parameters[0]
  }

  return listener.parameters;
}

module.exports = pythonParams

What the code could have been:

/**
 * Module dependencies.
 */
const path = require('path');
const antlr4 = require('antlr4');

/**
 * Function to parse Python code.
 * 
 * @param {string} pythonCode - The Python code to be parsed.
 * @returns {Promise>} A promise resolving to an array of function parameter objects.
 */
async function pythonParams(pythonCode) {
  // Get the ANTLR parser generator for Python3
  const { Grammar } = await import('antlr4/Java/ANTLRv4Parser');
  const python3Grammar = require('./Python3.g4'); // Assuming the grammar file is in the same directory

  // Create a Python3 lexer and parser
  const python3Lexer = new antlr4.Lexer(new antlr4.InputStream(pythonCode), new python3Grammar.Lexer());
  const python3Parser = new antlr4.Parser(new antlr4.InputStream(pythonCode), new python3Grammar.Parser());

  // Define a custom listener to extract function parameters
  class ParameterListener extends antlr4.tree.ParseTreeListener {
    constructor() {
      super();
      this.parameters = [];
    }

    enterFuncdef(ctx) {
      // Extract the function name and parameters
      const funcName = ctx.children[1].getText();
      const paramCtx = ctx.children[2];

      if (paramCtx && paramCtx.children.length > 1) {
        const params = paramCtx.getText()
         .replace(/[()]/g, '')  // Remove brackets
         .split(',')
         .map(param => param.trim());

        this.parameters.push({ function: funcName, parameters: params });
      }
    }
  }

  // Create an instance of the custom listener
  const listener = new ParameterListener();

  // Parse the Python code
  const tree = python3Parser.file_input();

  // Walk the parse tree with the listener
  antlr4.tree.ParseTreeWalker.DEFAULT.walk(listener, tree);

  // Filter the result to only include the function with the matching name
  const mainFunc = listener.parameters.find(param => param.function === '__all__ = ');

  return mainFunc || listener.parameters;
}

module.exports = pythonParams;

Code Breakdown

Purpose

This code is a Node.js module that provides a function to parse Python code and extract function parameters.

Dependencies

Function: pythonParams

ANTLR4 Tool Integration

ParameterListener Class

Main Logic

Export

Example Usage

const pythonParams = require('./pythonParams');
const pythonCode = 'def my_function(a, b): pass';
const result = pythonParams(pythonCode);
console.log(result); // [{ function:'my_function', parameters: ['a', 'b'] }]