clang-format: Align asterisk (*) of pointer declaration with variable name - clang

I am using the following options in my .clang-format file:
AlignConsecutiveDeclarations: true
PointerAlignment: Right
The current formatting result is the following:
char * var1;
SomeOtherType *var2;
int var3;
The result I was expecting would be:
char *var1; //note the changed position of *
SomeOtherType *var2;
int var3;
How can I configure clang-format to align the asterix (*) with the variable name rather then with the type when I am
using the AlignConsecutiveDeclarations option?

PointerAlignment: Right is unfortunately not implemented yet.
See https://github.com/llvm/llvm-project/blob/master/clang/lib/Format/WhitespaceManager.cpp#L643
void WhitespaceManager::alignConsecutiveDeclarations() {
if (!Style.AlignConsecutiveDeclarations)
return;
// FIXME: Currently we don't handle properly the PointerAlignment: Right
// The * and & are not aligned and are left dangling. Something has to be done
// about it, but it raises the question of alignment of code like:
// const char* const* v1;
// float const* v2;
// SomeVeryLongType const& v3;
AlignTokens(Style, [](Change const &C) { return C.IsStartOfDeclName; },
Changes);
}

It's fixed now!
The review https://reviews.llvm.org/D27651 has been re-applied in https://reviews.llvm.org/D103245 and committed in https://reviews.llvm.org/rG3e333cc82e42e1e2ecc974d896489eebe1a5edc2.
This change will be included in LLVM 13 release.

Related

clang-format function argument indent

Is there a way to configure clang-format to behave in this way? Notice how each parameter is on its own line and is indented by only 1 level as opposed to aligned with the function name. This is my preferred coding style, but I just can't get clang-format to do this.
int a_very_long_function_name(
int var_a,
double my_b,
char *str
) {
int d = 0;
/* ... */
return d;
}
As far as I know, this is not possible.
You can try all the different parameters with this nifty tool: https://zed0.co.uk/clang-format-configurator/
Should be possible now according to: https://clang.llvm.org/docs/ClangFormatStyleOptions.html
AlignAfterOpenBracket: BlockIndent

How do I find the SourceLocation of the commas between function arguments using libtooling?

My main goal is trying to get macros (or even just the text) before function parameters. For example:
void Foo(_In_ void* p, _Out_ int* x, _Out_cap_(2) int* y);
I need to gracefully handle things like macros that declare parameters (by ignoring them).
#define Example _In_ int x
void Foo(Example);
I've looked at Preprocessor record objects and used Lexer::getSourceText to get the macro names In, Out, etc, but I don't see a clean way to map them back to the function parameters.
My current solution is to record all the macro expansions in the file and then compare their SourceLocation to the ParamVarDecl SourceLocation. This mostly works except I don't know how to skip over things after the parameter.
void Foo(_In_ void* p _Other_, _In_ int y);
Getting the SourceLocation of the comma would work, but I can't find that anywhere.
The title of the questions asks for libclang, but as you use Lexer::getSourceText I assume that it's libTooling. The rest of my answer is viable only in terms of libTooling.
Solution 1
Lexer works on the level of tokens. Comma is also a token, so you can take the end location of a parameter and fetch the next token using Lexer::findNextToken.
Here is a ParmVarDecl (for function parameters) and CallExpr (for function arguments) visit functions that show how to use it:
template <class T> void printNextTokenLocation(T *Node) {
auto NodeEndLocation = Node->getSourceRange().getEnd();
auto &SM = Context->getSourceManager();
auto &LO = Context->getLangOpts();
auto NextToken = Lexer::findNextToken(NodeEndLocation, SM, LO);
if (!NextToken) {
return;
}
auto NextTokenLocation = NextToken->getLocation();
llvm::errs() << NextTokenLocation.printToString(SM) << "\n";
}
bool VisitParmVarDecl(ParmVarDecl *Param) {
printNextTokenLocation(Param);
return true;
}
bool VisitCallExpr(CallExpr *Call) {
for (auto *Arg : Call->arguments()) {
printNextTokenLocation(Arg);
}
return true;
}
For the following code snippet:
#define FOO(x) int x
#define BAR float d
#define MINUS -
#define BLANK
void foo(int a, double b ,
FOO(c) , BAR) {}
int main() {
foo( 42 ,
36.6 , MINUS 10 , BLANK 0.0 );
return 0;
}
it produces the following output (six locations for commas and two for parentheses):
test.cpp:6:15
test.cpp:6:30
test.cpp:7:19
test.cpp:7:24
test.cpp:10:17
test.cpp:11:12
test.cpp:11:28
test.cpp:11:43
This is quite a low-level and error-prone approach though. However, you can change the way you solve the original problem.
Solution 2
Clang stores information about expanded macros in its source locations. You can find related methods in SourceManager (for example, isMacroArgExpansion or isMacroBodyExpansion). As the result, you can visit ParmVarDecl nodes and check their locations for macro expansions.
I would strongly advice moving in the second direction.
I hope this information will be helpful. Happy hacking with Clang!
UPD speaking of attributes, unfortunately, you won't have a lot of choices. Clang does ignore any unknown attribute and this behaviour is not tweakable. If you don't want to patch Clang itself and add your attributes to Attrs.td, then you're limited indeed to tokens and the first approach.

MQL4 multi-timeframe indicator

I would like to write out an indicator that can take in input the int shift of an assigned timeframe, and turns out a value related to another timeframe.
As an example, I would like to write an MACD indicator over a 100 periods of M15, that can return out its value 1,2,3,4,5,6,7... minutes before the current candle.
Since in the current candle this indicator "changes" its value, tick by tick, I think that should be possible to write out such an indicator, but I can not figure out how to do it.
MQL4 language principally has tools for this:
However, as noted above, your experimentation will need thorough quant validations, as the earlier Builds did not support this in [MT4-Strategy Tester] code-execution environment ( and more recent shifts into New-MQL4.56789 have devastated performance constraints for all [CustomIndicators], the all [MT4-graph]-GUI-s together plus the all [Expert Advisor]-s use, since all these suddenly share one ( yes, ONE and THE ONLY ) computing thread.
Ok, you have been warned :o)
So,
if indeed keen to equip your [CustomIndicator] so as to be independent of the GUI-native-TimeFrame, all your calculations inside such [CustomIndicator]-code must use indirect access-tools to source the PriceDOMAIN data - so never use any { Open[] | High[] | Low[] | Close[] }-TimeSeries data directly, but only using { iOpen() | iHigh() | iLow() | iClose() }
All these access tools conceptually have a common signature:
double iLow( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
and
if your code
obeys this duty,
your [CustomIndicator]( iff the StrategyTester will not finally spoil the game -- due quant testing will show this )
will be working with data from timeframe & shift of your wish.
Implementation remarks:
Your [CustomIndicator]-code has to implement a "non-GUI-shift" independently from the GUI-native-TimeFrame shift-counting. See an iCustom() signature template for inspiration. The GUI-TimeFrame-shift is like moving the line-graph on GUI-screen, i.e. in GUI-native-TimeFrame steps, not taking into account your [CustomIndicator] "internal"-"non-GUI-shift" values, so your code has to be smarter, so as to process this "internal"-"non-GUI-shift" during a value generation. If in doubts, during prototyping, validate the proper "mechanics" on Time[aShiftINTENDED] vs iTime( _Symbol, PERIOD_INTENDED, aShiftINTENDED )
Due to quite a lot of points, where an iCustom() call-interface may be a bit misleading, or a revision-change-management error-prone, we got used to use a formal template for each [Custom Indicator] code, helping to maintain referential integrity with a iCustom() use in the actual [ExpertAdvisor] code. It might seem a bit dumb, but those, who have spent man*hours in search for a bug in { un- | ill- }-propagated call-interface changes, this may become a life-saver.
We formalise the call-interface in such a way, that this section, maintained in the [CustomIndicator]-code, can always be copied into the [ExpertAdviser] code, so that the iCustom() signature-match can be inspected.
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!
//---- indicator parameters -------------------------------------------------
// POSITIONAL ORDINAL-NUMBERED CALLING INTERFACE
// all iCustom() calls MUST BE REVISED ON REVISION
//!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#define XEMA_CUSTOM_INDICATOR_NAME "EMA_DEMA_TEMA_XEMA_wShift" // this.
//--- input parameters ------------------------------------------------------ iCustom( ) CALL INTERFACE
input int nBARs_period = 8;
extern double MUL_SIGMA = 2.5;
sinput ENUM_APPLIED_PRICE aPriceTYPE = PRICE_CLOSE;
extern int ShiftBARs = 0;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/* = iCustom( _Symbol,
PERIOD_CURRENT, XEMA_CUSTOM_INDICATOR_NAME, // |-> iCustom INDICATOR NAME
XEMA_nBARs_period, // |-> input nBARs_period
XEMA_MUL_SIGMA, // |-> input MUL_SIGMA
XEMA_PRICE_TYPE, // |-> input aPriceTYPE from: ENUM_APPLIED_PRICE
XEMA_ShiftBARs, // |-> input ShiftBARs
XEMA_<_VALUE_>_BUFFER_ID, // |-> line# --------------------------------------------from: { #define'd (e)nums ... }
0 // |-> [0]-aTimeDOMAIN-offset
); //
*/
#define XEMA_Main_AXIS_BUFFER_ID 0 // <----xEMA<maxEMAtoCOMPUTE>[]
#define XEMA_UpperBAND_BUFFER_ID 1
#define XEMA_LowerBAND_BUFFER_ID 2
#define XEMA_StdDEV____BUFFER_ID 3
#define XEMA_SimpleEMA_BUFFER_ID 4 // sEMA
#define XEMA_DoubleEMA_BUFFER_ID 10 // dEMA
#define XEMA_TripleEMA_BUFFER_ID 11 // tEMA
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!
//---- indicator parameters -------------------------------------------------
// POSITIONAL ORDINAL-NUMBERED CALLING INTERFACE
// all iCustom() calls MUST BE REVISED ON REVISION
//!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Found a way to write it in a very simple way:
double M1 (int shift) {double val = iCustom(NULL,PERIOD_M1, "my_indicator",100,2.0,30.0,0,shift); return(val);}
double M15 (int shift) {double val = iCustom(NULL,PERIOD_M15,"my_indicator",100,2.0,30.0,0,shift); return(val);}
int s1_15;
double B_M1_M15(int i) {
if (i>=0 && i<15 ) s1_15=0;
else if (i>=15 && i<30 ) s1_15=1;
else if (i>=30 && i<45 ) s1_15=2;
else if (i>=45 && i<60 ) s1_15=3;
else if (i>=60 && i<75 ) s1_15=4;
return NormalizeDouble(MathAbs(M1(i) - M15(s1_15)),Digits);
}
and so on for every others couples of timeframe.

How to align a struct member in D?

I tried this
struct Foo(T)
{
align(8) void[T.sizeof] data;
}
but
static assert(Foo!(int).data.alignof == 8);
fails, telling me the alignment is still 1 instead of 8.
Why is this, and how do I fix it, so that it works for any arbitrary alignment that is a power of 2 (not just 8)?
Browsing the DMD source, it looks like alignof doesn't take into account align attributes.
Here is where it is handled:
... if (ident == Id::__xalignof)
{
e = new IntegerExp(loc, alignsize(), Type::tsize_t);
}
This converts a .alignof expression into a size_t expression with value alignsize(), so let's look at alignsize() for a static array:
unsigned TypeSArray::alignsize()
{
return next->alignsize();
}
It just gets the alignment of the element type (void) in your case.
void is handled by TypeBasic::alignsize(), which just forwards to TypeBasic::size(0)
switch (ty)
{
...
case Tvoid:
size = 1;
break;
...
}
Looking at how other types handle alignof, it doesn't look like align attributes are taken into account at all, but I could be wrong. It may be worth testing the alignment manually.

Evaluating Mathematical Expressions using Lua

In my previous question I was looking for a way of evaulating complex mathematical expressions in C, most of the suggestions required implementing some type of parser.
However one answer, suggested using Lua for evaluating the expression. I am interested in this approach but I don't know anything about Lua.
Can some one with experience in Lua shed some light?
Specifically what I'd like to know is
Which API if any does Lua provide that can evaluate mathematical expressions passed in as a string? If there is no API to do such a thing, may be some one can shed some light on the linked answer as it seemed like a good approach :)
Thanks
The type of expression I'd like to evaluate is given some user input such as
y = x^2 + 1/x - cos(x)
evaluate y for a range of values of x
It is straightforward to set up a Lua interpreter instance, and pass it expressions to be evaluated, getting back a function to call that evaluates the expression. You can even let the user have variables...
Here's the sample code I cooked up and edited into my other answer. It is probably better placed on a question tagged Lua in any case, so I'm adding it here as well. I compiled this and tried it for a few cases, but it certainly should not be trusted in production code without some attention to error handling and so forth. All the usual caveats apply here.
I compiled and tested this on Windows using Lua 5.1.4 from Lua for Windows. On other platforms, you'll have to find Lua from your usual source, or from www.lua.org.
Update: This sample uses simple and direct techniques to hide the full power and complexity of the Lua API behind as simple as possible an interface. It is probably useful as-is, but could be improved in a number of ways.
I would encourage readers to look into the much more production-ready ae library by lhf for code that takes advantage of the API to avoid some of the quick and dirty string manipulation I've used. His library also promotes the math library into the global name space so that the user can say sin(x) or 2 * pi without having to say math.sin and so forth.
Public interface to LE
Here is the file le.h:
/* Public API for the LE library.
*/
int le_init();
int le_loadexpr(char *expr, char **pmsg);
double le_eval(int cookie, char **pmsg);
void le_unref(int cookie);
void le_setvar(char *name, double value);
double le_getvar(char *name);
Sample code using LE
Here is the file t-le.c, demonstrating a simple use of this library. It takes its single command-line argument, loads it as an expression, and evaluates it with the global variable x changing from 0.0 to 1.0 in 11 steps:
#include <stdio.h>
#include "le.h"
int main(int argc, char **argv)
{
int cookie;
int i;
char *msg = NULL;
if (!le_init()) {
printf("can't init LE\n");
return 1;
}
if (argc<2) {
printf("Usage: t-le \"expression\"\n");
return 1;
}
cookie = le_loadexpr(argv[1], &msg);
if (msg) {
printf("can't load: %s\n", msg);
free(msg);
return 1;
}
printf(" x %s\n"
"------ --------\n", argv[1]);
for (i=0; i<11; ++i) {
double x = i/10.;
double y;
le_setvar("x",x);
y = le_eval(cookie, &msg);
if (msg) {
printf("can't eval: %s\n", msg);
free(msg);
return 1;
}
printf("%6.2f %.3f\n", x,y);
}
}
Here is some output from t-le:
E:...>t-le "math.sin(math.pi * x)"
x math.sin(math.pi * x)
------ --------
0.00 0.000
0.10 0.309
0.20 0.588
0.30 0.809
0.40 0.951
0.50 1.000
0.60 0.951
0.70 0.809
0.80 0.588
0.90 0.309
1.00 0.000
E:...>
Implementation of LE
Here is le.c, implementing the Lua Expression evaluator:
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <string.h>
static lua_State *L = NULL;
/* Initialize the LE library by creating a Lua state.
*
* The new Lua interpreter state has the "usual" standard libraries
* open.
*/
int le_init()
{
L = luaL_newstate();
if (L)
luaL_openlibs(L);
return !!L;
}
/* Load an expression, returning a cookie that can be used later to
* select this expression for evaluation by le_eval(). Note that
* le_unref() must eventually be called to free the expression.
*
* The cookie is a lua_ref() reference to a function that evaluates the
* expression when called. Any variables in the expression are assumed
* to refer to the global environment, which is _G in the interpreter.
* A refinement might be to isolate the function envioronment from the
* globals.
*
* The implementation rewrites the expr as "return "..expr so that the
* anonymous function actually produced by lua_load() looks like:
*
* function() return expr end
*
*
* If there is an error and the pmsg parameter is non-NULL, the char *
* it points to is filled with an error message. The message is
* allocated by strdup() so the caller is responsible for freeing the
* storage.
*
* Returns a valid cookie or the constant LUA_NOREF (-2).
*/
int le_loadexpr(char *expr, char **pmsg)
{
int err;
char *buf;
if (!L) {
if (pmsg)
*pmsg = strdup("LE library not initialized");
return LUA_NOREF;
}
buf = malloc(strlen(expr)+8);
if (!buf) {
if (pmsg)
*pmsg = strdup("Insufficient memory");
return LUA_NOREF;
}
strcpy(buf, "return ");
strcat(buf, expr);
err = luaL_loadstring(L,buf);
free(buf);
if (err) {
if (pmsg)
*pmsg = strdup(lua_tostring(L,-1));
lua_pop(L,1);
return LUA_NOREF;
}
if (pmsg)
*pmsg = NULL;
return luaL_ref(L, LUA_REGISTRYINDEX);
}
/* Evaluate the loaded expression.
*
* If there is an error and the pmsg parameter is non-NULL, the char *
* it points to is filled with an error message. The message is
* allocated by strdup() so the caller is responsible for freeing the
* storage.
*
* Returns the result or 0 on error.
*/
double le_eval(int cookie, char **pmsg)
{
int err;
double ret;
if (!L) {
if (pmsg)
*pmsg = strdup("LE library not initialized");
return 0;
}
lua_rawgeti(L, LUA_REGISTRYINDEX, cookie);
err = lua_pcall(L,0,1,0);
if (err) {
if (pmsg)
*pmsg = strdup(lua_tostring(L,-1));
lua_pop(L,1);
return 0;
}
if (pmsg)
*pmsg = NULL;
ret = (double)lua_tonumber(L,-1);
lua_pop(L,1);
return ret;
}
/* Free the loaded expression.
*/
void le_unref(int cookie)
{
if (!L)
return;
luaL_unref(L, LUA_REGISTRYINDEX, cookie);
}
/* Set a variable for use in an expression.
*/
void le_setvar(char *name, double value)
{
if (!L)
return;
lua_pushnumber(L,value);
lua_setglobal(L,name);
}
/* Retrieve the current value of a variable.
*/
double le_getvar(char *name)
{
double ret;
if (!L)
return 0;
lua_getglobal(L,name);
ret = (double)lua_tonumber(L,-1);
lua_pop(L,1);
return ret;
}
Remarks
The above sample consists of 189 lines of code total, including a spattering of comments, blank lines, and the demonstration. Not bad for a quick function evaluator that knows how to evaluate reasonably arbitrary expressions of one variable, and has rich library of standard math functions at its beck and call.
You have a Turing-complete language underneath it all, and it would be an easy extension to allow the user to define complete functions as well as to evaluate simple expressions.
Since you're lazy, like most programmers, here's a link to a simple example that you can use to parse some arbitrary code using Lua. From there, it should be simple to create your expression parser.
This is for Lua users that are looking for a Lua equivalent of "eval".
The magic word used to be loadstring but it is now, since Lua 5.2, an upgraded version of load.
i=0
f = load("i = i + 1") -- f is a function
f() ; print(i) -- will produce 1
f() ; print(i) -- will produce 2
Another example, that delivers a value :
f=load('return 2+3')
print(f()) -- print 5
As a quick-and-dirty way to do, you can consider the following equivalent of eval(s), where s is a string to evaluate :
load(s)()
As always, eval mechanisms should be avoided when possible since they are expensive and produce a code difficult to read.
I personally use this mechanism with LuaTex/LuaLatex to make math operations in Latex.
The Lua documentation contains a section titled The Application Programming Interface which describes how to call Lua from your C program. The documentation for Lua is very good and you may even be able to find an example of what you want to do in there.
It's a big world in there, so whether you choose your own parsing solution or an embeddable interpreter like Lua, you're going to have some work to do!
function calc(operation)
return load("return " .. operation)()
end

Resources