Why does Resharper think that these enums are never used? - combobox

I have these enums:
private enum FontSizeType
{
XSmall, //9
Small, //12
Medium, //18
Large, //24
XLarge, //36
XXLarge //47
}
private enum AlignOptions
{
Left,
Center,
Right
}
private enum ValueType
{
Text,
Barcode
}
And Resharper's inspection tells me about all of them that "Enum member 'XSmall' [etc.] is never used"
Yet I am using them in my combo boxes, like so:
comboBoxType1.DataSource = Enum.GetNames(typeof(ValueType));
...so why is Resharper fooled? Or is it?

ReSharper doesn't detect implicit usages. You can use [UsedImplicitly] to tell it that your type member is used implicitly, and then it should stop complaining.
In order to use UsedImplicitlyAttribute in your code, you should either include reference to JetBrains.Annotations.dll or include some copy-pasted source code in your project, see http://www.jetbrains.com/resharper/webhelp/Code_Analysis__Annotations_in_Source_Code.html for details.
You should add [UsedImplicitly] on each enum value.

You can as well disable the complaints itself by using this directive:
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public enum ComplianceStatus
{
Notcompliant,
Unknown,
Warning,
Compliant,
Pendingrestart,
Pendinglogoff
}

Related

C++11, wrapper class for handling different versions of C struct versions

EDIT:
I think the version is known at run-time instead of compile-time so I'm not able to add it as a compile option to the gcc cmd. Which is why I have to support both versions based on whatever version the hardware reports back.
So I'm dealing with firmware where I am required to support multiple definitions for versions of the same C struct. We created our own header file as defined by the interface documentation of a memory controller based on the vendor's C struct definition.
// For simplicity lets pretend that this is the struct for version 1
typedef struct __attribute__((packed)) ver1 {
int x;
int y;
} ver1;
I also have an existing API that uses this interface already that needs to be replaced by some sort of class wrapper (I believe), or a wrapper that plays well with the existing API.
void function_call(ver1 v1);
Only one instance (ver 1 or ver 2) of the struct can exist at any time
ver 1 for a certain fw version, and ver 2 after a certain fw version
ver2 is my extended version of ver1, I am naming it as ver2 for the hope of using some sort of factory to select the right C-style struct.
typedef struct __attribute__((packed)) ver2 {
int x;
int y;
int w; // new
int z; // new
} ver2;
Before creating a ver 2 I was looking into options such as the decorator or adaptor design pattern I could try a fancy CRTP template style I found on Hands-On Design Patterns but for simplicity, I'll illustrate with this scheme where I could possibly "add-on" to ver1:
struct ver2 : public ver1 {
int w;
int z;
}
But then I learned that C++ doesn't guarantee the same class layout
C struct Inheritance vs C++ POD struct Inheritance
and potential alignment issues (I'm not too familiar with it) so I don't think it is a real option for me to use.
I found this example on stackoverflow but I don't like the idea of adding include headers in the struct How to handle conflicting struct definitions in a C application.
There is a similar example here using a similar base class
C++ design for multiple versions of same interface (enumerations / structures in header files) which I don't think I can even use due to inheritance impact on the class layout.
Unless there is a valid reason to use the techniques of the links above, I was considering a wrapper class that returns the right version based on a selector. First I'll define a free function to leverage this.
int get_fw_version(int target);
I'm working on C++11 so I'm limited on auto return type deduction and below is just some draft code I'm trying to think up, not complete, doesn't compile, just illustrating my thought process. I haven't considered composition yet since IDK how that will quite work. Looking for ideas.
int main() {
// Roughly how I would like to use it...
const int fw_ver = get_fw_version(target);
auto ver_inst = ver_factory(fw_ver);
function_call( ver_inst.get_data() );
return 0;
}
I am not sure if I can do this without polymorphism where the base class gets ver1 and but the derived class has ver2.
Rough idea where I am at, I tried doing CRTP but I hit the problem that the base class needs to be a template and I can't use a heterogeneous base type (e.g. shared_ptr). Trying the non-CRTP way IDK how to set up the abstract base class with the get_data() method. Without the compiler complains saying that the base doesn't have a get_data method, which, makes sense
// I can't figure out how to add T get_data() here without adding a template param. This base function is really to delegate common member methods and trying to keep a common base for polymorphism.
class base {
virtual ~base() = 0;
// ?? get_data() = 0 or some other method
};
class ver1_derived : public base
{
ver1 data;
public:
ver1_derived() = default;
ver1 get_data() {
return data;
}
};
class ver2_derived : public base
{
ver2 data;
public:
ver2_derived() = default;
ver2 get_data() {
return data;
}
};
// should be using unique_ptr but I can't at work....
shared_ptr<base> ver_factory(const int fw_ver) {
if(fw_ver <= 1)
return make_shared<ver1_derived>();
return make_shared<ver2_derived>();
}
I ended up giving up on an inheritance schemed and ended up taking two different code paths based on the template type.
So
if(fw_ver <= 1)
function_call<ver1>();
} else {
function_call<ver2>();
}

Achieving Object-Oriented Design in the C Language by using proper function names

I am writing a MISRA compliant code that runs on a microcontroller, and this program must be written in the C language.
I would like to design my software according to the object-oriented design. However, the C-language lacks OOP support.
Therefore, I decided to create "classes" and "packages" through C-files and Folders, respectively.
Currently, all legacy function names were having the following names: <Module_Name>_f_<Function_Name>_<Return type>.
This function naming convention works as long as there is only a single Module. However, if I add SubModules or even SubSubModules, then the function name might get confusing.
For example, having Module, Submodule, and a SubSubModule might end up in one the following function names:
<Module_Name><SubModule_Name><SubSubModule_Name>_f_<Function_Name>_<Return type>
<Module_Name>_<SubModule_Name>_<SubSubModule_Name>_f_<Function_Name>_<Return type>
<Module_Name>_f_<SubModule_Name>_<SubSubModule_Name>_<Function_Name>_<Return type>
...
What would be a good name for such functions, and their respective C-files? I would like to have a naming convention that one can read and still understand the "class"/"package" structure?
To make it more clear, we can take more concrete example with the following file structure containing Folders and C-files:
Module (Folder)
- SubModule_1 (Folder)
- SubSubModule_1_1.c
- SubSubModule_1_2.c
- SubSubSubModule_1_2_1.c (Maybe also put in a seperate Sub-Folder?)
- SubSubSubModule_1_2_2.c (Maybe also put in a seperate Sub-Folder?)
...
- SubModule_n (Folder)
- SubSubModule_n_1.c
- SubSubModule_n_2.c
...
The above file structure might look like this in an OOP pseudocode:
class Module:
begin Module;
# Field Declarations
SubModule_1 subModule_1_Instance;
SubModule_2 subModule_2_Instance;
...
# Function declarations
Module_f_<Function_Name>_<return type>;
...
end Module;
class SubModule_1:
begin SubModule_1;
# Field Declarations
SubSubModule_1_1 subSubModule_1_1_Instance;
SubSubModule_1_2 subSubModule_1_2_Instance;
...
# Function declarations
ModuleSubModule1_f_<Function_Name>_<return type>;
OR
Module_SubModule1_f_<Function_Name>_<return type>;
OR
Module_f_SubModule1_f_<Function_Name>_<return type>;
...
end SubModule_1;
class SubSubModule_1_1:
begin SubSubModule_1_1;
# Function declarations
ModuleSubModule1SubModuleSubModule11_f_<Function_Name>_<return type>;
OR
Module_SubModule1_SubModule11_f_<Function_Name>_<return type>;
OR
Module_f_SubModule1_SubModule11__f_<Function_Name>_<return type>;
...
end SubSubModule_1_1;
So for the SubSubModule_1_1, I might end up with:
ModuleSubModule1SubModuleSubModule11_f_<Function_Name>_<return type>;
Module_SubModule1_SubModule11_f_<Function_Name>_<return type>;
Module_f_SubModule1_SubModule11__f_<Function_Name>_<return type>;
Is there maybe a better way to name those functions? I am looking forward to Your replays/alternatives.
Thank you in advance.
Sticking to an OO design is almost always a good idea, but you need to boil down OO to the things that matter. Namely:
Autonomous objects that only know of their designated purpose and know nothing about unrelated things.
For example in an embedded system, your SPI driver shouldn't and needn't know anything about the LCD you are using, even though you are communicating with the LCD through SPI.
Private encapsulation that hides information away to reduce complexity, tight coupling and namespace collisions.
In some cases, inheritance.
For example if you are writing a portable HAL that should function the same no matter the underlying microcontroller hardware. (Like for example a SPI driver.)
All of the above OO can be achieved in C and the language directly or indirectly has language support for it. There's misc other concepts like "RAII", which are handy but not necessary. Unfortunately we can't get automatically called constructors/destructors in C, so we have to live with calling them explicitly.
The main thing to concider when doing OO in C (and other languages) is to do it on a file level. The header file should contain the public interface - everything that the caller needs to know, that you would normally have declared public in a language with keyword support. Each header file contains a corresponding .c file containing the private implementation details.
It's a good idea to have a strict naming policy like in your examples, so that the caller knows where a certain function belongs. The functions belonging to the SPI driver spi.h should be named spi_init, spi_transceive and so on, with the source code prefix first.
Not sure if I like the SubSubModule idea though, seems a bit burdensome. Also, in an embedded system there should be just so many cases where you actually need inheritance, it is a bit of a rare beast rather than the main attraction in most programs. Often it can rather be a sign of poor design and over-engineering with far too many abstraction layers. It's also important to never let your inheritance API be set in stone. Don't hesitate to change it later on, when you discover new requirements that weren't considered during the initial design.
Regarding private encapsulation, C supports that through the static keyword. Functions declared static in the .c file are truly private and can't be accessed from other files. It doesn't work quite as well for variables though. You can use static file scope variables as a "poor man's private", that's in fact how it is done most of the time in embedded systems. static variables have some limitations though: they force the object to become a "singleton pattern" with only one instance possible. Which is fine if you only need one instance of the SPI driver, but what if the MCU comes with 5 different SPI peripherals, all behaving identically?
As a side note, static variables aren't thread-safe in larger, multi-process/multi-thread programs. Could become relevant in case of RTOS.
It is however possible to take OO one step further in C, by using the concept known as opaque type / opaque pointers. Examples. This allows you to create multi-instance classes, fully encapsulated, or optionally with some public parts. It can be used to model inheritance and polymorphism, by letting the first object of the inherited class contain a struct instance of its parent. Function pointers enable "virtual" inherited functions, where calling a function through a base class pointer invokes the corresponding function in the caller.
An object declared as opaque through pointers to incomplete type cannot be allocated by the caller, they can only declare pointers to them. From the caller's perspective they work essentially just the same as abstract base classes in C++. You will have to encapsulate the object allocation inside the init function (constructor). This is a bit of a disadvantage in low-end embedded systems, since sanity demands that we don't use malloc there. Instead memory allocation will have to be done through a fixed maximum size static memory pool. Examples: Static allocation of opaque data types
From a MISRA-C perspective, they actually encourage the use of opaque type since MISRA-C:2012 (Dir 4.8).
Do not over-use opaque type though. It makes perfect sense for things like HAL on top of drivers, portable code, protocol handling etc. But not so much for hiding away non-portable, application-specific logic, which doesn't benefit from abstraction layers since you won't be able to re-use or port it anyway.
Overall, program design is highly qualified work. It takes lots of experience to get it done properly. Add too much abstraction and you end up in over-engineered, meta-programming hell. Add too little and you end up in spaghetti-programming, tight-coupling hell.
The concept missing from this discussion is the "this" pointer to have instance-specific data.
It's implicit in C++, but must be explicit in C.
For example, in a hypothetical module NSMotionController.c:
typedef struct NSMotionControllerStruct {
float speed__m_s;
} NSMotionController_t;
float NSMotionController_SpeedGet__m_s(NSMotionController_t const * const this) {
return this->speed__m_s;
}
bool NSMotionController_Initialize(NSMotionController_t * const this, float const speedCurrent__m_s) {
this->speed__m_s = speedCurrent__m_s;
return true;
}
We can use this like so:
int main(int argc, char ** argv) {
NSMotionController_t motionControllerInstance1;
NSMotionController_Initialize(motionControllerInstance1, 1.0f);
NSMotionController_t motionControllerInstance2;
NSMotionController_Initialize(motionControllerInstance1, 2.0f);
printf("speed1: %.1f\n", NSMotionController_SpeedGet__m_s(&motionControllerInstance1));
printf("speed2: %.1f\n", NSMotionController_SpeedGet__m_s(&motionControllerInstance2));
}
As far as naming, I use a two-letter namespace ("NS" above) since C doesn't support namespaces idiomatically.
I use the module name, then an underscore to start the method name.
I use two underscores to separate a units suffix ("__m_s" above indicates "meters per second").
For polymorphism, you can use function pointers. So, augmenting our example with function pointers:
typedef float (*NSMotionControllerInterface_SpeedGet__m_s_t)(void const * const this);
typedef struct NSMotionControllerStruct {
NSMotionControllerInterface_SpeedGet__m_s_t SpeedGet__m_s;
float speed__m_s;
} NSMotionController_t;
float NSMotionController_SpeedGet__m_s(void const * const this) {
NSMotionController_t const * const motionThis = (NSMotionController_t const *) this;
return motionThis->speed__m_s;
}
bool NSMotionController_Initialize(NSMotionController_t * const this, float const speedCurrent__m_s) {
this->SpeedGet__m_s = NSMotionController_SpeedGet__m_s;
this->speed__m_s = speedCurrent__m_s;
return true;
}
int main(int argc, char ** argv) {
NSMotionController_t motionControllerInstance1;
NSMotionController_Initialize(motionControllerInstance1, 1.0f);
NSMotionController_t motionControllerInstance2;
NSMotionController_Initialize(motionControllerInstance1, 2.0f);
printf("speed1: %.1f\n", motionControllerInstance1.SpeedGet__m_s(&motionControllerInstance1));
printf("speed2: %.1f\n", motionControllerInstance2.SpeedGet__m_s(&motionControllerInstance2));
}
Rather than using polymorphism on a single function, though, you can gather them up in a struct and pass that to other modules.
typedef float (*NSMotionControllerInterface_SpeedGet__m_s_t)(void const * const this);
typedef bool (*NSMotionControllerInterface_SpeedSet__m_s_t)(void const * const this, float const speedNew__m_s);
typedef struct NSMotionControllerInterfaceStruct {
NSMotionControllerInterface_SpeedGet__m_s_t SpeedGet__m_s;
NSMotionControllerInterface_SpeedSet__m_s_t SpeedSet__m_s;
} NSMotionControllerInterface_t;
typedef struct NSMotionControllerStruct {
NSMotionControllerInterface_t interface;
float speed__m_s;
} NSMotionController_t;
float NSMotionController_SpeedGet__m_s(void const * const this) {
NSMotionController_t const * const motionThis = (NSMotionController_t const *) this;
return motionThis->speed__m_s;
}
bool NSMotionController_SpeedSet__m_s(void const * const this, float const speedNew__m_s) {
NSMotionController_t const * const motionThis = (NSMotionController_t const *) this;
motionThis->speed__m_s = speedNew__m_s;
return true;
}
bool NSMotionController_Initialize(NSMotionController_t * const this, float const speedCurrent__m_s) {
this->interface.SpeedGet__m_s = NSMotionController_SpeedGet__m_s;
this->interface.SpeedSet__m_s = NSMotionController_SpeedSet__m_s;
this->speed__m_s = speedCurrent__m_s;
return true;
}
int main(int argc, char ** argv) {
NSMotionController_t motionControllerInstance1;
NSMotionController_Initialize(motionControllerInstance1, 1.0f);
NSMotionController_t motionControllerInstance2;
NSMotionController_Initialize(motionControllerInstance1, 2.0f);
NSMotionControllerInterface_t * const interface1 = motionControllerInstance1.interface;
NSMotionControllerInterface_t * const interface2 = motionControllerInstance2.interface;
printf("speed1: %.1f\n", interface1->SpeedGet__m_s(&interface1));
printf("speed2: %.1f\n", interface2->SpeedGet__m_s(&interface2));
interface1->SpeedSet__m_s(&interface1, 5.0f);
printf("speed1 (faster): %.1f\n", interface1->SpeedGet__m_s(&interface1));
/* Example of passing abstract interface */
NSGroundControl_t groundControl;
NSGroundControl_Initialize(&groundControl, interface1);
}
In short, never use statics when you can avoid it. This will also help unit testing, which I imagine is next (or hopefully first) if you're working in a MISRA environment.

Compile-time check struct with function pointers to validate assignments

I'm wondering if the following is possible:
I have a namespace-style struct setup, filled with just function pointers. These are provided in the header file like so:
typedef struct {
int32_t(*const event_construct)(struct sync_event* evt);
int32_t(*const event_destroy)(struct sync_event* evt);
int32_t(*const event_set)(struct sync_event* evt);
int32_t(*const event_wait)(struct sync_event* evt);
} namespace_sync;
extern namespace_sync const sync;
and then in the relevant source file, after all the function implementations:
...
namespace_sync const sync = {
sync_event_construct,
sync_event_destroy,
sync_event_set,
sync_event_wait
};
Say I want to add an extra function not at the end; I add it to the struct and source file, but forget to assign it. Because the function declarations match, a warning isn't generated for it, and the compiler (at least in this example, vs2013) doesn't provide a hint that there's an issue.
I've got compile-time assertion checks available, but not sure if I can verify this particular aspect, since the struct size is accurate. If vs2013 can't work with it - I'm aware it's an abysmal C compiler(!) - the newest versions of gcc will also be used, so I could limit the functionality to one compiler.
One solution going forward would be to use designated initializers:
namespace_sync const sync = {
.event_construct = sync_event_construct,
.event_destroy = sync_event_destroy,
.event_set = sync_event_set,
.event_wait = sync_event_wait
};
Any unlisted members will default to null pointers.
I would advise to not add members into the middle of a struct, because it is difficult to be sure that you have correctly updated any code that was relying on the old struct layout. However, if you really do want to do this, then one way to have the compiler indicate to you where all the uses of the struct are is to change the struct name:
typedef struct {
// ...
} namespace_sync_2;
Then the code namespace_sync const sync will cause a compilation error. This alerts you to the fact that this piece of code requires a code review to make sure that it will work correctly with the new struct layout.

Porting InterlockedExchange, using GCC intrinsics only

Windows API offers InterlockedExchange, which sets a value in memory atomically. Using only GCC intrinsics, I’d like to create an equivalent of that function. Would setting the value and then calling a memory barrier be sufficient (see the code below) ?
template <typename T>
T InterlockedExchange(volatile T& _data, T _value)
{
const T oldValue = _data;
_data = _value;
__sync_synchronize();
return oldValue;
}
Thank you.
EDIT: The proposed snippet is NOT a correct solution to the problem, as it is clearly not atomic (but, well, I had to give a try at least).
Use __sync_val_compare_and_swap __sync_lock_test_and_set, not __sync_synchronize.
This has exactly the same function as InterlockedExchange.
Something like this (untested code!):
template<typename T> T InterlockedExchange(T& data, T& new_val)
{
return __sync_lock_test_and_set(&data, new_val);
}
EDIT:
Oi, I read wrong, you wanted InterlockedExchange, not InterlockedCompareExchange ... so that is __sync_lock_test_and_set (the name is a misleading Intel-nomer, but it's exactly what you want).
See here, bottom of the page.
Your proposed example is not equivalent, because it is not atomic. Two racing threads executing your function can both retrieve the same old value, with one of the new values being "lost".

Force compile error if function argument out of range

I am restricted to C (cannot use C++). I wish C had stricter type checking.
Is there a way to get compile errors on the commented lines? If it helps, the enum values cannot overlap.
enum hundred {
VALUE_HUNDRED_A = 100,
VALUE_HUNDRED_B
};
enum thousand {
VALUE_THOUSAND_A = 1000,
VALUE_THOUSAND_B
};
void print_hundred(enum hundred foo)
{
switch (foo) {
case VALUE_HUNDRED_A: printf("hundred:a\n"); break;
case VALUE_HUNDRED_B: printf("hundred:b\n"); break;
default: printf("hundred:error(%d)\n", foo); break;
}
}
void print_thousand(enum thousand bar)
{
switch (bar) {
case VALUE_THOUSAND_A: printf("thousand:a\n"); break;
case VALUE_THOUSAND_B: printf("thousand:b\n"); break;
default: printf("thousand:error(%d)\n", bar); break;
}
}
int main(void)
{
print_hundred(VALUE_HUNDRED_A);
print_hundred(VALUE_THOUSAND_A); /* Want a compile error here */
print_thousand(VALUE_THOUSAND_A);
print_thousand(VALUE_HUNDRED_A); /* Want a compile error here */
return 0;
}
In C, enum types are indistinguishable from integers. Very annoying.
The only way forward I can think of is a kludgy workaround using structs instead of enums. Structs are generative, so the hundreds and thousands are distinct. If the calling convention is sensible (AMD64) there will be no run-time overhead.
Here's an example using structs that gets the compile-time errors you wanted. Kludgy, but it works:
#include <stdio.h>
enum hundred_e {
VALUE_HUNDRED_A = 100,
VALUE_HUNDRED_B
};
enum thousand_e {
VALUE_THOUSAND_A = 1000,
VALUE_THOUSAND_B
};
struct hundred { enum hundred_e n; };
struct thousand { enum thousand_e n; };
const struct hundred struct_hundred_a = { VALUE_HUNDRED_A };
const struct hundred struct_hundred_b = { VALUE_HUNDRED_B };
const struct thousand struct_thousand_a = { VALUE_THOUSAND_A };
const struct thousand struct_thousand_b = { VALUE_THOUSAND_B };
void print_hundred(struct hundred foo)
{
switch (foo.n) {
case VALUE_HUNDRED_A: printf("hundred:a\n"); break;
case VALUE_HUNDRED_B: printf("hundred:b\n"); break;
default: printf("hundred:error(%d)\n", foo.n); break;
}
}
void print_thousand(struct thousand bar)
{
switch (bar.n) {
case VALUE_THOUSAND_A: printf("thousand:a\n"); break;
case VALUE_THOUSAND_B: printf("thousand:b\n"); break;
default: printf("thousand:error(%d)\n", bar.n); break;
}
}
int main(void)
{
print_hundred(struct_hundred_a);
print_hundred(struct_thousand_a); /* Want a compile error here */
print_thousand(struct_thousand_a);
print_thousand(struct_hundred_a); /* Want a compile error here */
return 0;
}
You can't do it. In C++ you could overload the function and do some trickery (or use boost::enable_if), or just rely on C++'s type safety making it error out automatically. In C, that doesn't work since function overloading is not supported. And you can't check the value in the function and cause a compile time error, since all values are known only at runtime (as opposed to types).
The C Standard allows compilers to warn about what you do. So you could enable the -Wall -Werror flag and hope gcc will error out. But this is not a general purpose C way.
I think strictly the answer is, "it depends on the compiler". I'm fairly sure that the code is legal C, so by default a C compiler wouldn't/shouldn't complain, but there are probably different options in different compilers that can pick it up.
If this type of error checking is important to you then I suggest investigating C linters/style checkers/static analysis tools which will catch this and other common (and not so common) errors (if you set them up correctly!). It is a bit of work to add these tools into your build process, but if for your project you think catching these kind of things at compile is valuable then the cost is going to be worth it.
Two I would recommend are:
FlexeLint, which is a relatively inexpensive commercial product that I have used to great effect.
An open source alternative would be Splint, but unfortunately it appears to be mostly unmaintained at the moment.
There are more expensive commercial tools such as Klocwork and Coverity.
Adding these kind of tools to your software does take some effort. They are usually extremely flexible and customisable, and you need to make some educated decisions about what behaviours you want to allow, and which you want to disallow in your code base.
You could do it using #defines for your functions and __builtin_constant(x), which returns 1 if x resolves to a constant and 0 if it does not. Note this is a gcc-only intrinsic; I have no idea if there are equivalents on other compilers.
I would argue that the problem isn't as much that C doesn't support strict type checking, as it's that it really doesn't support true user-defined types.
My guess is that most C compilers would translate both of your enums into simple ints or shorts or whatever, and would not do anything beyond that.
So as far as I can tell, the answer would be know.
There's no way C alone can do it because the compiler doesn't know anything except the base types. The usual thing is to use the assert() macro, but that's a run-time check.

Resources