fmt: reset const field align after multi line exprs (#9916)

pull/9908/head^2
Lukas Neubert 2021-04-29 01:17:37 +02:00 committed by GitHub
parent c82c8059cf
commit dee733aae4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 101 additions and 53 deletions

View File

@ -11,17 +11,17 @@ import vhelp
import v.vmod import v.vmod
const ( const (
default_vpm_server_urls = ['https://vpm.vlang.io'] default_vpm_server_urls = ['https://vpm.vlang.io']
valid_vpm_commands = ['help', 'search', 'install', 'update', 'upgrade', 'outdated', valid_vpm_commands = ['help', 'search', 'install', 'update', 'upgrade', 'outdated',
'list', 'remove'] 'list', 'remove']
excluded_dirs = ['cache', 'vlib'] excluded_dirs = ['cache', 'vlib']
supported_vcs_systems = ['git', 'hg'] supported_vcs_systems = ['git', 'hg']
supported_vcs_folders = ['.git', '.hg'] supported_vcs_folders = ['.git', '.hg']
supported_vcs_update_cmds = map{ supported_vcs_update_cmds = map{
'git': 'git pull' 'git': 'git pull'
'hg': 'hg pull --update' 'hg': 'hg pull --update'
} }
supported_vcs_install_cmds = map{ supported_vcs_install_cmds = map{
'git': 'git clone --depth=1' 'git': 'git clone --depth=1'
'hg': 'hg clone' 'hg': 'hg clone'
} }

View File

@ -37,9 +37,9 @@ const (
'vlib/v/tests/generics_test.v', /* multi_generic_args<Foo<int>, Foo<int> >(...) becomes .... Foo<int>>(...) which does not parse */ 'vlib/v/tests/generics_test.v', /* multi_generic_args<Foo<int>, Foo<int> >(...) becomes .... Foo<int>>(...) which does not parse */
'vlib/v/tests/string_interpolation_test.v' /* TODO byteptr: &byte.str() behaves differently than byteptr.str() */, 'vlib/v/tests/string_interpolation_test.v' /* TODO byteptr: &byte.str() behaves differently than byteptr.str() */,
'vlib/v/gen/js/tests/js.v', /* local `hello` fn, gets replaced with module `hello` aliased as `hl` */ 'vlib/v/gen/js/tests/js.v', /* local `hello` fn, gets replaced with module `hello` aliased as `hl` */
'vlib/v/gen/c/cheaders.v' /* the preprocessor directives are formated to the V standard, even though they are in a string literal */,
'examples/c_interop_wkhtmltopdf.v', /* &charptr --> &&char */ 'examples/c_interop_wkhtmltopdf.v', /* &charptr --> &&char */
'examples/path_tracing.v', /* block --> line comments corrupts code */ 'examples/path_tracing.v', /* block --> line comments corrupts code */
'vlib/v/gen/c/cheaders.v' /* infix wrapping error */,
] ]
vfmt_verify_list = [ vfmt_verify_list = [
'cmd/', 'cmd/',

View File

@ -1946,7 +1946,7 @@ const (
b: 0 b: 0
} }
// evaluate function call at compile-time* // evaluate function call at compile-time*
blue = rgb(0, 0, 255) blue = rgb(0, 0, 255)
) )
println(numbers) println(numbers)

View File

@ -12,7 +12,7 @@ const (
) )
const ( const (
text = ' text = '
Once upon a midnight dreary, while I pondered, weak and weary, Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore Over many a quaint and curious volume of forgotten lore
While I nodded, nearly napping, suddenly there came a tapping, While I nodded, nearly napping, suddenly there came a tapping,

View File

@ -7,7 +7,7 @@ import os
import time import time
const ( const (
text = ' text = '
Once upon a midnight dreary, while I pondered, weak and weary, Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore Over many a quaint and curious volume of forgotten lore
While I nodded, nearly napping, suddenly there came a tapping, While I nodded, nearly napping, suddenly there came a tapping,

View File

@ -4,12 +4,12 @@ import os
const ( const (
help_text = ' Usage:\t./VCasino\n help_text = ' Usage:\t./VCasino\n
Description:\n VCasino is a little game only made to learn V.\n' Description:\n VCasino is a little game only made to learn V.\n'
g_desc = " The object of Roulette is to pick the number where the spinning ball will land on the wheel. g_desc = " The object of Roulette is to pick the number where the spinning ball will land on the wheel.
If your number is the good one, you'll get your bet x3. If your number is the good one, you'll get your bet x3.
If your number is the same color as the ball one, you'll get your bet /2. If your number is the same color as the ball one, you'll get your bet /2.
Otherwise, you will lose your bet.\n" Otherwise, you will lose your bet.\n"
odd = 'red' odd = 'red'
even = 'black' even = 'black'
) )
struct Options { struct Options {

View File

@ -1189,7 +1189,7 @@ pub:
pub const ( pub const (
// reference: https://en.wikipedia.org/wiki/X86#/media/File:Table_of_x86_Registers_svg.svg // reference: https://en.wikipedia.org/wiki/X86#/media/File:Table_of_x86_Registers_svg.svg
// map register size -> register name // map register size -> register name
x86_no_number_register_list = map{ x86_no_number_register_list = map{
8: ['al', 'ah', 'bl', 'bh', 'cl', 'ch', 'dl', 'dh', 'bpl', 'sil', 'dil', 'spl'] 8: ['al', 'ah', 'bl', 'bh', 'cl', 'ch', 'dl', 'dh', 'bpl', 'sil', 'dil', 'spl']
16: ['ax', 'bx', 'cx', 'dx', 'bp', 'si', 'di', 'sp', /* segment registers */ 'cs', 'ss', 16: ['ax', 'bx', 'cx', 'dx', 'bp', 'si', 'di', 'sp', /* segment registers */ 'cs', 'ss',
'ds', 'es', 'fs', 'gs', 'flags', 'ip', /* task registers */ 'gdtr', 'idtr', 'tr', 'ldtr', 'ds', 'es', 'fs', 'gs', 'flags', 'ip', /* task registers */ 'gdtr', 'idtr', 'tr', 'ldtr',

View File

@ -22,7 +22,7 @@ https://github.com/vlang/v/issues/new/choose
You can also use #help on Discord: https://discord.gg/vlang You can also use #help on Discord: https://discord.gg/vlang
' '
no_compiler_error = ' no_compiler_error = '
================== ==================
Error: no C compiler detected. Error: no C compiler detected.

View File

@ -657,6 +657,9 @@ fn expr_is_single_line(expr ast.Expr) bool {
} }
} }
} }
ast.StringLiteral {
return expr.pos.line_nr == expr.pos.last_line
}
else {} else {}
} }
return true return true
@ -888,6 +891,12 @@ pub fn (mut f Fmt) comp_for(node ast.CompFor) {
f.writeln('}') f.writeln('}')
} }
struct ConstAlignInfo {
mut:
max int
last_idx int
}
pub fn (mut f Fmt) const_decl(node ast.ConstDecl) { pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
if node.is_pub { if node.is_pub {
f.write('pub ') f.write('pub ')
@ -901,22 +910,36 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
f.inside_const = false f.inside_const = false
} }
f.write('const ') f.write('const ')
mut max := 0 mut align_infos := []ConstAlignInfo{}
if node.is_block { if node.is_block {
f.writeln('(') f.writeln('(')
for field in node.fields { mut info := ConstAlignInfo{}
if field.name.len > max { for i, field in node.fields {
max = field.name.len if field.name.len > info.max {
info.max = field.name.len
}
if !expr_is_single_line(field.expr) {
info.last_idx = i
align_infos << info
info = ConstAlignInfo{}
} }
} }
info.last_idx = node.fields.len
align_infos << info
f.indent++ f.indent++
} else {
align_infos << ConstAlignInfo{0, 1}
} }
mut prev_field := if node.fields.len > 0 { mut prev_field := if node.fields.len > 0 {
ast.Node(node.fields[0]) ast.Node(node.fields[0])
} else { } else {
ast.Node(ast.NodeError{}) ast.Node(ast.NodeError{})
} }
for field in node.fields { mut align_idx := 0
for i, field in node.fields {
if i > align_infos[align_idx].last_idx {
align_idx++
}
if field.comments.len > 0 { if field.comments.len > 0 {
if f.should_insert_newline_before_node(ast.Expr(field.comments[0]), prev_field) { if f.should_insert_newline_before_node(ast.Expr(field.comments[0]), prev_field) {
f.writeln('') f.writeln('')
@ -929,7 +952,7 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
} }
name := field.name.after('.') name := field.name.after('.')
f.write('$name ') f.write('$name ')
f.write(strings.repeat(` `, max - field.name.len)) f.write(strings.repeat(` `, align_infos[align_idx].max - field.name.len))
f.write('= ') f.write('= ')
f.expr(field.expr) f.expr(field.expr)
f.writeln('') f.writeln('')

View File

@ -1 +1,27 @@
const font = $embed_file('../assets/fonts/RobotoMono-Regular.ttf') const font = $embed_file('../assets/fonts/RobotoMono-Regular.ttf')
const (
test_alignment = 123
foo = Foo{
f: 'foo'
}
spam = 456
egg = 'lorem ipsum'
spameggs = true
)
const (
bar = 'A string
spanning multiple
lines'
baz = 'short'
some_long_name = MyStruct{
x: 42
}
)
const (
a = 123
abc = 123
b = 123
)

View File

@ -5,18 +5,18 @@ module c
// for each constant, during C code generation. // for each constant, during C code generation.
const ( const (
// V_COMMIT_HASH is generated by cmd/tools/gen_vc.v . // V_COMMIT_HASH is generated by cmd/tools/gen_vc.v .
c_commit_hash_default = ' c_commit_hash_default = '
#ifndef V_COMMIT_HASH #ifndef V_COMMIT_HASH
#define V_COMMIT_HASH "@@@" #define V_COMMIT_HASH "@@@"
#endif #endif
' '
// V_CURRENT_COMMIT_HASH is updated, when V is rebuilt inside a git repo. // V_CURRENT_COMMIT_HASH is updated, when V is rebuilt inside a git repo.
c_current_commit_hash_default = ' c_current_commit_hash_default = '
#ifndef V_CURRENT_COMMIT_HASH #ifndef V_CURRENT_COMMIT_HASH
#define V_CURRENT_COMMIT_HASH "@@@" #define V_CURRENT_COMMIT_HASH "@@@"
#endif #endif
' '
c_concurrency_helpers = ' c_concurrency_helpers = '
typedef struct __shared_map __shared_map; typedef struct __shared_map __shared_map;
struct __shared_map { map val; sync__RwMutex mtx; }; struct __shared_map { map val; sync__RwMutex mtx; };
static inline voidptr __dup_shared_map(voidptr src, int sz) { static inline voidptr __dup_shared_map(voidptr src, int sz) {
@ -47,7 +47,7 @@ static inline void __sort_ptr(uintptr_t a[], bool b[], int l)
} }
} }
' '
c_str_fn_defs = ' c_str_fn_defs = '
void _STR_PRINT_ARG(const char *fmt, char** refbufp, int *nbytes, int *memsize, int guess, ...) { void _STR_PRINT_ARG(const char *fmt, char** refbufp, int *nbytes, int *memsize, int guess, ...) {
va_list args; va_list args;
va_start(args, guess); va_start(args, guess);
@ -176,7 +176,7 @@ string _STR_TMP(const char *fmt, ...) {
} // endof _STR_TMP } // endof _STR_TMP
' '
c_common_macros = ' c_common_macros = '
#define EMPTY_VARG_INITIALIZATION 0 #define EMPTY_VARG_INITIALIZATION 0
#define EMPTY_STRUCT_DECLARATION #define EMPTY_STRUCT_DECLARATION
#define EMPTY_STRUCT_INITIALIZATION #define EMPTY_STRUCT_INITIALIZATION
@ -306,7 +306,7 @@ static inline bool _us64_ne(uint64_t a, int64_t b) { return a > INT64_MAX || (in
static inline bool _us64_le(uint64_t a, int64_t b) { return a <= INT64_MAX && (int64_t)a <= b; } static inline bool _us64_le(uint64_t a, int64_t b) { return a <= INT64_MAX && (int64_t)a <= b; }
static inline bool _us64_lt(uint64_t a, int64_t b) { return a < INT64_MAX && (int64_t)a < b; } static inline bool _us64_lt(uint64_t a, int64_t b) { return a < INT64_MAX && (int64_t)a < b; }
' '
c_wyhash = ' c_wyhash = '
// ============== wyhash ============== // ============== wyhash ==============
#ifndef wyhash_final_version_3 #ifndef wyhash_final_version_3
#define wyhash_final_version_3 #define wyhash_final_version_3
@ -487,7 +487,7 @@ static inline void make_secret(uint64_t seed, uint64_t *secret){
} }
#endif #endif
' '
c_helper_macros = '//============================== HELPER C MACROS =============================*/ c_helper_macros = '//============================== HELPER C MACROS =============================*/
//#define tos4(s, slen) ((string){.str=(s), .len=(slen)}) //#define tos4(s, slen) ((string){.str=(s), .len=(slen)})
// `"" s` is used to enforce a string literal argument // `"" s` is used to enforce a string literal argument
#define _SLIT(s) ((string){.str=(byteptr)("" s), .len=(sizeof(s)-1), .is_lit=1}) #define _SLIT(s) ((string){.str=(byteptr)("" s), .len=(sizeof(s)-1), .is_lit=1})
@ -498,8 +498,8 @@ static inline void make_secret(uint64_t seed, uint64_t *secret){
#define _PUSH_MANY(arr, val, tmp, tmp_typ) {tmp_typ tmp = (val); array_push_many(arr, tmp.data, tmp.len);} #define _PUSH_MANY(arr, val, tmp, tmp_typ) {tmp_typ tmp = (val); array_push_many(arr, tmp.data, tmp.len);}
#define _IN_MAP(val, m) map_exists(m, val) #define _IN_MAP(val, m) map_exists(m, val)
' '
c_headers = c_headers = c_helper_macros + c_unsigned_comparison_functions + c_common_macros +
c_helper_macros + c_unsigned_comparison_functions + c_common_macros + r' r'
// c_headers // c_headers
typedef int (*qsort_callback_func)(const void*, const void*); typedef int (*qsort_callback_func)(const void*, const void*);
#include <stdio.h> // TODO remove all these includes, define all function signatures and types manually #include <stdio.h> // TODO remove all these includes, define all function signatures and types manually
@ -694,7 +694,7 @@ static void* g_live_info = NULL;
#undef _VFREESTANDING #undef _VFREESTANDING
#endif #endif
' + c_wyhash ' + c_wyhash
c_builtin_types = ' c_builtin_types = '
//================================== builtin types ================================*/ //================================== builtin types ================================*/
typedef int64_t i64; typedef int64_t i64;
typedef int16_t i16; typedef int16_t i16;
@ -728,8 +728,7 @@ typedef bool (*MapEqFn)(voidptr, voidptr);
typedef void (*MapCloneFn)(voidptr, voidptr); typedef void (*MapCloneFn)(voidptr, voidptr);
typedef void (*MapFreeFn)(voidptr); typedef void (*MapFreeFn)(voidptr);
' '
bare_c_headers = c_helper_macros + c_unsigned_comparison_functions + bare_c_headers = c_helper_macros + c_unsigned_comparison_functions + c_common_macros +
c_common_macros +
' '
#define _VFREESTANDING #define _VFREESTANDING

View File

@ -54,7 +54,7 @@ fn (mut g Gen) generate_hotcode_reloader_code() {
} }
const ( const (
posix_hotcode_definitions_1 = ' posix_hotcode_definitions_1 = '
void v_bind_live_symbols(void* live_lib){ void v_bind_live_symbols(void* live_lib){
@LOAD_FNS@ @LOAD_FNS@
} }

View File

@ -36,8 +36,8 @@ pub const (
'.wasm': 'application/wasm' '.wasm': 'application/wasm'
'.xml': 'text/xml; charset=utf-8' '.xml': 'text/xml; charset=utf-8'
} }
max_http_post_size = 1024 * 1024 max_http_post_size = 1024 * 1024
default_port = 8080 default_port = 8080
) )
pub struct Context { pub struct Context {

View File

@ -60,7 +60,7 @@ const (
34: `"` 34: `"`
47: `/` 47: `/`
} }
exp_signs = [byte(`-`), `+`] exp_signs = [byte(`-`), `+`]
) )
// move_pos proceeds to the next position. // move_pos proceeds to the next position.