how to get type from `cxxNewExpr` in `clang-tidy` - clang++

I'm trying to do a quick rewrite of our codebase to replace all instances of new T(...) with New<T>(...) (a custom function), so I can do some local measurements.
I think clang-tidy is the way to go here, so I've made a small clang tidy script, based off of this tutorial I found. The script is able to run, but not pass tests, since I do not match things correctly.
However, I'm running into problems getting the type out of the matched new expression.
What I have so far is:
class ReplaceNewAndDeleteCheck : public utils::TransformerClangTidyCheck {
public:
ReplaceNewAndDeleteCheck(StringRef Name, ClangTidyContext *Context)
: TransformerClangTidyCheck(MakeRules(), Name, Context) {}
};
Where MakeRules is defined as follows:
RewriteRuleWith<std::string> MakeRules() {
std::string s = "new";
return makeRule(
cxxNewExpr().bind(s),
changeTo(cat("New<", node(s), ">")),
cat("")
);
}
The script is able to run, but does not give the correct result. For example, with int* x = new int(10);, what I want is int* x = New<int>(10);, but what I get is int* x = New<new int(10)>;.
I know MakeRules is wrong, since I'm binding the entire new expression, not just the on the entire but I can't figure out how to either get the type and arguments out of the new expression, or to bind to those instead.

Related

How would I populate a vector with all the elements from a List of type system string while converting it to std::string?

I am trying to understand lambda functions better and would like some example of how I could add to a vector while converting System.String^ to std::string with such a Lambda example (If I am able to).
My current foreach:
List<String^>^ names = //Returning 'System.String' List from C#
for each (System::String^ name in names)
{
std::string convertedString = msclr::interop::marshal_as< std::string >(name);
nameObjects.push_back(MyObject(convertedString, "test"));
}
But I would like to extend it to something like this (My best guess but I am missing the logic to convert each element of "names" to a single string, this is where a Lambda would help me):
std::vector<nameObjects> testObjects{ std::begin(msclr::interop::marshal_as< std::string >(names)), std::end(msclr::interop::marshal_as< std::string >(names)) };
Alright, I figured out a way to make this work...it requires using the obscure cliext classes.
First, create a cliext::vector, there is an overload with takes an IEnumerator.
cliext::vector<String^> v_names(names);
Now, you can use cliext::transform() (not std::transform) to do STL-style iteration, and create MyObject instances with a lambda
std::vector<MyObject> testObjects;
cliext::transform(v_names.begin(), v_names.end(), std::back_inserter(testObjects), [](String^ name)
{
std::string convertedString = msclr::interop::marshal_as< std::string >(name);
return MyObject(convertedString, "test");
});

C++ : Strings, Structures and Access Violation Writing Locations

I'm attempting to try and use a string input from a method and set that to a variable of a structure, which i then place in a linked list. I didn't include, all of code but I did post constructor and all that good stuff. Now the code is breaking at the lines
node->title = newTitle;
node->isbn = newISBN;
So newTitle is the string input from the method that I'm trying to set to the title variable of the Book structure of the variable node. Now, I'm assuming this has to do with a issue with pointers and trying to set data to them, but I can't figure out a fix/alternative.
Also, I tried using
strcpy(node->title, newTitle)
But that had an issue with converting the string into a list of chars because strcpy only uses a list of characters. Also tried a few other things, but none seemed to pan out, help with an explanation would be appreciated.
struct Book
{
string title;
string isbn;
struct Book * next;
};
//class LinkedList will contains a linked list of books
class LinkedList
{
private:
Book * head;
public:
LinkedList();
~LinkedList();
bool addElement(string title, string isbn);
bool removeElement(string isbn);
void printList();
};
//Constructor
//It sets head to be NULL to create an empty linked list
LinkedList::LinkedList()
{
head = NULL;
}
//Description: Adds an element to the link in alphabetical order, unless book with
same title then discards
// Returns true if added, false otherwise
bool LinkedList::addElement(string newTitle, string newISBN)
{
struct Book *temp;
struct Book *lastEntry = NULL;
temp = head;
if (temp==NULL) //If the list is empty, sets data to first entry
{
struct Book *node;
node = (Book*) malloc(sizeof(Book));
node->title = newTitle;
node->isbn = newISBN;
head = node;
}
while (temp!=NULL)
{
... //Rest of Code
Note that your Book struct is already a linked list implementation, so you don't need the LinkedList class at all, or alternatively you don't need the 'next' element of the struct.
But there's no reason from the last (long) code snippet you pasted to have an error at the lines you indicated. node->title = newTitle should copy the string in newTitle to the title field of the struct. The string object is fixed size so it's not possible to overwrite any buffer and cause a seg fault.
However, there may be memory corruption from something you do further up the code, which doesn't cause an error until later on. The thing to look for is any arrays, including char[], that you might be overfilling. Another idea is you mention you save method parameters. If you copy, it's ok, but if you do something like
char* f() {
char str[20];
strcpy(str, "hello");
return str;
}
...then you've got a problem. (Because str is allocated on the stack and you return only the pointer to a location that won't be valid after the function returns.) Method parameters are local variables.
The answer you seek can be found here.
In short: the memory malloc returns does not contain a properly constructed object, so you can't use it as such. Try using new / delete instead.

Evaluating the subscript operator in the watch window

I have a simple array wrapper class, which goes like this:
class MyArray
{
int * m_Data;
int m_Size;
public:
MyArray(int aSize) : m_Size(aSize), m_Data(new int[aSize])
{
}
int & operator [](int aIndex)
{
return m_Data[aIndex];
}
const int & operator [](int aIndex) const
{
return m_Data[aIndex];
}
};
MyArray a(10);
Whenever I try to evaluate a subscript operator in the debugger (quick watch, immediate window etc): e.g. a[0], I get a[0] no operator "[]" matches these operands error. I know I can dig through class fields to get to the content of the array. But it is so much easier to just copy a part of code line and evaluate it in the watch window.
I tried removing const and non-const [] operators. I also tried using () operator, it didn't work either, but it gave a different error message. I tried this in VS2012 and VS2013 Preview: same thing.
Is there any way to fix this?
If I replace the subscript operator with a member function:
int & Item(int aIndex)
{
return m_Data[aIndex];
}
Then watch window is able to show me the result. But I would prefer to use subscript operator.
I found a solution, which is not very convenient, but seems to work. If I use the expanded form of the operator call, then it works in VC++2012:
a.operator[](0)
It's not clear to me why these two forms are different to VC++ debugger. So I posted a new question here

duck typing in D

I'm new to D, and I was wondering whether it's possible to conveniently do compile-time-checked duck typing.
For instance, I'd like to define a set of methods, and require that those methods be defined for the type that's being passed into a function. It's slightly different from interface in D because I wouldn't have to declare that "type X implements interface Y" anywhere - the methods would just be found, or compilation would fail. Also, it would be good to allow this to happen on any type, not just structs and classes. The only resource I could find was this email thread, which suggests that the following approach would be a decent way to do this:
void process(T)(T s)
if( __traits(hasMember, T, "shittyNameThatProbablyGetsRefactored"))
// and presumably something to check the signature of that method
{
writeln("normal processing");
}
... and suggests that you could make it into a library call Implements so that the following would be possible:
struct Interface {
bool foo(int, float);
static void boo(float);
...
}
static assert (Implements!(S, Interface));
struct S {
bool foo(int i, float f) { ... }
static void boo(float f) { ... }
...
}
void process(T)(T s) if (Implements!(T, Interface)) { ... }
Is is possible to do this for functions which are not defined in a class or struct? Are there other/new ways to do it? Has anything similar been done?
Obviously, this set of constraints is similar to Go's type system. I'm not trying to start any flame wars - I'm just using D in a way that Go would also work well for.
This is actually a very common thing to do in D. It's how ranges work. For instance, the most basic type of range - the input range - must have 3 functions:
bool empty(); //Whether the range is empty
T front(); // Get the first element in the range
void popFront(); //pop the first element off of the range
Templated functions then use std.range.isInputRange to check whether a type is a valid range. For instance, the most basic overload of std.algorithm.find looks like
R find(alias pred = "a == b", R, E)(R haystack, E needle)
if (isInputRange!R &&
is(typeof(binaryFun!pred(haystack.front, needle)) : bool))
{ ... }
isInputRange!R is true if R is a valid input range, and is(typeof(binaryFun!pred(haystack.front, needle)) : bool) is true if pred accepts haystack.front and needle and returns a type which is implicitly convertible to bool. So, this overload is based entirely on static duck typing.
As for isInputRange itself, it looks something like
template isInputRange(R)
{
enum bool isInputRange = is(typeof(
{
R r = void; // can define a range object
if (r.empty) {} // can test for empty
r.popFront(); // can invoke popFront()
auto h = r.front; // can get the front of the range
}));
}
It's an eponymous template, so when it's used, it gets replaced with the symbol with its name, which in this case is an enum of type bool. And that bool is true if the type of the expression is non-void. typeof(x) results in void if the expression is invalid; otherwise, it's the type of the expression x. And is(y) results in true if y is non-void. So, isInputRange will end up being true if the code in the typeof expression compiles, and false otherwise.
The expression in isInputRange verifies that you can declare a variable of type R, that R has a member (be it a function, variable, or whatever) named empty which can be used in a condition, that R has a function named popFront which takes no arguments, and that R has a member front which returns a value. This is the API expected of an input range, and the expression inside of typeof will compile if R follows that API, and therefore, isInputRange will be true for that type. Otherwise, it will be false.
D's standard library has quite a few such eponymous templates (typically called traits) and makes heavy use of them in its template constraints. std.traits in particular has quite a few of them. So, if you want more examples of how such traits are written, you can look in there (though some of them are fairly complicated). The internals of such traits are not always particularly pretty, but they do encapsulate the duck typing tests nicely so that template constraints are much cleaner and more understandable (they'd be much, much uglier if such tests were inserted in them directly).
So, that's the normal approach for static duck typing in D. It does take a bit of practice to figure out how to write them well, but that's the standard way to do it, and it works. There have been people who have suggested trying to come up with something similar to your Implements!(S, Interface) suggestion, but nothing has really come of that of yet, and such an approach would actually be less flexible, making it ill-suited for a lot of traits (though it could certainly be made to work with basic ones). Regardless, the approach that I've described here is currently the standard way to do it.
Also, if you don't know much about ranges, I'd suggest reading this.
Implements!(S, Interface) is possible but did not get enough attention to get into standard library or get better language support. Probably if I won't be the only one telling it is the way to go for duck typing, we will have a chance to have it :)
Proof of concept implementation to tinker around:
http://dpaste.1azy.net/6d8f2dc4
import std.traits;
bool Implements(T, Interface)()
if (is(Interface == interface))
{
foreach (method; __traits(allMembers, Interface))
{
foreach (compareTo; MemberFunctionsTuple!(Interface, method))
{
bool found = false;
static if ( !hasMember!(T, method) )
{
pragma(msg, T, " has no member ", method);
return false;
}
else
{
foreach (compareWhat; __traits(getOverloads, T, method))
{
if (is(typeof(compareTo) == typeof(compareWhat)))
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
}
}
return true;
}
interface Test
{
bool foo(int, double);
void boo();
}
struct Tested
{
bool foo(int, double);
// void boo();
}
pragma(msg, Implements!(Tested, Test)());
void main()
{
}

Conventions to specifying digital fixed point binary numbers with macros

I was wondering if there an established convention to specifying fixed point binary numbers in decimal format (with the use of a macro). I am not sure if this possible in C/C++, but perhaps this is implemented in some language(s) and there is a notational standard like 0x000000,1.2f,1.2d,1l,etc
Take this example for instance:
I am using Q15.16 for instance, but would like to have the convenience of specifying numbers in decimal format, perhaps something like this:
var num:Int32=1.2fp;
Presumably, the easiest way with regards to Haxe macros, numbers can be initialized with a function:
#:macro
fp_from_float(1.2);
But it would be nice to have a shorthand notation.
Have you seen Luca's Fixed Point example with Haxe 3 and Abstracts?
It's here:
https://groups.google.com/forum/?fromgroups=#!topic/haxelang/JsiWvl-c0v4
Summing it up, with the new Haxe 3 abstract types, you can define a type that will be compiled as an Int:
abstract Fixed16(Int)
{
inline function new(x:Int) this = x;
}
You can also define "conversion functions", which will allow you to automatically convert a float into Fixed16:
#:from public static inline function fromf(x:Float) {
#if debug
if (x >= 32768.0 || x < -32768.0) throw "Conversion to Fixed16 will overflow";
#end
return new Fixed16(Std.int(x*65536.0));
}
The secret here is the #:from metadata. With this code, you will already be able to declare fixed types like this:
var x:Fixed16 = 1.2;
Luca's already defined some operators, to make working with them easier, like:
#:op(A+B) public inline static function add(f:Fixed16, g:Fixed16) {
#if debug
var fr:Float = f.raw();
var gr:Float = g.raw();
if (fr+gr >= 2147483648.0 || fr+gr < -2147483648.0) throw "Addition of Fixed16 values will overflow";
#end
return new Fixed16(f.raw()+g.raw());
}
Again, the secret here is in #:op(A+B) metadata, which will annotate that this function may be called when handling addition. The complete GIST code is available at https://gist.github.com/deltaluca/5413225 , and you can learn more about abstracts at http://haxe.org/manual/abstracts

Resources