From dee733aae4839ca6e70c3b494e431b0d6d8de205 Mon Sep 17 00:00:00 2001 From: Lukas Neubert Date: Thu, 29 Apr 2021 01:17:37 +0200 Subject: [PATCH] fmt: reset const field align after multi line exprs (#9916) --- cmd/tools/vpm.v | 14 ++++++------ cmd/tools/vtest-cleancode.v | 2 +- doc/docs.md | 32 +++++++++++++-------------- examples/gg/raven_text_rendering.v | 2 +- examples/sokol/freetype_raven.v | 2 +- examples/vcasino/vcasino.v | 6 ++--- vlib/v/ast/ast.v | 2 +- vlib/v/builder/cc.v | 2 +- vlib/v/fmt/fmt.v | 35 +++++++++++++++++++++++++----- vlib/v/fmt/tests/consts_keep.vv | 26 ++++++++++++++++++++++ vlib/v/gen/c/cheaders.v | 23 ++++++++++---------- vlib/v/gen/c/live.v | 2 +- vlib/vweb/vweb.v | 4 ++-- vlib/x/json2/scanner.v | 2 +- 14 files changed, 101 insertions(+), 53 deletions(-) diff --git a/cmd/tools/vpm.v b/cmd/tools/vpm.v index be30acb20b..417dfbdf6a 100644 --- a/cmd/tools/vpm.v +++ b/cmd/tools/vpm.v @@ -11,17 +11,17 @@ import vhelp import v.vmod const ( - default_vpm_server_urls = ['https://vpm.vlang.io'] - valid_vpm_commands = ['help', 'search', 'install', 'update', 'upgrade', 'outdated', + default_vpm_server_urls = ['https://vpm.vlang.io'] + valid_vpm_commands = ['help', 'search', 'install', 'update', 'upgrade', 'outdated', 'list', 'remove'] - excluded_dirs = ['cache', 'vlib'] - supported_vcs_systems = ['git', 'hg'] - supported_vcs_folders = ['.git', '.hg'] - supported_vcs_update_cmds = map{ + excluded_dirs = ['cache', 'vlib'] + supported_vcs_systems = ['git', 'hg'] + supported_vcs_folders = ['.git', '.hg'] + supported_vcs_update_cmds = map{ 'git': 'git pull' 'hg': 'hg pull --update' } - supported_vcs_install_cmds = map{ + supported_vcs_install_cmds = map{ 'git': 'git clone --depth=1' 'hg': 'hg clone' } diff --git a/cmd/tools/vtest-cleancode.v b/cmd/tools/vtest-cleancode.v index 15bd3908de..a347c604d8 100644 --- a/cmd/tools/vtest-cleancode.v +++ b/cmd/tools/vtest-cleancode.v @@ -37,9 +37,9 @@ const ( 'vlib/v/tests/generics_test.v', /* multi_generic_args, Foo >(...) becomes .... Foo>(...) which does not parse */ '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/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/path_tracing.v', /* block --> line comments corrupts code */ + 'vlib/v/gen/c/cheaders.v' /* infix wrapping error */, ] vfmt_verify_list = [ 'cmd/', diff --git a/doc/docs.md b/doc/docs.md index 0eb5db8a92..907e301fa3 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1384,7 +1384,7 @@ fn read_log() { ``` If the function returns a value the `defer` block is executed *after* the return -expression is evaluated: +expression is evaluated: ```v import os @@ -1946,7 +1946,7 @@ const ( b: 0 } // evaluate function call at compile-time* - blue = rgb(0, 0, 255) + blue = rgb(0, 0, 255) ) println(numbers) @@ -3122,7 +3122,7 @@ each object. ### Control -You can take advantage of V's autofree engine and define a `free()` method on custom +You can take advantage of V's autofree engine and define a `free()` method on custom data types: ```v @@ -3134,7 +3134,7 @@ fn (data &MyType) free() { } ``` -Just as the compiler frees C data types with C's `free()`, it will statically insert +Just as the compiler frees C data types with C's `free()`, it will statically insert `free()` calls for your data type at the end of each variable's lifetime. For developers willing to have more low level control, autofree can be disabled with @@ -3358,7 +3358,7 @@ You will get: [factorial.v:5] n * factorial(n - 1): 120 120 ``` -Note that `dump(expr)` will trace both the source location, +Note that `dump(expr)` will trace both the source location, the expression itself, and the expression value. ## Memory-unsafe code @@ -3648,9 +3648,9 @@ To cast a `voidptr` to a V reference, use `user := &User(user_void_ptr)`. ### C Declarations -C identifiers are accessed with the `C` prefix similarly to how module-specific -identifiers are accessed. Functions must be redeclared in V before they can be used. -Any C types may be used behind the `C` prefix, but types must be redeclared in V in +C identifiers are accessed with the `C` prefix similarly to how module-specific +identifiers are accessed. Functions must be redeclared in V before they can be used. +Any C types may be used behind the `C` prefix, but types must be redeclared in V in order to access type members. To redeclare complex types, such as in the following C code: @@ -3688,10 +3688,10 @@ struct C.SomeCStruct { } ``` -The existence of the data members is made known to V, and they may be used without +The existence of the data members is made known to V, and they may be used without re-creating the original structure exactly. -Alternatively, you may [embed](#embedded-structs) the sub-data-structures to maintain +Alternatively, you may [embed](#embedded-structs) the sub-data-structures to maintain a parallel code structure. ## Debugging generated C code @@ -3930,7 +3930,7 @@ If you do need a custom flag file, that has platform dependent code, use the postfix `_d_customflag.v`, and then use plaftorm dependent compile time conditional blocks inside it, i.e. `$if linux {}` etc. -- `_notd_customflag.v` => similar to _d_customflag.v, but will be used +- `_notd_customflag.v` => similar to _d_customflag.v, but will be used *only* if you do NOT pass `-d customflag` to V. ## Compile time pseudo variables @@ -4085,7 +4085,7 @@ To improve safety and maintainability, operator overloading is limited: are auto generated when the operators are defined though they must return the same type. ## Inline assembly - + ```v ignore a := 100 b := 20 @@ -4094,12 +4094,12 @@ asm amd64 { mov eax, a add eax, b mov c, eax - ; =r (c) as c // output - ; r (a) as a // input + ; =r (c) as c // output + ; r (a) as a // input r (b) as b } -println('a: $a') // 100 -println('b: $b') // 20 +println('a: $a') // 100 +println('b: $b') // 20 println('c: $c') // 120 ``` diff --git a/examples/gg/raven_text_rendering.v b/examples/gg/raven_text_rendering.v index a548b7db2f..5d14e46ed1 100644 --- a/examples/gg/raven_text_rendering.v +++ b/examples/gg/raven_text_rendering.v @@ -12,7 +12,7 @@ const ( ) const ( - text = ' + text = ' Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore— While I nodded, nearly napping, suddenly there came a tapping, diff --git a/examples/sokol/freetype_raven.v b/examples/sokol/freetype_raven.v index 7a735cee0a..8c14881c92 100644 --- a/examples/sokol/freetype_raven.v +++ b/examples/sokol/freetype_raven.v @@ -7,7 +7,7 @@ import os import time const ( - text = ' + text = ' Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore— While I nodded, nearly napping, suddenly there came a tapping, diff --git a/examples/vcasino/vcasino.v b/examples/vcasino/vcasino.v index 3a038239a3..e6fd87c2b6 100644 --- a/examples/vcasino/vcasino.v +++ b/examples/vcasino/vcasino.v @@ -4,12 +4,12 @@ import os const ( help_text = ' Usage:\t./VCasino\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 same color as the ball one, you'll get your bet /2. Otherwise, you will lose your bet.\n" - odd = 'red' - even = 'black' + odd = 'red' + even = 'black' ) struct Options { diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 02adc4f34d..44d16012f9 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -1189,7 +1189,7 @@ pub: pub const ( // reference: https://en.wikipedia.org/wiki/X86#/media/File:Table_of_x86_Registers_svg.svg // 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'] 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', diff --git a/vlib/v/builder/cc.v b/vlib/v/builder/cc.v index 793c7b9cc1..7546c30ab1 100644 --- a/vlib/v/builder/cc.v +++ b/vlib/v/builder/cc.v @@ -22,7 +22,7 @@ https://github.com/vlang/v/issues/new/choose You can also use #help on Discord: https://discord.gg/vlang ' - no_compiler_error = ' + no_compiler_error = ' ================== Error: no C compiler detected. diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 11580ac793..e542cb35a3 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -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 {} } return true @@ -888,6 +891,12 @@ pub fn (mut f Fmt) comp_for(node ast.CompFor) { f.writeln('}') } +struct ConstAlignInfo { +mut: + max int + last_idx int +} + pub fn (mut f Fmt) const_decl(node ast.ConstDecl) { if node.is_pub { f.write('pub ') @@ -901,22 +910,36 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) { f.inside_const = false } f.write('const ') - mut max := 0 + mut align_infos := []ConstAlignInfo{} if node.is_block { f.writeln('(') - for field in node.fields { - if field.name.len > max { - max = field.name.len + mut info := ConstAlignInfo{} + for i, field in node.fields { + 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++ + } else { + align_infos << ConstAlignInfo{0, 1} } mut prev_field := if node.fields.len > 0 { ast.Node(node.fields[0]) } else { 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 f.should_insert_newline_before_node(ast.Expr(field.comments[0]), prev_field) { f.writeln('') @@ -929,7 +952,7 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) { } name := field.name.after('.') 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.expr(field.expr) f.writeln('') diff --git a/vlib/v/fmt/tests/consts_keep.vv b/vlib/v/fmt/tests/consts_keep.vv index c2e1072e98..c505ad7da6 100644 --- a/vlib/v/fmt/tests/consts_keep.vv +++ b/vlib/v/fmt/tests/consts_keep.vv @@ -1 +1,27 @@ 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 +) diff --git a/vlib/v/gen/c/cheaders.v b/vlib/v/gen/c/cheaders.v index f869650cf2..d4393931af 100644 --- a/vlib/v/gen/c/cheaders.v +++ b/vlib/v/gen/c/cheaders.v @@ -5,18 +5,18 @@ module c // for each constant, during C code generation. const ( // V_COMMIT_HASH is generated by cmd/tools/gen_vc.v . - c_commit_hash_default = ' + c_commit_hash_default = ' #ifndef V_COMMIT_HASH #define V_COMMIT_HASH "@@@" #endif ' // 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 #define V_CURRENT_COMMIT_HASH "@@@" #endif ' - c_concurrency_helpers = ' + c_concurrency_helpers = ' typedef struct __shared_map __shared_map; struct __shared_map { map val; sync__RwMutex mtx; }; 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, ...) { va_list args; va_start(args, guess); @@ -176,7 +176,7 @@ string _STR_TMP(const char *fmt, ...) { } // endof _STR_TMP ' - c_common_macros = ' + c_common_macros = ' #define EMPTY_VARG_INITIALIZATION 0 #define EMPTY_STRUCT_DECLARATION #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_lt(uint64_t a, int64_t b) { return a < INT64_MAX && (int64_t)a < b; } ' - c_wyhash = ' + c_wyhash = ' // ============== wyhash ============== #ifndef 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 ' - c_helper_macros = '//============================== HELPER C MACROS =============================*/ + c_helper_macros = '//============================== HELPER C MACROS =============================*/ //#define tos4(s, slen) ((string){.str=(s), .len=(slen)}) // `"" s` is used to enforce a string literal argument #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 _IN_MAP(val, m) map_exists(m, val) ' - c_headers = - c_helper_macros + c_unsigned_comparison_functions + c_common_macros + r' + c_headers = c_helper_macros + c_unsigned_comparison_functions + c_common_macros + + r' // c_headers typedef int (*qsort_callback_func)(const void*, const void*); #include // TODO remove all these includes, define all function signatures and types manually @@ -694,7 +694,7 @@ static void* g_live_info = NULL; #undef _VFREESTANDING #endif ' + c_wyhash - c_builtin_types = ' + c_builtin_types = ' //================================== builtin types ================================*/ typedef int64_t i64; typedef int16_t i16; @@ -728,8 +728,7 @@ typedef bool (*MapEqFn)(voidptr, voidptr); typedef void (*MapCloneFn)(voidptr, voidptr); typedef void (*MapFreeFn)(voidptr); ' - bare_c_headers = c_helper_macros + c_unsigned_comparison_functions + - c_common_macros + + bare_c_headers = c_helper_macros + c_unsigned_comparison_functions + c_common_macros + ' #define _VFREESTANDING diff --git a/vlib/v/gen/c/live.v b/vlib/v/gen/c/live.v index 5bcf6015ba..69709f93fe 100644 --- a/vlib/v/gen/c/live.v +++ b/vlib/v/gen/c/live.v @@ -54,7 +54,7 @@ fn (mut g Gen) generate_hotcode_reloader_code() { } const ( - posix_hotcode_definitions_1 = ' + posix_hotcode_definitions_1 = ' void v_bind_live_symbols(void* live_lib){ @LOAD_FNS@ } diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index 46b8ccb612..57bea00d36 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -36,8 +36,8 @@ pub const ( '.wasm': 'application/wasm' '.xml': 'text/xml; charset=utf-8' } - max_http_post_size = 1024 * 1024 - default_port = 8080 + max_http_post_size = 1024 * 1024 + default_port = 8080 ) pub struct Context { diff --git a/vlib/x/json2/scanner.v b/vlib/x/json2/scanner.v index a04aaa9926..c77f4373b8 100644 --- a/vlib/x/json2/scanner.v +++ b/vlib/x/json2/scanner.v @@ -60,7 +60,7 @@ const ( 34: `"` 47: `/` } - exp_signs = [byte(`-`), `+`] + exp_signs = [byte(`-`), `+`] ) // move_pos proceeds to the next position.