I would like to refactor a variable inside a function, but only inside that function. Is this possible in the JetBrains IDE's?
Example:
var global = 0;
function func1 (val) {
if (val === global) {
doSomething();
} else if (val * 2 === global) {
doSomethingElse();
} else {
doSomethingElseEntirely();
}
}
function func2 (val) {
if (val === global) {
doSomething();
} else if (val * 2 === global) {
doSomethingElse();
} else {
doSomethingElseEntirely();
}
}
If I try to change the variable global inside func1 via refactor, it will be changed in all of globals scope, so in func2 as well. I would like to prevent this. Is this possible?
Here is a simpler workaround.
Add a dummy var global within func1.
Use the Refactor > Rename tool (Shift + F6), while selecting any occurrence of global in func1.
Remove the line (place the caret in the line and hit Ctrl + Y) added in step 1.
As far as I know "current file" is the smallest scope possible.
Workaround:
To achive what you want with the least effort, I suggest to use the normal search.
Search "global" (Strg + F)
place the cursor before or above the first occurence of "global" in your function (to get right starting point and remove focus from the search field)
click "Add Selection for Next Occurence" (or Alt+J) as often as needed
rename all occurences at once by typing in the new name
some manual work needed here, but I think its the fastest way for big functions.
Related
I have an if statement which needs to check for the existence of a value in a nested Option. The statement currently looks like
if my_vec.get(0).is_some() && my_vec.get(0).unwrap().is_some() {
// My True Case
} else {
// My Else Case
}
I feel like this is an amateurish way of checking if this potential nested value exists. I want to maintain safety when fetching the Option from the array as it may or may not exist, and also when unwrapping the Option itself. I tried using and_then and similar operators but haven't had any luck.
I would check the length first and access it like a regular array instead of using .get(x) unless there is some benefit in doing so (like passing it to something which expects an option).
if my_vec.len() > x && my_vec[x].is_some() {
// etc
}
Another option is to just match the value with an if let x = y or full match statement.
if let Some(Some(_)) = my_vec.get(x) {
// etc
}
The matches! macro can also be used in this situation similarly to the if let when you don't need to take a reference to the data.
if matches!(my_vec.get(x), Some(Some(_))) {
// etc
}
Or the and_then version, but personally it is probably my least favorite since it is longer and gargles the intention.
if my_vec.get(x).and_then(|y| y.as_ref()).is_some() {
// etc
}
You can pick whichever one is your favorite. They all compile down to the same thing (probably, I haven't checked).
In C and in javascript I enjoy the ability to write this kind of thing and have it just work.
while (a)
{
ctx: while(b)
{
while (c)
{
if(d) break ctx;
...
}
}
...
}
Perhaps I'm just confused about C++ versions but I get this kind of error in g++:
error: expected ‘;’ before ‘ctx’
break ctx;
error: ‘ctx’ was not declared in this scope
warning: label ‘ctx’ defined but not used [-Wunused-label]
ctx:
C++ appears to refuse letting me write this code.
C++ has added lambdas/closures that potentially would let me do this but I'm not quite sure how they would work in this case.
Using try throw catch is the closest construct I can think of that produces this behavior but the sloppiness of using an error system when none should be needed concerns me (Also they are slow I hear).
I'm tempted to just wrap it in extern C except I'm relying on c++ library's completely for the entire project so this also feels sloppy.
Is a try block or just rewriting my only options?
Neither C nor C++ have a labelled break statement (You're probably using a language extension, rather than standard C).
Instead, you can use goto to break out of a nested loop.
while (a)
{
while(b)
{
while (c)
{
if(d)
goto break_b;
}
}
break_b:
// ...
}
I was able to use goto to solve this... I though it was a banned construct in c++?
No. goto is not "banned" in C++.
This is a completely fine way to use goto. There doesn't exist an equivalent structured control statement.
lambdas/closures [...] potentially would let me do this but I'm not quite sure how they would work in this case.
If you are allergic to goto, then you can indeed use a lambda, but I don't see it providing any additional readability:
while (a)
{
[&](){
while(b)
{
while (c)
{
if(d)
return;
}
}
}();
// ...
}
Instead of a lambda, you can use a named function. But in that case you need to pass any variables (such as b, c and d) as arguments (assuming they're not globals).
Yet another way is an extra variable:
while (a)
{
bool break_b = false;
while(b)
{
while (c)
{
if(d) {
break_b = true;
break;
}
}
if (break_b)
break;
}
// ...
}
Of these three methods, I recommend goto, since it's the most readable. Except in the case the actual inner loop omitted from the example is very long, in which case a separate function might be better.
As has already been pointed out by others, goto would be a way to do exactly what you're asking for.
That being said, I would argue that, before asking the question of how to break out of a massively-complicated control flow structure, you should first ask yourself why there is a massively-complicated flow structure to begin with. What is going on in these loops? Should whatever is going on in each of these loops not better be moved into its own function? For example, instead of
while (a)
{
ctx: while (b)
{
while (c)
{
if (d) goto ctx;
…
}
}
…
}
why not
bool doC()
{
while (c)
{
if (d)
return false;
…
}
return true;
}
void doB()
{
while (b && doC());
}
and then
while (a)
{
doB();
…
}
Replacing the break with a goto here is not advisable. There can be issues wrt constructors and destructors not being called correctly. Whilst goto still exists in C++, it's really not something you want to use unless you really know what you're doing! A safer option would be to use a try-catch block. A better approach would be to re-factor your algorithm (currently it's O(N^3), which should really be ringing some alarm bells!)
while (a)
{
try
{
while(b)
{
while (c)
{
if(d) throw;
}
}
}
catch(...)
{
}
}
I tried to custom Scoping like this:
In the file MyDslScopeProvider that extends AbstractMyDslScopeProvider,
I implemented the function with this signature:
override def IScope getScope(EObject context, EReference reference)
and I used cases like this
if (reference == SpectraPackage.Literals.SOMETHING__POINTER)
but I have function in my grammar that it's have parameters and we can declare inside local vars. I don't want that those local vars and the parameters of that function would be visible from the outside, I want them to be visible only inside the function so I did something like this:
if (contextDecl instanceof function) {
val fun= contextDecl as function
val allContentsCurrFile = EcoreUtil2.getAllContentsOfType(fun,Constant)
EObjectsInScope.addAll(fun.params)
EObjectsInScope.addAll(allContentsCurrFile)
return Scopes.scopeFor(EObjectsInScope)
}
else{
val removeEobjects = newArrayList()
EObjectsInScope.addAll(EcoreUtil2.getAllContentsOfType(root,EObject))
val funList= EcoreUtil2.getAllContentsOfType(root,function) as List<function>
for(function f: funList){
removeEobjects.addAll(f.varDeclList)
removeEobjects.addAll(f.params.params)
removeEobjects.addAll(EcoreUtil2.getAllContentsOfType(f,Constant))
}
EObjectsInScope.removeAll(removeEobjects)
return Scopes.scopeFor(EObjectsInScope)
This is very un-efficient to get all the EObjects and to remove the vars that I don't want to be visible from the outside (it's taking a lot of time).
There is a way to do this more efficient?
Thanks.
EDIT: You might also be interested in my answer to "Xtext: IResourceScopeCache for Avoid expensive scope calculation"
First of all, if you are talking about local variables, you probably don't want to allow using local variables before they are declared, e.g.
function foo() {
x = x + 1;
int x = 0;
}
So you are actually doing too much work by using getAllContentsOfType().
What exactly are you trying to achieve using your optimizations? Better performance for content assist inside a function? Better speed for large number of models with small functions bodies? Better speed for many large functions?
Keep in mind to avoid premature optimization - it is more important to keep your code maintainable, and optimize for speed only if it doesn't scale to the workloads you actually need to handle. Did you use a profiler to find Hotspots? Human intuition can be pretty wrong when it comes to performance bottlenecks.
Anyway, under the assumption that you need to improve speed of scoping but you don't have massive workloads, as a first shot, I'd suggest using a TreeIterator to traverse the function body collecting the local variables that should be visible, and, using the return value of EcoreUtil2.getAllContainers(context) as a guide when to use prune() and when to use next().
I.e.
import static extension org.eclipse.xtext.EcoreUtil2.*
// ...
val predecessors = new ArrayList<EObject>
val iterator = EcoreUtils.getAllContents(function, true)
// Could be optimized further
val descentGuide = context.allContainers.dropWhile[it != function].toList.reverseView.iterator
var current = iterator.next
var nextDescent = descentGuide.next
while(current != context) {
// collect list with local variables here
predecessors += current
if(current == nextDescent) {
// Reached another ancestor of context - will look for the following ancestor next
nextDescent = descentGuide.next
} else {
iterator.prune
}
current = iterator.next
}
// Reverse so innermost declarations shadow outer declarations
val localVariables = predecessors.filter(LocalVariableDeclaration).toList.reverseView
I didn't compile/test the code, but I hope the idea becomes clear.
The while loop should terminate in the end because at some point, context will be reached -- but to be more robust it might make sense to add && iterator.hasNext to the while loop.
Let's say you have a function in C/C++, that behaves a certain way the first time it runs. And then, all other times it behaves another way (see below for example). After it runs the first time, the if statement becomes redundant and could be optimized away if speed is important. Is there any way to make this optimization?
bool val = true;
void function1() {
if (val == true) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
gcc has a builtin function that let you inform the implementation about branch prediction:
__builtin_expect
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
For example in your case:
bool val = true;
void function1()
{
if (__builtin_expect(val, 0)) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
You should only make the change if you're certain that it truly is a bottleneck. With branch-prediction, the if statement is probably instant, since it's a very predictable pattern.
That said, you can use callbacks:
#include <iostream>
using namespace std;
typedef void (*FunPtr) (void);
FunPtr method;
void subsequentRun()
{
std::cout << "subsequent call" << std::endl;
}
void firstRun()
{
std::cout << "first run" << std::endl;
method = subsequentRun;
}
int main()
{
method = firstRun;
method();
method();
method();
}
produces the output:
first run subsequent call subsequent call
You could use a function pointer but then it will require an indirect call in any case:
void (*yourFunction)(void) = &firstCall;
void firstCall() {
..
yourFunction = &otherCalls;
}
void otherCalls() {
..
}
void main()
{
yourFunction();
}
One possible method is to compile two different versions of the function (this can be done from a single function in the source with templates), and use a function pointer or object to decide at runtime. However, the pointer overhead will likely outweigh any potential gains unless your function is really expensive.
You could use a static member variable instead of a global variable..
Or, if the code you're running the first time changes something for all future uses (eg, opening a file?), you could use that change as a check to determine whether or not to run the code (ie, check if the file is open). This would save you the extra variable. Also, it might help with error checking - if for some reason the initial change is be unchanged by another operation (eg, the file is on removable media that is removed improperly), your check could try to re-do the change.
A compiler can only optimize what is known at compile time.
In your case, the value of val is only known at runtime, so it can't be optimized.
The if test is very quick, you shouldn't worry about optimizing it.
If you'd like to make the code a little bit cleaner you could make the variable local to the function using static:
void function() {
static bool firstRun = true;
if (firstRun) {
firstRun = false;
...
}
else {
...
}
}
On entering the function for the first time, firstRun would be true, and it would persist so each time the function is called, the firstRun variable will be the same instance as the ones before it (and will be false each subsequent time).
This could be used well with #ouah's solution.
Compilers like g++ (and I'm sure msvc) support generating profile data upon a first run, then using that data to better guess what branches are most likely to be followed, and optimizing accordingly. If you're using gcc, look at the -fprofile-generate option.
The expected behavior is that the compiler will optimize that if statement such that the else will be ordered first, thus avoiding the jmp operation on all your subsequent calls, making it pretty much as fast as if it wern't there, especially if you return somewhere in that else (thus avoiding having to jump past the 'if' statements)
One way to make this optimization is to split the function in two. Instead of:
void function1()
{
if (val == true) {
// do something
val = false;
} else {
// do other stuff
}
}
Do this:
void function1()
{
// do something
}
void function2()
{
// do other stuff
}
One thing you can do is put the logic into the constructor of an object, which is then defined static. If such a static object occurs in a block scope, the constructor is run the fist time that an execution of that scope takes place. The once-only check is emitted by the compiler.
You can also put static objects at file scope, and then they are initialized before main is called.
I'm giving this answer because perhaps you're not making effective use of C++ classes.
(Regarding C/C++, there is no such language. There is C and there is C++. Are you working in C that has to also compile as C++ (sometimes called, unofficially, "Clean C"), or are you really working in C++?)
What is "Clean C" and how does it differ from standard C?
To remain compiler INDEPENDENT you can code the parts of if() in one function and else{} in another. almost all compilers optimize the if() else{} - so, once the most LIKELY being the else{} - hence code the occasional executable code in if() and the rest in a separate function that's called in else
I think many of you have this kind of code somewhere:
int foo;
switch (bar) {
case SOMETHING: foo = 5; break;
case STHNELSE: foo = 10; break;
...
}
But this code has some drawbacks:
You can easily forget a "break"
The foo variable is not const while it should be
It's just not beautiful
So I started wondering if there was a way to "improve" this kind of code, and I got this little idea:
const int foo = [&]() -> int {
switch (bar) {
case SOMETHING: return 5;
case STHNELSE: return 10;
...
}
}();
Note: the first pair of parentheses it not mandatory, but MSVC++ doesn't support this yet
You can use the same trick with if-else where the ternary operator would be too complicated, variables that require to be passed by pointers to be initialized (like for DirectX functions), etc.
My questions are:
Is there anything wrong with this code that I didn't see?
Do you find it better than the one above?
g++ seems to inline the function, but do you think that all compilers will do so?
EDIT: this is what I mean by "DirectX functions"
_xAudio2 = [&]() -> std::shared_ptr<IXAudio2> {
IXAudio2* ptr = nullptr;
if (FAILED(XAudio2Create(&ptr, xAudioFlags, XAUDIO2_DEFAULT_PROCESSOR)))
throw std::runtime_error("XAudio2Create failed");
return std::shared_ptr<IXAudio2>(ptr, [](IUnknown* ptr) { ptr->Release(); });
}();
This is a fairly common technique in other languages. Almost every high-level feature of Scheme is defined in terms of lambdas that are immediately called.
In JavaScript it is the basis of the "module pattern", e.g.
var myModule = (function() {
// declare variables and functions (which will be "private")
return {
// populate this object literal with "public" functions
};
})();
So an anonymous function is declared and immediately called, so that any internal details are hidden and only the return value is exposed externally.
The only downsides is that on a casual reading of the code, the return statements will appear to be returning from the outer function (there was intense controversy about this during the Java lambda wars). But this is just something you have to get used to once your language has lambdas.
There are many language features in an imperative language like C++ which would benefit from being able to return a value (rather than being like a void function). For example, if has an alternative, the tertiary operator expr ? a : b.
In Ruby pretty much all statements can be evaluated, so there is no need for a separate syntax where a return value can be supplied. If C++ worked that way, this would mean things like:
auto result = try
{
getIntegerSomehow();
}
catch (const SomeException &)
{
0;
}
I don't see any reason at all to use a switch case in such a case. Any decent compiler will generate just as fast code with if statements as with a switch case.
if(bar == SOMETHING)
foo = 5;
else if(bar == STHNELSE)
foo = 10;