Function Repository Resource:

CodeCases

Source Notebook

Isolate code structures

Contributed by: Wolfram Research

ResourceFunction["CodeCases"][File[filename], case]

gives a list of all cases of code in filename identified as being of type case.

ResourceFunction["CodeCases"]["string", case]

gives a list of all cases of code in the program given by string identified as being of type case.

Details

The list of case types can be found in the clang documentation.
Some examples of case types include the following:
IfStmtAn if statement
WhileStmt A while statement
DoStmtA do statement
GotoStmtA goto statement
DeclStmtA declaration

Examples

Basic Examples (4) 

Isolate the if statements from a C source file:

In[1]:=
addcString = "/* add.c -- Read a sequence of positive integers and print them \n *          out together with their sum. Use a Sentinel value\n *          (say 0) to determine when the sequence has terminated.\n */\n\n#include <stdio.h>\n#define SENTINEL 0\n\nint main(void) {\n  int sum = 0; /* The sum of numbers already read */\n  int current; /* The number just read */\n\n  do {\n    printf(\"\\nEnter an integer > \");\n    scanf(\"%d\", &current);\n    if (current > SENTINEL)\n      sum = sum + current;\n  } while (current > SENTINEL);\n  printf(\"\\nThe sum is %d\\n\", sum);\n}\n";
ResourceFunction["CodeCases"][addcString, "IfStmt"]
Out[2]=

Isolate the function calls from a C source file:

In[3]:=
ResourceFunction["CodeCases"][addcString, "CallExpr"]
Out[3]=

Isolate the identifiers from a C source file:

In[4]:=
ResourceFunction["CodeCases"][addcString, "Identifier"]
Out[4]=

Isolate the declarations from a C program:

In[5]:=
ResourceFunction["CodeCases"][
 "int main(int argv, char **argv)
{
	int a;
	char b;
	char *c;
	return 0;
}", "DeclStmt"]
Out[5]=

Publisher

Christopher Cooley

Version History

  • 1.0.1 – 14 June 2021

Related Resources

License Information