How to align a designated initializer in C99 with clang-format? - clang-format

I am using clang-format 4.0.0 to align a personal project of mine.
I am using the following configurations for clang-format.
Language: Cpp
BreakBeforeBraces: Allman
ColumnLimit: 120
TabWidth: 4
IndentWidth: 4
UseTab: ForContinuationAndIndentation
The sample code below is aligned using the above configuration.
struct test
{
int a;
int b;
int c;
};
struct test T = {
.a = 1, .b = 2, .c = 3,
};
Is there any way to align the initialization part like the one shown below.
Basically I am looking for a way to place all the initializers in separate lines.
struct test T =
{
.a = 1,
.b = 2,
.c = 3,
};

Using clang-format 6.0.0, the formatting is what you ask for. In fact, there no longer seems to be any way to get the single-line formatting that you don't like.

Related

Correct function to parse a ansistring

I'm using C++ Builder Berlin Community edition.
I want to parse a string such as "1234' into a integer array such as N[1] = 1, N[2] = 2, ... .
I've tried using SubString(str, #, #), StrMove(str, #, #), Copy(str, #, #).
They all return "function not found". I've been developing code for over years now, so I know I am not including the correct header (either .h, or .hpp) file in my include statements, or the programmers at Embarcadero in their wisdom have modified C++ Builder to make these functions obsolete.
int Lock;
AnsiString N_Str;
randomize();
Lock = rand() * 1000;
N_Str = AnsiString(Lock);
L[0] = StrToInt(StrMove(N_Str, 1, 1));
L[1] = StrToInt(SubString(N_Str, 2, 1));
L[2] = StrToInt(copy(N_Str, 3, 1));
L[3] = StrToInt(copy(N_Str, 4, 1));

Clang-format struct initialization - indent with two spaces?

I'm trying to format a C file with clang-format. I want indentations to be two space characters, which mostly works except for in global variable struct initialization. For this, it continues to produce lines which are indented with four spaces.
Here is my .clang-format file
BasedOnStyle: LLVM
ColumnLimit: '80'
IndentWidth: '2'
clang-format produces this surprising output
typedef struct {
int x;
} foo;
static foo bar{
1, // This line is being indented with 4 spaces!
};
And this is what I'd expect the file to look like:
typedef struct {
int x;
} foo;
static foo bar{
1, // This line is being indented with 2 spaces!
};
I've tried using a few different values for ConstructorInitializerIndentWidth, but that field doesn't appear to affect this pattern.
Is there a setting that I could provide to get this behavior?
Try ContinuationIndentWidth: 2. That worked for me, when I had that problem.

OpenCV detect and compute image features

Recently upgraded OpenCV from 3.4.5. to OpenCV 4.2.0.
Before I followed this stitching example: https://github.com/opencv/opencv/blob/5131619a1a4d1d3a860b5da431742cc6be945332/samples/cpp/stitching_detailed.cpp (particularly line 480). After upgrading, I altered the code to align more with this newer example: https://github.com/opencv/opencv/blob/master/samples/cpp/stitching_detailed.cpp (Note line 481).
Problem is with this new computeImageFeatures function, I am getting less detected features. Older code with same images gave me 1400+ features but computeImageFeatures gave me exactly 500 features per image. Any ideas how to "fix" this? I believe it also causes the "Bundle Adjuster" to fail later.
According to documentation of cv::ORB::create, default value of nfeatures argument is 500:
The first argument is nfeatures, you may set the first argument to grater number like 2000.
Here are the constructor arguments:
static Ptr<ORB> cv::ORB::create (int nfeatures = 500,
float scaleFactor = 1.2f,
int nlevels = 8,
int edgeThreshold = 31,
int firstLevel = 0,
int WTA_K = 2,
int scoreType = ORB::HARRIS_SCORE,
int patchSize = 31,
int fastThreshold = 20
)
Try modifying:
if (features_type == "orb")
{
finder = ORB::create();
}
to
if (features_type == "orb")
{
finder = ORB::create(2000);
}
In case you are not using ORB, but other type of features, read the documentation of the constructor.
I assume all types has a limiter argument.

How to convert number words to int (like three to 3) using Dart

I want to convert number words (like one, two, three and so on) to int (like 1, 2, 3 etc) using Dart
You have to depend on machine learning library or pair every string with the respective number.
int convertStrToNum(String str) {
var number = <String, num>{'one': 1, ...};
return number[str];
}
Of course, machine learning might be the fastest and best way to do this, but I can't really help you there. So, here's an implementation that would work assuming the "number word" follows a certain format, up until 10. (You could implement a RegExp parser to make this easier, but that would get tricky).
int convStrToNum(String str) {
var oneten = <String, num> {
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
}
if (oneten.keys.contains(str)) {
return oneten[str];
}
}
int convStrToInt(String str) {
var list = [
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
];
return list.indexOf(str);
}
I just pushed a repo addressing this issue. It's open to open to build upon so feel free to contribute, it would really help improve the package. Heres the link https://github.com/michaelessiet/wordstonumbers.dart

How do I use the Rust parser (libsyntax) myself?

I want to use the Rust parser (libsyntax) to parse a Rust file and extract information like function names out of it. I started digging in the docs and code, so my first goal is a program that prints all function names of freestanding functions in a .rs file.
The program should expand all macros before it prints the function names, so functions declared via macro aren't missed. That's why I can't write some crappy little parser by myself to do the job.
I have to admit that I'm not yet perfectly good at programming Rust, so I apologize in advance for any stupid statements in this question.
How I understood it I need to do the following steps:
Parse the file via the Parser struct
Expand macros with MacroExpander
???
Use a Visitor to walk the AST and extract the information I need (eg. via visit_fn)
So here are my questions:
How do I use MacroExpander?
How do I walk the expanded AST with a custom visitor?
I had the idea of using a custom lint check instead of a fully fledged parser. I'm investigating this option.
If it matters, I'm using rustc 0.13.0-nightly (f168c12c5 2014-10-25 20:57:10 +0000)
You can use syntex to parse Rust, so you don't need to use unstable Rust.
Here's a simple example:
// Tested against syntex_syntax v0.33
extern crate syntex_syntax as syntax;
use std::rc::Rc;
use syntax::codemap::{CodeMap};
use syntax::errors::{Handler};
use syntax::errors::emitter::{ColorConfig};
use syntax::parse::{self, ParseSess};
fn main() {
let codemap = Rc::new(CodeMap::new());
let tty_handler =
Handler::with_tty_emitter(ColorConfig::Auto, None, true, false, codemap.clone());
let parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
let src = "fn foo(x: i64) { let y = x + 1; return y; }".to_owned();
let result = parse::parse_crate_from_source_str(String::new(), src, Vec::new(), &parse_session);
println!("parse result: {:?}", result);
}
This prints the whole AST:
parse result: Ok(Crate { module: Mod { inner: Span { lo: BytePos(0), hi: BytePos(43), expn_id: ExpnId(4294967295) },
items: [Item { ident: foo#0, attrs: [], id: 4294967295, node: Fn(FnDecl { inputs: [Arg { ty: type(i64), pat:
pat(4294967295: x), id: 4294967295 }], output: Default(Span { lo: BytePos(15), hi: BytePos(15), expn_id: ExpnId(4294967295) }),
variadic: false }, Normal, NotConst, Rust, Generics { lifetimes: [], ty_params: [], where_clause: WhereClause { id:
4294967295, predicates: [] } }, Block { stmts: [stmt(4294967295: let y = x + 1;), stmt(4294967295: return y;)], expr:
None, id: 4294967295, rules: Default, span: Span { lo: BytePos(15), hi: BytePos(43), expn_id: ExpnId(4294967295) } }),
vis: Inherited, span: Span { lo: BytePos(0), hi: BytePos(43), expn_id: ExpnId(4294967295) } }] }, attrs: [], config: [],
span: Span { lo: BytePos(0), hi: BytePos(42), expn_id: ExpnId(4294967295) }, exported_macros: [] })
I'm afraid I can't answer your question directly; but I can present an alternative that might help.
If all you need is the AST, you can retrieve it in JSON format using rustc -Z ast-json. Then use your favorite language (Python is great) to process the output.
You can also get pretty-printed source using rustc --pretty=(expanded|normal|typed).
For example, given this hello.rs:
fn main() {
println!("hello world");
}
We get:
$ rustc -Z ast-json hello.rs
{"module":{"inner":null,"view_items":[{"node":{"va... (etc.)
$ rustc --pretty=normal hello.rs
#![no_std]
#[macro_use]
extern crate "std" as std;
#[prelude_import]
use std::prelude::v1::*;
fn main() { println!("hello world"); }
$ rustc --pretty=expanded hello.rs
#![no_std]
#[macro_use]
extern crate "std" as std;
#[prelude_import]
use std::prelude::v1::*;
fn main() {
::std::io::stdio::println_args(::std::fmt::Arguments::new({
#[inline]
#[allow(dead_code)]
static __STATIC_FMTSTR:
&'static [&'static str]
=
&["hello world"];
__STATIC_FMTSTR
},
&match () {
() => [],
}));
}
If you need more than that though, a lint plugin would be the best option. Properly handling macro expansion, config flags, the module system, and anything else that comes up is quite non-trivial. With a lint plugin, you get the type-checked AST right away without fuss. Cargo supports compiler plugins too, so your tool will fit nicely into other people's projects.
The syn crate works indeed. At the beginning I wrongly think it is for writing procedural macros (as its readme suggests), but indeed it can parse a source code file. Please look at this page: https://docs.rs/syn/1.0.77/syn/struct.File.html . It even gives an example that inputs a .rs file and output AST (of course, you can do anything with it - not just printing):
use std::env;
use std::fs::File;
use std::io::Read;
use std::process;
fn main() {
let mut args = env::args();
let _ = args.next(); // executable name
let filename = match (args.next(), args.next()) {
(Some(filename), None) => filename,
_ => {
eprintln!("Usage: dump-syntax path/to/filename.rs");
process::exit(1);
}
};
let mut file = File::open(&filename).expect("Unable to open file");
let mut src = String::new();
file.read_to_string(&mut src).expect("Unable to read file");
let syntax = syn::parse_file(&src).expect("Unable to parse file");
// Debug impl is available if Syn is built with "extra-traits" feature.
println!("{:#?}", syntax);
}
Thanks #poolie for pointing out this hint (though lacking a bit of details).
syntex seems to no longer be maintained (last updated 2017), but https://crates.io/crates/syn may do what you need.

Resources