Is there any method support in clang which helps to get "fall through" cases? - llvm-clang

I want to get the fall through cases while traversing through the AST. Is there any method clang provides which i can use to get the "fallThrough" cases.
For example:
void f(int n) {
void g(), h(), i();
switch (n) {
case 1:
case 2:
g(); // This is the one of the case of "fall through"
case 3:
h();
}
}

After search in the internet i found the solution in clang developers archive.
http://clang-developers.42468.n3.nabble.com/check-whether-a-case-statement-has-a-break-statement-td4029282.html#a4029357
It was wonderful learning about how clang diagnostic works. :)

Related

Rust: what's the distinction between calling a variable inside placeholders and outside them (as a separate argument)

(Beginner's question) After observing a few coding examples (from various sources) and syntax suggestions by Cargo Clippy, I'm still wondering whether the following blocks are just two alternatives for the same result, or actually do something different(ly) which I must be aware of.
fn main() {
let string_1 = "Hello!";
let string_2 = "See you!";
println!("{} {}", string_1, string_2);
}
Or...
fn main() {
let string_1 = "Hello!";
let string_2 = "See you!";
println!("{string_1} {string_2}");
}
If I use the first syntax, Cargo Clippy suggests me to use the second one instead. But, if I write println!("{} {}", &string_1, &string_2);, Clippy no longer complains, so I guess the difference between both coding blocks has to do with Rust's unique concept of "ownership".
So, am I missing something?
They are the same (but the second is newer, being stabilized in Rust 1.58.0, and more recommended for new code).
The reason Clippy does not suggest the second form anymore when you take reference is because it is invalid: only identifiers (bare variable names) can be used with inline captures.

Are tail calls on diverging functions optimized in Rust?

If I have the following functions:
fn a() -> ! {
b()
}
fn b() -> ! {
loop {}
}
Does Rust optimize such calls to simple jumps?
I have looked at a Playground to show the assembly, but a seems to just callq the b function.
Is this always the case?
First, you can tell the compiler to inline a function using #[inline]: Technically, this does not guarantee inlining, but it should work in reasonable situations. I would recommend using this.
Second, as noted in the comments, you have to do an optimised build to see such inlining. Maybe a better tool for this would be Compiler Explorer. Here is a slight modification of your example (notice the -O flag in compiler options). As you can see, everything is inlined into one infinite loop, and the compiler can even eliminate some work done in the loop if it can prove that it is useless.
Overall, unless you use #[inline], the result will depend on the contents of a and b. So I would advise to create some kind of minimal-viable-implementation of what you are trying to achieve with a and b, and then test it in Compiler Explorer.

Why would one write a C++ lambda with a name so it can be called from somewhere?

Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?
One use of this is to have a function access the enclosing scope.
In C++, we don't have nested functions as we do in some other languages.
Having a named lambda solves this problem.
An example:
#include <iostream>
int main ()
{
int x;
auto fun = [&] (int y) {
return x + y;
};
std::cin >> x;
int t;
std::cin >> t;
std::cout << fun (fun (t));
return 0;
}
Here, the function fun is basically a nested function in main, able to access its local variables.
We can format it so that it resembles a regular function, and use it more than once.
A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:
std::string key;
std::map<std::string, int> v;
one can write the following:
std::find_if( v.begin(), v.end(), [&](auto const& elem){ return elem.first == key; } );
but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:
auto matches_key = [&](auto const& elem){ return elem.first == key; };
std::find_if( v.begin(), v.end(), matches_key );
it is clearer that we do want the equality comparison and the readability is improved.
I see three things to consider when choosing between a named lamdba and a free function:
Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).
Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).
Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure
is a bit confusing in a header file (though this is debatable, of course).
requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.
When your lambda is a recursive function by itself you have no choice but to give it a name. Also, an auto keyword won't suffice and you would HAVE to declare it using an std::function with the return type and the argument list.
Below is the example for a function that returns the Nth Fibonacci number:
std::function<int(int)> fibonacci = [&](int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
You have to give it a name in order to capture it with &. And auto won't work since lambda needs its to know its types before calling itself.
This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.
But beside of that, there is no difference.
when tuning a C++ application, a named lambda is easier to tune/trace, as compared to an anonymous/unamed lambda
I always consider lamdas as a nicety - I did plenty of C++ coding without them before they were introduced. So in some ways, I don't consider that there are many shoulds or shouldn'ts surrounding them. They are there to use however they make your life easier.
One time I use named lamdas is to scope a function - i.e. the lamda is only going to be used within another function - perhaps it does something a little dangerous, that you don't want other functions to have access to or perhaps you don't want to pollute the namespace.
If your lamda is too long to be an easy one-liner, but you don't want it to be
a available outside of your scope, then a named lamda is ideal way to produce tidy easy to read code.

Jump out of "try-catch"?

Is there a language with a keyword to jump out of try-catch block?
For example, there is a walkaround in Ruby:
lambda {
begin
p 0
break
p 1
rescue
p 2
end
}.call
p 3
It's also (I believe) possible in Javascript.
But I want a way without anonymous function (to avoid indentation) – like if break or continue were possible.
I know, that C/C++/C# languages allow using goto.
Do languages with another approach exist?
You could always just throw a known exception which you catch but do nothing with. In c#
try {
if(true)
throw new GetOutException();
}
catch(GetOutException e) {
}
catch(Exception e) {
// Do something here
}
Using continuations, you can jump out of any part in the code. For instance, with call-with-current-continuation in Scheme. This example from wikipedia illustrates the basic concept:
(define (f return)
(return 2)
3)
(display (f (lambda (x) x))) ; displays 3
(display (call-with-current-continuation f)) ; displays 2
In general, a continuation can be used to escape from any point in the execution of a procedure (they're not limited to try/catch blocks), no matter how deeply nested it is - in that regard, it's a more general construct than an Exception or a goto, as both of those constructs can be implemented in terms of continuations.
At first, continuations are not an easy-to-grasp concept, but with practice they can be very useful, see this paper detailing the many possible applications of continuations.
So basically it sounds like you're asking for a goto equivalent to skip the execution of particular parts of your code. Something like:
foo();
if (!bar) {
goto end;
}
baz();
end:
print "ended";
I won't go into pros and cons of gotos, but they're not available in a number of languages for various reasons. You can virtually always formulate your code like below for the same effect though:
foo();
if (bar) {
baz();
}
print "ended";
This obviously also works when you're actually using exceptions:
try {
foo();
if (bar) {
baz();
}
} catch (Exception e) {
help();
}
print "ended";
It has the same effect of skipping the execution of a particular branch of code under certain circumstances and is the standard way to do it. I cannot really imagine a situation where breaking out of a try..catch or using an equivalent goto would offer any advantage.

What is the best way to replace or substitute if..else if..else trees in programs?

This question is motivated by something I've lately started to see a bit too often, the if..else if..else structure. While it's simple and has its uses, something about it keeps telling me again and again that it could be substituted with something that's more fine-grained, elegant and just generally easier to keep up-to-date.
To be as specific as possible, this is what I mean:
if (i == 1) {
doOne();
} else if (i == 2) {
doTwo();
} else if (i == 3) {
doThree();
} else {
doNone();
}
I can think of two simple ways to rewrite that, either by ternary (which is just another way of writing the same structure):
(i == 1) ? doOne() :
(i == 2) ? doTwo() :
(i == 3) ? doThree() : doNone();
or using Map (in Java and I think in C# too) or Dictionary or any other K/V structure like this:
public interface IFunctor() {
void call();
}
public class OneFunctor implemets IFunctor() {
void call() {
ref.doOne();
}
}
/* etc. */
Map<Integer, IFunctor> methods = new HashMap<Integer, IFunctor>();
methods.put(1, new OneFunctor());
methods.put(2, new TwoFunctor());
methods.put(3, new ThreeFunctor());
/* .. */
(methods.get(i) != null) ? methods.get(i).call() : doNone();
In fact the Map method above is what I ended up doing last time but now I can't stop thinking that there has to be better alternatives in general for this exact issue.
So, which other -and most likely better- ways to replace the if..else if..else are out there and which one is your favorite?
Your thoughts below this line!
Okay, here are your thoughts:
First, most popular answer was switch statement, like so:
switch (i) {
case 1: doOne(); break;
case 2: doTwo(); break;
case 3: doThree(); break;
default: doNone(); break;
}
That only works for values which can be used in switches, which at least in Java is quite a limiting a factor. Acceptable for simple cases though, naturally.
The other and perhaps a bit fancier way you seem to sugges is to do it using polymorphism. The Youtube lecture linked by CMS is an excellent watch, go see it here: "The Clean Code Talks -- Inheritance, Polymorphism, & Testing" As far as I understood, this would translate to something like this:
public interface Doer {
void do();
}
public class OneDoer implements Doer {
public void do() {
doOne();
}
}
/* etc. */
/* some method of dependency injection like Factory: */
public class DoerFactory() {
public static Doer getDoer(int i) {
switch (i) {
case 1: return new OneDoer();
case 2: return new TwoDoer();
case 3: return new ThreeDoer();
default: return new NoneDoer();
}
}
}
/* in actual code */
Doer operation = DoerFactory.getDoer(i);
operation.do();
Two interesting points from the Google talk:
Use Null Objects instead of returning nulls (and please throw only Runtime Exceptions)
Try to write a small project without if:s.
Also in addition one post worth mentioning in my opinion is CDR who provided his perverse habits with us and while not recommended to use, it's just very interesting to look at.
Thank you all for the answers (so far), I think I might have learned something today!
These constructs can often be replaced by polymorphism. This will give you shorter and less brittle code.
In Object Oriented languages, it's common to use polymorphism to replace if's.
I liked this Google Clean Code Talk that covers the subject:
The Clean Code Talks -- Inheritance, Polymorphism, & Testing
ABSTRACT
Is your code full of if statements?
Switch statements? Do you have the
same switch statement in various
places? When you make changes do you
find yourself making the same change
to the same if/switch in several
places? Did you ever forget one?
This talk will discuss approaches to
using Object Oriented techniques to
remove many of those conditionals. The
result is cleaner, tighter, better
designed code that's easier to test,
understand and maintain.
A switch statement:
switch(i)
{
case 1:
doOne();
break;
case 2:
doTwo();
break;
case 3:
doThree();
break;
default:
doNone();
break;
}
Depending on the type of thing you are if..else'ing, consider creating a hierarchy of objects and using polymorphism. Like so:
class iBase
{
virtual void Foo() = 0;
};
class SpecialCase1 : public iBase
{
void Foo () {do your magic here}
};
class SpecialCase2 : public iBase
{
void Foo () {do other magic here}
};
Then in your code just call p->Foo() and the right thing will happen.
There's two parts to that question.
How to dispatch based on a value? Use a switch statement. It displays your intent most clearly.
When to dispatch based on a value? Only at one place per value: create a polymorphic object that knows how to provide the expected behavior for the value.
The switch statement of course, much prettier then all those if's and else's.
Outside of using a switch statement, which can be faster, none. If Else is clear and easy to read. having to look things up in a map obfuscates things. Why make code harder to read?
switch (i) {
case 1: doOne(); break;
case 2: doTwo(); break;
case 3: doThree(); break;
default: doNone(); break;
}
Having typed this, I must say that there is not that much wrong with your if statement. Like Einstein said: "Make it as simple as possible, but no simpler".
I use the following short hand just for fun! Don't try anyof these if code clearity concerns you more than the number of chars typed.
For cases where doX() always returns true.
i==1 && doOne() || i==2 && doTwo() || i==3 && doThree()
Ofcourse I try to ensure most void functions return 1 simply to ensure that these short hands are possible.
You can also provide assignments.
i==1 && (ret=1) || i==2 && (ret=2) || i==3 && (ret=3)
Like instad of writting
if(a==2 && b==3 && c==4){
doSomething();
else{
doOtherThings();
}
Write
a==2 && b==3 && c==4 && doSomething() || doOtherThings();
And in cases, where not sure what the function will return, add an ||1 :-)
a==2 && b==3 && c==4 && (doSomething()||1) || doOtherThings();
I still find it faster to type than using all those if-else and it sure scares all new noobs out. Imagine a full page of statement like this with 5 levels of indenting.
"if" is rare in some of my codes and I have given it the name "if-less programming" :-)
In this simple case you could use a switch.
Otherwise a table-based approach looks fine, it would be my second choice whenever the conditions are regular enough to make it applicable, especially when the number of cases is large.
Polymorphism would be an option if there are not too many cases, and conditions and behaviour are irregular.
The example given in the question is trivial enough to work with a simple switch. The problem comes when the if-elses are nested deeper and deeper. They are no longer "clear or easy to read," (as someone else argued) and adding new code or fixing bugs in them becomes more and more difficult and harder to be sure about because you might not end up where you expected if the logic is complex.
I've seen this happen lots of times (switches nested 4 levels deep and hundreds of lines long--impossible to maintain), especially inside of factory classes that are trying to do too much for too many different unrelated types.
If the values you're comparing against are not meaningless integers, but some kind of unique identifier (i.e. using enums as a poor man's polymorphism), then you want to use classes to solve the problem. If they really are just numeric values, then I would rather use separate functions to replace the contents of the if and else blocks, and not design some kind of artificial class hierarchy to represent them. In the end that can result in messier code than the original spaghetti.
Use a switch/case it's cleaner :p
switch statement or classes with virtual functions as fancy solution. Or array of pointers to functions. It's all depends on how complex conditions are, sometimes there's no way around those if's. And again, creating series of classes to avoid one switch statement is clearly wrong, code should be as simple as possible (but not simpler)
I would go so far as to say that no program should ever use else. If you do you are asking for trouble. You should never assume if it's not an X it must be a Y. Your tests should test for each individually and fail following such tests.
In OO paradigm you could do it using good old polymorphism. Too big if - else structures or switch constructs are sometimes considered a smell in the code.
The Map method is about the best there is. It lets you encapsulate the statements and breaks things up quite nicely. Polymorphism can complement it, but its goals are slightly different. It also introduces unnecessary class trees.
Switches have the drawback of missing break statements and fall through, and really encourage not breaking the problem into smaller pieces.
That being said: A small tree of if..else's is fine (in fact, i argued in favor for days about have 3 if..elses instead of using Map recently). Its when you start to put more complicated logic in them that it becomes a problem due to maintainability and readability.
In python, I would write your code as:
actions = {
1: doOne,
2: doTwo,
3: doThree,
}
actions[i]()
I regard these if-elseif-... constructs as "keyword noise". While it may be clear what it does, it is lacking in conciseness; I regard conciseness as an important part of readability. Most languages provide something like a switch statement. Building a map is a way to get something similar in languages that do not have such, but it certainly feels like a workaround, and there is a bit of overhead (a switch statement translates to some simple compare operations and conditional jumps, but a map first is built in memory, then queried and only then the compare and jump takes place).
In Common Lisp, there are two switch constructs built in, cond and case. cond allows arbitrary conditionals, while case only tests for equality, but is more concise.
(cond ((= i 1)
(do-one))
((= i 2)
(do-two))
((= i 3)
(do-three))
(t
(do-none)))
(case i
(1 (do-one))
(2 (do-two))
(3 (do-three))
(otherwise (do-none)))
Of course, you could make your own case-like macro for your needs.
In Perl, you can use the for statement, optionally with an arbitrary label (here: SWITCH):
SWITCH: for ($i) {
/1/ && do { do_one; last SWITCH; };
/2/ && do { do_two; last SWITCH; };
/3/ && do { do_three; last SWITCH; };
do_none; };
Use a Ternary Operator!
Ternary Operator(53Characters):
i===1?doOne():i===2?doTwo():i===3?doThree():doNone();
If(108Characters):
if (i === 1) {
doOne();
} else if (i === 2) {
doTwo();
} else if (i === 3) {
doThree();
} else {
doNone();
}
Switch((EVEN LONGER THAN IF!?!?)114Characters):
switch (i) {
case 1: doOne(); break;
case 2: doTwo(); break;
case 3: doThree(); break;
default: doNone(); break;
}
this is all you need! it is only one line and it is pretty neat, way shorter than switch and if!
Naturally, this question is language-dependent, but a switch statement might be a better option in many cases. A good C or C++ compiler will be able to generate a jump table, which will be significantly faster for large sets of cases.
If you really must have a bunch of if tests and want to do different things whenwver a test is true I would recommend a while loop with only ifs- no else. Each if does a test an calls a method then breaks out of the loop. No else there's nothing worse than a bunch of stacked if/else/if/else etc.