If I have
class A
{
int a;
int b;
}
Is there a way for resharper to reformat this code on "code cleanup" action to the following?
class A
{
int a, b;
}
There is no way to do it in ReSharper because this is considered a bad style. See Why do you not declare several variables of the same type on the same line? and Declaring Multiple Variables in JavaScript
Related
Following code in MSVC generates warning about assignment in conditional expression.
https://godbolt.org/z/i_rwY9
int main()
{
int a;
if ((a = 5)) {
return 1;
}
return a;
}
Note that I tried to use the double () around if since that makes the warning go away with g++, but I do not know how to make it go away in msvc without extracting the assignment from condition.
Is there a way to nudge msvc to figure out that this assignment is intentional?
I know I can use pragmas to disable this warning, but pattern is very common so I would like to get a solution without pragmas if one exists.
The MSVC compiler will give this warning unless you can convince it that you really do know what you're doing. Adding at least one 'real' logical test will achieve this:
int main()
{
int a;
if ((a = 5) != 0) {
return 1;
}
return a;
}
Note that the constant 5 can readily be replaced with any variable or valid expression: adding the explicit != 0 test does nothing to actually change the outcome of the code (and it is unlikely to change the generated assembly).
I am working on a research project that an Alloy generated instance holds entities (such as Signatures, Fields, Relations or Tuples) that resemble a programming language (such as java, c, etc).
For example, there are entities for Arithmetic operations (such as Add, Sub, Multiply, etc), for Relational operations (such equals, greater than, less than or equal, etc.) for variables, constants, and so on.
A tree view and graph view examples (max of two integers algorithm) of the model solution (instance found) are showing next. Those figures were extracted from Alloy Analyzer GUI.
My question is there a quick way to convert that alloy instance to any common language source code (Java would be the preferred language)?
Or should I do everything (Sigs, Fields, Atoms, language brackets, indentation, etc) by starting this way (going through an A4Solution) to build a kind of translator?
The main goal here is to build a Java program that is able to convert an Alloy instance to a Java source code file ready to compile and run.
//max of 2 integers' java source code at mymax2.java file
class MyMax2 {
public static void main(String[] args) {
int x;
int y;
int res;
if(y <= X) {
res = x;
} else {
res = y;
}
}
}
Finally, convert from XML to Java, by starting this way is not a desired option.
Thank you for help me on :)
Yours is really a formatted printing problem, with a tree as the data input. The tree is roughly an Abstract Syntax Tree (AST).
Do a post-order transversal of the tree, adding in the sensible text to each node as you travel back up the tree.
This means your "text for the node" function will look like a visitor, with lots of "policies" for each node type; however, there will be some wrinkles to address when it comes to variable scoping. Basically, the position of the declaration seems to be lost in your AST, and so you will have to write some code to cache the variable names in play, and define them in the upper blocks.
Since it might be ambiguous which block you would "unroll" your "variables to be declared" as you collapse your tree from the bottom up, your code will not be 100% identical to the input code. For example
public static void main(String[] args) {
int x;
if (x > 3) {
int y = 3 + x;
return x + y;
} else {
return 4;
}
}
might (after a full round trip of being converted to AST and back) read as
public static void main(String[] args) {
int x;
int y;
if (x > 3) {
y = 3 + x;
return x + y;
} else {
return 4;
}
}
Also, this assumes your AST has a pretty tight fit to the target programming language. For example, if you wanted to convert the presented AST to Prolog; you would quickly find out that the constructs in your AST are a poor fit for Prolog generation.
Should you need some direction, look into Pretty Printers which leverage most of the components of a compiler, with the exception that after they have their AST, they process it back out as source code.
There are a few wrinkles, but nothing too severe (provided your AST isn't missing a critical piece of information for the reverse back to source code).
So I have the following code in bool_struct.sv:
typedef enum {false=0, true=1} bool;
class my_bool_class;
bool my_bool_value;
function new (bool initial_bool_value)
my_bool_value = initial_bool_value;
endfunction
endclass
In checker.sv I want to do the following:
class checker;
my_bool_class bool_class_handle = new(true)
endclass
My question is, will this compile? I imagine the "true" in the new call will be out of the scope of the typedef so it will not. How do I get that "true" in the new call to work?
A typedef for an enumerated type declares all the labels as well as the enumeration at the same level (That is why you cannot declare two different enumerations with overlapping labels in the same scope).
What you should always do is put typedefs and class declarations in a package and then import the package where you want to use bool, false, true, and my_bool.
See http://go.mentor.com/package-import-versus-include
I was trying to make a simple struct to hold character stats.
This is what I came up with:
struct cStats
{
int nStrength;
int nIntelligence;
int nMedical;
int nSpeech;
int nAim;
};
cStats mainchar;
mainchar.nStrength = 10;
mainchar.nIntelligence = 10;
mainchar.nMedical = 10;
mainchar.nSpeech = 10;
mainchar.nAim = 10;
The mainchar. part is underlined red in visual studio, and when I mouse over it it shows this:
Error: this declaration has no storage class or type specifier
Any explanation of why it's doing this, and what I should be doing to fix it would be appreciated.
If this is C you should tag your question as such. cStats is a structure tag, not a type specifier. You need to declare mainchar as:
struct cStats mainchar;
If you wanted to use cStats as a type specifier you would define it as:
typedef struct
{
int nStrength;
int nIntelligence;
int nMedical;
int nSpeech;
int nAim;
} cStats;
If you did that your cStats mainchar would work.
Note that in C, char and character mean “ASCII alphanumeric character”, not “character in a play or game”. I suggest coming up with a different term for your program.
Another bit of advice; do not prefix your names with their data type; like nStrength for integer Strength. The compiler will tell you if you get your data types wrong, and if you ever need to change a type, for example to float nStrength to handle fractional Strengths, changing the name will be a big problem.
main(){
mainchar.nStrength = 10;
mainchar.nIntelligence = 10;
mainchar.nMedical = 10;
mainchar.nSpeech = 10;
mainchar.nAim = 10;}
These initialization should be written within the main() function.
Or else, write a init function and call it from main function.
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()
{
}