Include header file in abstract syntax tree CDT - c

Problem: I want generate function prototype if it doesn't exists, in the C file, I have done this, but in case if the prototype already exists in a header file it doesn't feel it, BTW I used CDT IIndex
//C Code
#include "test.h" //where it have bar prototype
void bar(void)
{
//function body
}
//Obtaining the AST [JAVA CDT CHECKER]
ITranslationUnit tu = (ITranslationUnit) CDTUITools.getEditorInputCElement(editor.getEditorInput());
String cFilePath = tu.getResource().getFullPath().toString();
ICProject[] allProjects = CoreModel.getDefault().getCModel().getCProjects();
IIndex **index** = CCorePlugin.getIndexManager().getIndex(allProjects);
IASTTranslationUnit ast = null;
try {
index.acquireReadLock(); // we need a read-lock on the index
ast = tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
} finally {
index.releaseReadLock();
ast = null; // don't use the ast after releasing the read-lock
}
//In the AST visitor class
/**
* extract prototype and store them into 'prototypes' hash set and then rewrite the AST.
*/
#Override
protected int visit(IASTSimpleDeclaration simpleDeclaration) {
IASTDeclarator[] declarators = simpleDeclaration.getDeclarators();
boolean isProtoFuncDeclaration = false;
for (IASTDeclarator declarator: declarators) {
if( declarator instanceof IASTFunctionDeclarator)
{
isProtoFuncDeclaration = true;
}
}
if(isProtoFuncDeclaration)
{
prototypes.add(simpleDeclaration);
}
return super.visit(simpleDeclaration);
}
The output of the new C Code
#include "test.h" //where it have bar prototype
void bar(void) <=== I shouldn't be inserted as it is already in the header
void bar(void)
{
//function body
}

I would suggest the following:
Traverse the AST to find the IASTFunctionDefinition for which you maybe want to add a prototype.
Use getDeclarator().getName() to get the function name,
Use IASTName.resolveBinding() to get the function binding.
Use IIndex.findDeclarations(IBinding) to find all declarations and definitions of the function.
From the resulting IIndexName[], filter out the definition itself (check IName.isDefinition()).
Further filter the list to declarations that appear in included header files (since findDeclarations() will return declarations in the entire project). You can do this by calling IASTTranslationUnit.getIndexFileSet() on your AST, and checking IIndexFileSet.contains(name.getFile()) for every IIndexName.
If after this filtering, the list is empty, you know you need to add a prototype.

Related

how to detect what struct a function is being called from

The title is confusing, i tried my best to explain it in a few words but i failed. Here is a better explenation of my problem.
Lets say there's a struct named Object with a bool variable named _active and a function named SetActive().
typedef struct Object
{
bool _active;
void (*SetActive)(bool)
} Object;
Object someObject;
Object someOtherObject;
void SetActive(bool set)
{
/*
if function is being called from someObject, then
someObject._active = set
if function is being called from someOtherObject, then
someOtherObject._active = set
*/
}
(This is an example)
I want SetActive() to set _active of the struct its being called from to set
For example when i call structname.SetActive(true), structname._active = true
How do i do something like this?
void (*SetActive)(bool); is a pointer to a free function. It has no association with any particular object.
In C it's pretty common to supply the object as the first or last argument to the functions acting as member functions. This is needed because C doesn't have actual member functions. To make the association clear to other programmers reading the code, you can prepend all acting "member functions" with the name of the type each function acts upon.
It could look like this:
#include <stdbool.h>
#include <stdlib.h>
typedef struct Object Object;
struct Object {
bool _active;
};
Object *Object_create() {
Object *obj = malloc(sizeof *obj);
if(obj) {
// provide some default init values
*obj = (Object){ ._active = false };
}
return obj;
}
void Object_destroy(Object *obj) {
free(obj);
}
void Object_SetActive(Object *obj, bool set) {
obj->_active = set;
}
int main(void) {
Object *obj = Object_create();
Object_SetActive(obj, true);
Object_destroy(obj);
}
If you really really want to have a poor man OOP, you can do it. But why not switching to a more friendly language?
Basically you would include a function pointer in a struct, iif you plan to override that function in a subclass. This is needed only for polymorphism. In that case you will probably need also a polymorphic destructor for your class.
The problem is that you get pointers to these polymorphic functions in every instance of your objects, so better alternatives are required (vtables, pointer to class CPython style, ...).
The bad news is that now you need to specify the object to access the function pointer and to pass it to the function itself. Which really requires some syntax sugar.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct Object Object;
struct Object {
bool active_;
void (*SetActive)(Object *this, bool status); // This is a virtual method
void (*Destruct)(Object *this); // You will need this for polymorphism
};
void Object_SetActive(Object *this, bool status);
void Object_Destructor(Object *this);
void Object_Constructor(Object *this) { // Default constructor
this->active_ = false;
this->SetActive = Object_SetActive;
this->Destruct = Object_Destructor;
}
void Object_Destructor(Object *this) {
// Nothing to be done here, but maybe when subclassing?
}
void Object_SetActive(Object *this, bool status) {
this->active_ = status;
}
int main(void)
{
Object someObject;
Object_Constructor(&someObject);
Object someOtherObject;
Object_Constructor(&someOtherObject);
someObject.SetActive(&someObject, true);
someOtherObject.SetActive(&someOtherObject, false);
printf("someObject.active_ = %s\n", someObject.active_ ? "true" : "false");
printf("someOtherObject.active_ = %s\n", someOtherObject.active_ ? "true" : "false");
someObject.Destruct(&someObject);
someOtherObject.Destruct(&someOtherObject);
return 0;
}
If you want to waste some time with OOP in C, with macro abuse, you can read this post.
Warning: I don't want to be held responsible for nausea or vomiting caused by reading that post.
With respect to Ted Lyngmo's answer, I'm constructing and destructing already allocated objects. This would need also some new and delete clones.

How do I avoid circular dependancy coding UNDO/REDO in C?

//I'm moving this note to the top: I'm recreating OOP with structs and associated methods like int MyClass_getInt(MyClass* this)
I'm coding a small DAW in C. I have my Timeline and Region classes in Timeline.h. I would like my UndoRedoStack class to be able to work with multiple Timeline instances so I'd like the UndoRedoStack to be in a separate .c/.h file.
This line of thinking seems to require the TimelineUndoRedoCommand class to know about Timelines and Regions because it needs to backup pre-existing states.
It also requires Timelines to know about TimelineUndoRedoCommands so that it can fire them into the UndoRedoStack.
This seems to be a circular dependency. How should I structure this so that I can avoid circular dependencies?
//
I ended up asking Timeline.h to write all the code that needs it but house the UndoRedo separately like so:
/*
UndoRedoCmd
*/
typedef struct _UndoRedoCmd{
void* content;
char* name;
}UndoRedoCmd;
/*
UndoRedoStack
*/
typedef struct _UndoRedoStack{
t_LinkList* undoStack;
t_LinkList* redoStack;
bool redoingNow;
void (*redoFunc)(UndoRedoCmd* redoThis);
void (*undoFunc)(UndoRedoCmd* undoThis);
}UndoRedoStack;
/*
UndoRedoCmd
*/
UndoRedoCmd* UndoRedoCmd_New(char* name, void* content){
UndoRedoCmd* this = malloc(sizeof(UndoRedoCmd));
this->name=name;
this->content=content;
return this;
}
void UndoRedoCmd_Kill(UndoRedoCmd* this){
/*this should never be used. instead the
user of UndoRedoStack should provide
a custom killer which simply calls
free after freeing the contents
*/
}
/*
UndoRedoStack
*/
UndoRedoStack* UndoRedoStack_New(
void (*redoFunc)(UndoRedoCmd*),
void (*undoFunc)(UndoRedoCmd*),
void (*freeLinkFunction)(void*)
){
/*
redoFunc is meant to take the content of the command and redo some action with it.
undoFunc is the opposite
freeLinkFunction is meant should free a LinkList_Link with the custom UndoRedo content inside of it.
*/
UndoRedoStack* this = malloc(sizeof(UndoRedoStack));
this->undoFunc=undoFunc;
this->redoFunc=redoFunc;
this->redoStack = LinkList_New();
this->redoStack->autoFree=2;
this->redoStack->customFree=freeLinkFunction;
this->undoStack = LinkList_New();
this->undoStack->autoFree=2;
this->undoStack->customFree=freeLinkFunction;
return this;
}
void UndoRedoStack_Kill(UndoRedoStack* this){
LinkList_Free(this->undoStack);
LinkList_Free(this->redoStack);
free(this);
}
void UndoRedoStack_do(UndoRedoStack* this,char* name,void* undoredoinfo){
UndoRedoCmd* mycmd = UndoRedoCmd_New(name, undoredoinfo);
LinkList_push(this->undoStack, mycmd);
}
void UndoRedoStack_undo(UndoRedoStack* this){
if(this->undoStack->length==0){
return;
}
UndoRedoCmd* undoMe = (UndoRedoCmd*)LinkList_pop(this->undoStack);
this->undoFunc(undoMe);
LinkList_push(this->redoStack, undoMe);
}
void UndoRedoStack_redo(UndoRedoStack* this){
if(this->redoStack->length==0){
return;
}
UndoRedoCmd* redoMe = (UndoRedoCmd*)LinkList_pop(this->redoStack);
this->redoFunc(redoMe);
LinkList_push(this->undoStack, redoMe);
}

Function mocking in C?

I'm writing a unit-test to check some API calls. I am using check to test. My module is build with CMake (idk if it matters).
My test calls a function (which I need to test) and this function makes a call to another binary.
Simplified version of it looks like this.
/* unitTest.c */
#include "libraryAPI.h"
void letsMakeACall(void)
{
ck_assert_eq(foo("water"), 0);
}
-- Module I am working on---
/*libraryAPI.c*/
#include "legacyLib.h"
void foo(const char *drink )
{
if (checkDrink(drink)!=0)
{
return 1;
}else
{
return 0;
}
}
----LEGACY BINARY---
/*legacyLib.c*/
static const char* expected = "water";
void checkDrink(const char *drink)
{
if(drink == expected)
{
/*There are also a dozen functions being called which depend on legacy module initialisation*/
return 0;
}else{
return 1;
}
}
I'd like to mock response from legacyLib, because otherwise it call dozens of functions and breaks. My initial idea was to add some ifdef conditions when tests are being run, but it is against guidelines.
Because it is basically a call interception I don't know what it a best(or working) solution. What can I use to solve it?
I am also unsure how to solve this generally, I have posted a similar question, but in some cases you can do the following (presuming you are testing individual functions):
Include the .c file instead of the header .h, but after you "rename" your mocked function using a define directive:
#define checkDrink checkDrink_mocked
// preprocessor will now replace all occurrences of "checkDrink"
// with "checkDrink_mocked"
int checkDrink_mocked(const char *drink);
#include "legacyLib.c"
#undef checkDrink
Implement the renamed function:
int checkDrink_mocked(const char *drink)
{
return 15;
}

object oriented approach in c program

I don't have much experience in Object oriented programming.I am trying to create an object in c which will have its own methods.
I have declared structure which have pointers to function. All instance of this variable are going to point same function. But currently I need to initialize every instance of variable as in main (Line 1 and Line 2). So is there any method that will initialize its default value when I declare it?
#include <stdio.h>
#include <stdlib.h>
typedef struct serialStr Serial;
struct serialStr
{
void(*init)(Serial*);
void(*open)();
void(*close)();
};
void open()
{
printf("Open Port Success\n");
return;
}
void close()
{
printf("Close port Success\n");
return;
}
void init(Serial* ptr)
{
ptr->open = open;
ptr->close = close;
}
int main()
{
Serial serial,serial_2;
serial.init = init;
serial.init(&serial); // Line1
serial_2.init = init;
serial_2.init(&serial_2); // Line2
serial.open();
//rest of code
serial.close();
serial_2.open();
serial_2.close();
return 0;
}
In C, the standard way would be to declare an initializer macro:
#define SERIAL_INITIALIZER { .init = init, .open = open, /* and others */ }
Serial serial = SERIAL_INITIALIZER;
In most cases in C there is simply no need for dynamic intialization of variables. You only need it for malloced objects.
C++ add some automatization by calling constructor/destructor. In pure C is no way to do so. You should do all steps manually: create and initialize object (call constructor-like function for structure), call functions by pointers from the structure instance, call destructor (it should destroy the instance and free related resources).
If is no polymorphism in your task then use simple way - without pointers to functions, but each function (method) should take pointer to the object.
Common case example:
struct MyStruct
{
// data
};
struct MyStruct* createMyStruct(/* maybe some input */)
{
// create, init and return the structure instance
}
void destoyMyStruct(struct MyStruct* obj)
{
// free resources and delete the instance
}
void doSomeAction(struct MyStruct* obj /* , some other data */)
{
// ...
}
int main()
{
struct MyStruct* object = createMyStruct();
doSomeAction(object);
destoyMyStruct(object);
return 0;
}
Edit 1: macro is only for very simple cases and error-prone way.
Typically, you would do this through "opaque type". Meaning that you declare an object of incomplete type in your header:
typedef struct Serial Serial;
And then in the C file, you place the actual struct definition. This will hide the contents of the struct to the caller (private encapsulation). From your constructor, you could then set up private member functions:
struct Serial
{
void(*init)(void);
void(*open)(void);
void(*close)(void);
};
// private member functions:
static void open (void);
...
// constructor:
Serial* SerialCreate (void)
{
Serial* s = malloc(sizeof (*s));
...
s->open = open;
return s;
}
This means that if you wish to inherit the class, you will only need to change the constructor.
Though of course, if you wish to implement true polymorphism, you don't want to change any code. You could solve this by passing the init function as parameter to the constructor.
header file:
typedef void init_func_t (void);
c file:
// constructor:
Serial* SerialCreate (init_func_t* init)
{
Serial* s = malloc(sizeof (*s));
...
init();
return s;
}
And then from the init function in the inherited class, set all private member functions.

Pass delegates to external C functions in D

How do I pass a delegate to an external C function taking a function pointer, in D?
Let me cross post what I said on the newsgroup:
How do I pass a delegate to an external C function taking a
function pointer?
You can't do it directly in general, unless you can modify the C
function, then you can hack around it, but a delegate and a
regular function pointer are pretty different animals.
But perhaps you can magic hack it. Observe:
// a C function that needs a plain function
extern(C) void test(void function() f) {
// pretend this is implemented in C
f();
}
// just create a random delegate
void delegate() foo(int a) {
return { import std.stdio; writeln(a); };
}
// what we want to work
void main() {
auto dg = foo(10);
dg(); // works
//test(dg); // won't work
test(bindDelegate(dg)); // we want this
}
// transform delegate into pointer..
import std.traits;
auto bindDelegate(T, string file = __FILE__, size_t line = __LINE__)(T t) if(isDelegate!T) {
static T dg;
dg = t;
extern(C)
static ReturnType!T func(ParameterTypeTuple!T args) {
return dg(args);
}
return &func;
}
What bindDelegate does is create a special static variable and
function for that specific call. It is as if we wrote a separate
function and global to hold it.
The __FILE__, __LINE__ things are a filthy hack to make it
instantiate a separate variable+function pair for different
lines so the global variable holding the delegate won't be so
easily overwritten.

Resources