Clang formatting rule to add an empty line before the closing brace of a struct or class? - clang-format

I am unable to find a documented way to add an empty line to the end of a class or struct declaration. Is there a way for clang-format to convert this:
struct foo {
int bar = 0;
};
To this
struct foo {
int bar = 0;
};
And optionally having the ability to add a line to the beginning would be nice as well:
struct foo {
int bar = 0;
};

I have found the same problem recently. To add a new line between the class declaration and contents, set KeepEmptyLinesAtTheStartOfBlocks to Yes.
However, it seems that there is not option to enforce an empty line between last declaration or definition and closing braces.

Related

How do I initialize non-nullable members in a constructor body?

I've created my class in Dart this way, but I'm getting the Non-nullable instance field 'text' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'. I would like to know if there's a way to do it in a 'Python' style where this kind of class creation is possible, thank you in advance.
class Lexer {
String _text;
int _pos;
String _current_char;
Lexer(String text) {
this._text = text;
this._pos = -1;
this._current_char = '';
this.advance();
}
void advance() {
this._pos++;
this._current_char = this._pos < this._text.length ? this._text[this._pos] : '';
}
}
class Lexer {
String _text;
int _pos;
String _current_char;
This declares several members with type String. Since they are declared as String and not as String?, these members are non-nullable; they are not allowed to ever be null. (This is part of the new null-safety feature from Dart 2.12.)
Dart initializes objects in two phases. When the constructor's body runs, Dart expects all member variables to already be initialized. Because your members are non-nullable and haven't been initialized to non-null values yet, this is an error. The error message explains what you can do:
Non-nullable instance field 'text' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.
Use initializer expressions. This means using an initializer list:
Lexer(String text)
: _text = text,
_pos = -1,
_current_char = '' {
advance();
}
Note that if you're initializing members with a construction parameter of the same name, you can use shorthand:
Lexer(this._text)
: _pos = -1,
_current_char = '' {
advance();
}
Adding field initializers. This means initializing members inline in the class declaration.
class Lexer {
String _text = '';
int _pos = -1,
String _current_char = '';
Marking your members as late. This means that you promise that the variables will be initialized before anything attempts to use them.
class Lexer {
late String _text;
late int _pos,
late String _current_char;
Making your members nullable, which allows them to be implicitly null by default:
class Lexer {
String? _text;
int? _pos,
String? _current_char;
However, that will require that all accesses explicitly check that the members aren't null before using them.
You also might want to read: Dart assigning to variable right away or in constructor?

What is the use of constant values in dart?

As described in the documentations:
The const keyword isn’t just for declaring constant variables. You can also use it to create constant values, as well as to declare constructors that create constant values. Any variable can have a constant value.
Can someone explain the use of constant values?
This is a simple example which I hope explains clearly:
Start with two variables and a constant.
var foo = [10,11];
var bar = const [20,21];
const baz = [30,31];
Try to modify foo and it succeeds.
foo.add(12); // [10,11,12]
Try to similarly modify bar and there's an error, because even though bar is a variable, its value was declared to be a constant, thus is immutable.
bar.add(22); // ERROR!
Try to reassign bar to a different value. That works since bar itself was not declared as a constant.
bar = [40,41];
Now, try to modify bar's value again and this time it works, since its new value is not a constant.
bar.add(42) // [40,41,42]
Try to modify baz and there's an error, since baz being declared as a constant itself, its value is inherently immutable.
baz.add(32); // ERROR!
Try reassigning baz to a new value and it fails because baz is a constant and can't be reassigned to a new value.
baz = [50,51]; // ERROR!
void main() {
simpleUse();
finalUse();
constUse();
}
simpleUse() {
print("\nsimple declaration");
var x = [10];
print('before: $x');
x = [5];//changing reference allowed
x.add(10);//changing content allowed
print('after: $x');
}
finalUse() {
print("\nfinal declaration");
final x = [10];
print('before: $x');
// x = [10,20]; //nope changing reference is not allowed for final declaration
x.add(20); //changing content is allowed
print('after: $x');
}
constUse() {
print("\nconst declaration");
const x = [10];
print('before: $x');
// x = [10,20]; //nope -> changing reference is not allowed for final declaration
// x.add(20);//nope -> changing content is not allowed
print('after: $x');
}
Also, variables are simple values like x = 10;
values are instances of enums, list, maps, classes, etc.
I want to add, that another point for const is to guarantee your get the same instance of the object each time you construct it with the same parameters:
class Test {
final int value;
const Test(this.value);
}
void main() {
print(Test(5).hashCode == Test(5).hashCode); // false
print((const Test(5)).hashCode == (const Test(5)).hashCode); // true
}
This is the reason why the const constructor can be difficult to make for all objects since your need to make sure the object can be constructed on compile-time. Also, why after creation of the object no internal state can be changed as the previous answer also shows.

static const - top level of program does not allow static const - Dart

I have looked at some other similar questions on SO, but they don't appear to address the following specifically.
What I want to achieve is to have compile-time constants that cannot be altered.
I have a program which I reorganized a little in order to de-clutter. The program had some const declarations prior to "main()". I moved these to a class, however it required that I declare them as "static const". I then thought, ok those other "const" declarations prior to "main()" should probably also be "static const". However when I attempted that, the Editor advised "Top-level declarations cannot be declared to be 'static'". EG.
static const int I_CORRECT_YN = 12; // prompt nr.
So, I am a little confused. I thought that a "const" was static. Why do I have to declare "static" in the class? Why can't I declare a "top level" const as "static"? Also, what is the difference between:
static const int I_CORRECT_YN = 12;
const int I_CORRECT_YN = 12;
static final int I_CORRECT_YN = 12;
final int I_CORRECT_YN = 12; ?
What is the best or only way to declare compile-time values that cannot be altered?
I guess I am looking at the literal meaning, but I presume there is a more complex meaning.
Why do I have to declare "static" in the class?
Because instance variables/methods can't be const. This would mean their value could be different per instance, which can't be the case for compile-time constants. (Source)
Why can't I declare a "top level" const as "static"?
The static modifier marks variables/methods as class-wide (same value for every instance of the class). Top-level stuff is application-wide and doesn't belong to any class, so marking them as class-wide doesn't make any sense and is not allowed. (Source)
What is the best or only way to declare compile-time values that cannot be altered?
You are already doing it - add static when defining class constants. Don't add it when defining top-level constants. Also, use const. final vars aren't compile-time values.
What is the difference between [source code with different constant definitions omitted]
static const and const is the pretty much the same, usage depends on context.
The difference between const and final is that const are compile-time constants - they can only be initialized using literal values (or expressions constisting of operators and literal values) and can't be changed. final variables also can't be changed after being initialized, but they are basically normal variables. This means any kind of expression can be used, and the value can be a different one for every class instance:
import "dart:math";
Random r = new Random();
int getFinalValue() {
return new Random().nextInt(100);
}
class Test {
// final variable per instance.
final int FOO = getFinalValue();
// final variable per class. "const" wouldn't work here, getFinalValue() is no literal
static final int BAR = getFinalValue();
}
// final top-level variable
final int BAZ = getFinalValue();
// again, this doesn't work, because static top-level elements don't make sense
// static final int WAT = getFinalValue();
void main() {
Test a = new Test();
print(Test.BAR);
print(BAZ); // different from Test.BAR
print(a.FOO);
a = new Test();
print(Test.BAR); // same as before
print(BAZ); // same as before
print(a.FOO); // not the same as before, because it is another instance,
// initialized with another value
// but this would still be a syntax error, because the variable is final.
// a.FOO = 42;
}
I hope this helped, and I didn't descibe it too confusing. :]

Initializer must be a compile time constant

I just want have a final List with colors :
final List<String> COLORS = ['#cefbe4', '#81ec72', '#5cd646'];
final num MAX = 90;
class Square {
// ...
It's ok for MAX but it does not compile for list :
Initializer must be a compile time constant
I also tried :
static final num MAX = 90;
class Square {
final List<String> COLORS = ['#cefbe4', '#81ec72', '#5cd646'];
New error : "initializer must be a compile time constant"
The only solution, I found is to initialise in constructor...
I don't like this solution : I don't want a list instance by Square object.
How can I do ?
I don't get the same errors as you. In the first case I get a compile time warning "Expected constant expression" and in the second case another compile-time warning and a runtime error. Try the latest SDK which you can find here.
static final num MAX = 90;
class Square {
final List<String> COLORS = ['#cefbe4', '#81ec72', '#5cd646'];
In this case static it doesn't make any sense because static denotes class variables which are the same for all instantiated objects of the same class. And in this case MAX is outside a class boundary. Hence a runtime error is shown and a compile time warning ("Top-level field cannot be static").
I guess both MAX and COLORS are supposed to be the same for all instances of the Square class. So it makes sense to do this:
class Square {
static final List<String> COLORS = const ['#cefbe4', '#81ec72', '#5cd646'];
static final num MAX = 90;
}
The list itself is the part that is final, not the contents. The contents inside a final list can still be added and removed.
final List<String> COLOURS = new ArrayList<String>();
This would create your list. The actual filling of the list would be done in the constructor, or for that matter anywhere in your code.
It would be more appropriate to use an enum for this in my opinion.

Extending Aero Glass in F# (PInvoke)

I'm working on a F# console application. In the properties I set the output type of application to Windows Application to hide the console. I also created a form to run in its place. Currently I only have a simple form with no controls. To make the form I added referances to System.Windows.Forms and System.Drawing and opened them along with System.Runtime.InteropServices.
The part that I don't know how to do is extending the aero-glass. There are loads of exaples on how to do it in C#. For example, here is the API call and MARGINS structure:
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
[DllImport("dwmapi.dll")]
pubic static extend int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
The API call from Form_Load event:
MARGINS margins = new MARGINS();
margins.cxLeftWidth = 0;
margins.cxRightWidth = 100;
margins.cyTopHeight = 0;
margins.cyBottomHeight = 0;
int result = DwmExtendFrameIntoClientArea(this.Handle, ref margins);
This is what I've got so far in F#:
The API call and MARGINS structure:
[<StructLayout(LayoutKind.Sequential)>]
type MARGINS =
struct
val cxLeftWidth : int
val cxRightWidth : int
val cyTopHeight : int
val cyBottomHeigh t: int
new(left, right, top, bottom) = { cxLeftWidth = left; cxRightWidth = right; cyTopHeight = top; cyBottomHeigh = bottom } (*Is there any other way to do this?*)
end
[<DllImport("dwmapi.dll")>]
extend int DwmExtendFrameIntoClientArea(IntPtr hWnd, (*I need help here*))
The API call from Form_Load event:
let margins = new MARGINS(0, 100, 0, 0); (*Is there any other way to do this?*)
let result : int = DwmExtendFrameIntoClientArea(this.Handle, (*I need help here*))
I have been searching around but I can't find anything about using ref parameters like this in F#. I know this would be a lot easier to write in C# but the code behind the form will be easier to write int F# because it's a functional programing language and the whole program I'm writing is orientated around functions. I know this is purely decorative but please help.
In general, extern (AKA P/Invoke or platform invoke) definitions in F# use C-like syntax (and note that it's extern, not extend):
[<DllImport("dwmapi.dll")>]
extern int DwmExtendFrameIntoClientArea(nativeint hWnd, MARGINS& pMarInset)
This can then be used as follows:
let mutable margin = ...
let result = DwmExtendFrameIntoClientArea(this.Handle, &margin)
Note that the way that you have defined MARGINS is not quite analogous to the C# definition. The various val definitions are not mutable, and are actually properties rather than fields (though they're backed by fields, so it's probably not a big deal). If you want them to be mutable fields, you can add the mutable keyword after val for each field:
[<Struct; StructLayout(LayoutKind.Sequential)>]
type MARGINS =
val mutable cxLeftWidth : int
val mutable cxRightWidth : int
val mutable cyTopHeight : int
val mutable cyBottomHeight: int
(I've also used the Struct attribute instead of struct ... end, but that's just for brevity). You can initialize this like you do in C#, or using F#'s named arguments:
let mutable margin = MARGINS(cxRightWidth = 100)

Resources