fmt: make single-stmt `or` blocks single-line (#7126)

pull/7128/head
spaceface777 2020-12-04 12:25:23 +01:00 committed by GitHub
parent 9345d489f8
commit 50a3009113
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 78 additions and 170 deletions

View File

@ -202,9 +202,7 @@ pub fn (b Builder) v_files_from_dir(dir string) []string {
} else if !os.is_dir(dir) {
verror("$dir isn't a directory!")
}
mut files := os.ls(dir) or {
panic(err)
}
mut files := os.ls(dir) or { panic(err) }
if b.pref.is_verbose {
println('v_files_from_dir ("$dir")')
}

View File

@ -39,9 +39,7 @@ pub fn (mut b Builder) build_c(v_files []string, out_file string) {
b.pref.out_name_c = os.real_path(out_file)
b.info('build_c($out_file)')
output2 := b.gen_c(v_files)
mut f := os.create(out_file) or {
panic(err)
}
mut f := os.create(out_file) or { panic(err) }
f.writeln(output2)
f.close()
// os.write_file(out_file, b.gen_c(v_files))
@ -58,9 +56,7 @@ pub fn (mut b Builder) compile_c() {
// println(files)
}
$if windows {
b.find_win_cc() or {
verror(no_compiler_error)
}
b.find_win_cc() or { verror(no_compiler_error) }
// TODO Probably extend this to other OS's?
}
// v1 compiler files

View File

@ -210,9 +210,7 @@ fn (mut v Builder) cc() {
}
}
// v.out_name_c may be on a different partition than v.out_name
os.mv_by_cp(v.out_name_c, v.pref.out_name) or {
panic(err)
}
os.mv_by_cp(v.out_name_c, v.pref.out_name) or { panic(err) }
return
}
// Cross compiling for Windows

View File

@ -30,9 +30,7 @@ pub fn (mut b Builder) build_js(v_files []string, out_file string) {
b.out_name_js = out_file
b.info('build_js($out_file)')
output := b.gen_js(v_files)
mut f := os.create(out_file) or {
panic(err)
}
mut f := os.create(out_file) or { panic(err) }
f.writeln(output)
f.close()
}

View File

@ -166,12 +166,8 @@ fn find_msvc() ?MsvcResult {
processor_architecture := os.getenv('PROCESSOR_ARCHITECTURE')
vswhere_dir := if processor_architecture == 'x86' { '%ProgramFiles%' } else { '%ProgramFiles(x86)%' }
host_arch := if processor_architecture == 'x86' { 'X86' } else { 'X64' }
wk := find_windows_kit_root(host_arch) or {
return error('Unable to find windows sdk')
}
vs := find_vs(vswhere_dir, host_arch) or {
return error('Unable to find visual studio')
}
wk := find_windows_kit_root(host_arch) or { return error('Unable to find windows sdk') }
vs := find_vs(vswhere_dir, host_arch) or { return error('Unable to find visual studio') }
return MsvcResult{
full_cl_exe_path: os.real_path(vs.exe_path + os.path_separator + 'cl.exe')
exe_path: vs.exe_path

View File

@ -273,9 +273,7 @@ fn (mut c Checker) check_valid_snake_case(name string, identifier string, pos to
}
fn stripped_name(name string) string {
idx := name.last_index('.') or {
-1
}
idx := name.last_index('.') or { -1 }
return name[(idx + 1)..]
}
@ -348,9 +346,7 @@ pub fn (mut c Checker) struct_decl(decl ast.StructDecl) {
if decl.language == .v && !c.is_builtin_mod {
c.check_valid_pascal_case(decl.name, 'struct name', decl.pos)
}
mut struct_sym := c.table.find_type(decl.name) or {
table.TypeSymbol{}
}
mut struct_sym := c.table.find_type(decl.name) or { table.TypeSymbol{} }
if mut struct_sym.info is table.Struct {
for i, field in decl.fields {
if decl.language == .v && !field.is_embed {
@ -2735,9 +2731,7 @@ fn (mut c Checker) hash_stmt(mut node ast.HashStmt) {
}
}
// println('adding flag "$flag"')
c.table.parse_cflag(flag, c.mod, c.pref.compile_defines_all) or {
c.error(err, node.pos)
}
c.table.parse_cflag(flag, c.mod, c.pref.compile_defines_all) or { c.error(err, node.pos) }
} else {
if node.kind != 'define' {
c.error('expected `#define`, `#flag`, `#include` or `#pkgconfig` not $node.val',
@ -2847,9 +2841,7 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type {
}
ast.Assoc {
scope := c.file.scope.innermost(node.pos.pos)
v := scope.find_var(node.var_name) or {
panic(err)
}
v := scope.find_var(node.var_name) or { panic(err) }
for i, _ in node.fields {
c.expr(node.exprs[i])
}
@ -3193,9 +3185,7 @@ fn (mut c Checker) at_expr(mut node ast.AtExpr) table.Type {
c.error('@VMOD_FILE can be used only in projects, that have v.mod file',
node.pos)
}
vmod_content := os.read_file(vmod_file_location.vmod_file) or {
''
}
vmod_content := os.read_file(vmod_file_location.vmod_file) or { '' }
$if windows {
c.vmod_file_content = vmod_content.replace('\r\n', '\n')
} $else {
@ -3978,9 +3968,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) table.Type {
}
for st in branch.stmts {
// must not contain C statements
st.check_c_expr() or {
c.error('`if` expression branch has $err', st.position())
}
st.check_c_expr() or { c.error('`if` expression branch has $err', st.position()) }
}
}
// Also check for returns inside a comp.if's statements, even if its contents aren't parsed

View File

@ -327,9 +327,7 @@ pub fn (mut d Doc) generate() ? {
// get all files
d.base_path = if os.is_dir(d.base_path) { d.base_path } else { os.real_path(os.dir(d.base_path)) }
d.is_vlib = 'vlib' !in d.base_path
project_files := os.ls(d.base_path) or {
return error_with_code(err, 0)
}
project_files := os.ls(d.base_path) or { return error_with_code(err, 0) }
v_files := d.prefs.should_compile_filtered_files(d.base_path, project_files)
if v_files.len == 0 {
return error_with_code('vdoc: No valid V files were found.', 1)
@ -345,14 +343,10 @@ pub fn (mut d Doc) generate() ? {
mut file_asts := []ast.File{}
for i, file_path in v_files {
if i == 0 {
d.parent_mod_name = get_parent_mod(d.base_path) or {
''
}
d.parent_mod_name = get_parent_mod(d.base_path) or { '' }
}
filename := os.base(file_path)
d.sources[filename] = util.read_file(file_path) or {
''
}
d.sources[filename] = util.read_file(file_path) or { '' }
file_asts <<
parser.parse_file(file_path, d.table, comments_mode, d.prefs, global_scope)
}

View File

@ -26,9 +26,7 @@ fn get_parent_mod(input_dir string) ?string {
base_dir := os.dir(input_dir)
input_dir_name := os.file_name(base_dir)
prefs := new_vdoc_preferences()
fentries := os.ls(base_dir) or {
[]string{}
}
fentries := os.ls(base_dir) or { []string{} }
files := fentries.filter(!os.is_dir(it))
if 'v.mod' in files {
// the top level is reached, no point in climbing up further
@ -36,9 +34,7 @@ fn get_parent_mod(input_dir string) ?string {
}
v_files := prefs.should_compile_filtered_files(base_dir, files)
if v_files.len == 0 {
parent_mod := get_parent_mod(base_dir) or {
return input_dir_name
}
parent_mod := get_parent_mod(base_dir) or { return input_dir_name }
if parent_mod.len > 0 {
return parent_mod + '.' + input_dir_name
}
@ -52,9 +48,7 @@ fn get_parent_mod(input_dir string) ?string {
if file_ast.mod.name == 'main' {
return ''
}
parent_mod := get_parent_mod(base_dir) or {
return input_dir_name
}
parent_mod := get_parent_mod(base_dir) or { return input_dir_name }
if parent_mod.len > 0 {
return '${parent_mod}.$file_ast.mod.name'
}

View File

@ -62,9 +62,7 @@ pub fn get_comment_block_right_before(comments []ast.Comment) string {
fn (mut d Doc) convert_pos(filename string, pos token.Position) DocPos {
if filename !in d.sources {
d.sources[filename] = util.read_file(os.join_path(d.base_path, filename)) or {
''
}
d.sources[filename] = util.read_file(os.join_path(d.base_path, filename)) or { '' }
}
source := d.sources[filename]
mut p := util.imax(0, util.imin(source.len - 1, pos.pos))

View File

@ -241,6 +241,18 @@ pub fn (mut f Fmt) stmts(stmts []ast.Stmt) {
f.indent--
}
pub fn (mut f Fmt) stmt_str(node ast.Stmt) string {
was_empty_line := f.empty_line
prev_line_len := f.line_len
pos := f.out.len
f.stmt(node)
str := f.out.after(pos).trim_space()
f.out.go_back_to(pos)
f.empty_line = was_empty_line
f.line_len = prev_line_len
return str
}
pub fn (mut f Fmt) stmt(node ast.Stmt) {
if f.is_debug {
eprintln('stmt: ${node.position():-42} | node: ${typeof(node):-20}')
@ -1126,6 +1138,19 @@ pub fn (mut f Fmt) or_expr(or_block ast.OrExpr) {
.block {
if or_block.stmts.len == 0 {
f.write(' or { }')
} else if or_block.stmts.len == 1 {
// the control stmts (return/break/continue...) print a newline inside them,
// so, since this'll all be on one line, trim any possible whitespace
str := f.stmt_str(or_block.stmts[0]).trim_space()
single_line := ' or { $str }'
if single_line.len + f.line_len <= max_len.last() {
f.write(single_line)
} else {
// if the line would be too long, make it multiline
f.writeln(' or {')
f.stmts(or_block.stmts)
f.write('}')
}
} else {
f.writeln(' or {')
f.stmts(or_block.stmts)
@ -1597,9 +1622,7 @@ pub fn (mut f Fmt) mark_module_as_used(name string) {
if !name.contains('.') {
return
}
pos := name.last_index('.') or {
0
}
pos := name.last_index('.') or { 0 }
mod := name[..pos]
if mod in f.used_imports {
return

View File

@ -26,9 +26,7 @@ fn test_fmt() {
os.chdir(vroot)
basepath := os.join_path(vroot, '')
tmpfolder := os.temp_dir()
diff_cmd := util.find_working_diff_command() or {
''
}
diff_cmd := util.find_working_diff_command() or { '' }
mut fmt_bench := benchmark.new_benchmark()
keep_input_files := os.walk_ext('vlib/v/fmt/tests', '_keep.vv')
expected_input_files := os.walk_ext('vlib/v/fmt/tests', '_expected.vv')

View File

@ -23,9 +23,7 @@ fn test_fmt() {
}
vroot := os.dir(vexe)
tmpfolder := os.temp_dir()
diff_cmd := util.find_working_diff_command() or {
''
}
diff_cmd := util.find_working_diff_command() or { '' }
mut fmt_bench := benchmark.new_benchmark()
// Lookup the existing test _input.vv files:
input_files := os.walk_ext('$vroot/vlib/v/fmt/tests', '_input.vv')

View File

@ -26,9 +26,7 @@ fn test_vlib_fmt() {
}
vroot := os.dir(vexe)
tmpfolder := os.temp_dir()
diff_cmd := util.find_working_diff_command() or {
''
}
diff_cmd := util.find_working_diff_command() or { '' }
mut fmt_bench := benchmark.new_benchmark()
os.chdir(vroot)
input_files := os.walk_ext('vlib/v/', '.v').filter(!it.contains('/tests/'))

View File

@ -1,13 +0,0 @@
fn fn_with_or() int {
fn_with_optional() or {
return 10
}
return 20
}
fn (f Foo) method_with_or() int {
f.fn_with_optional() or {
return 10
}
return 20
}

View File

@ -1,5 +1,5 @@
fn fn_with_or() int {
fn_with_optional() or { return 10 }
fn_with_optional() or { return 10 }
return 20
}

View File

@ -3,7 +3,5 @@ fn tt() ? {
}
fn main() {
tt() or {
panic('$err')
}
tt() or { panic('$err') }
}

View File

@ -18,16 +18,12 @@ fn test_c_files() {
vroot := os.dir(vexe)
for i in 1 .. (nr_tests + 1) {
path := '$vroot/vlib/v/gen/tests/${i}.vv'
ctext := os.read_file('$vroot/vlib/v/gen/tests/${i}.c') or {
panic(err)
}
ctext := os.read_file('$vroot/vlib/v/gen/tests/${i}.c') or { panic(err) }
mut b := builder.new_builder(pref.Preferences{})
b.module_search_paths = ['$vroot/vlib/v/gen/tests/']
mut res := b.gen_c([path]).after('#endbuiltin')
if res.contains('string _STR') {
pos := res.index('string _STR') or {
-1
}
pos := res.index('string _STR') or { -1 }
end := res.index_after('endof _STR_TMP', pos)
res = res[..pos] + res[end + 15..]
}

View File

@ -38,9 +38,7 @@ fn (mut g Gen) comptime_call(node ast.ComptimeCall) {
result_type := g.table.find_type_idx('vweb.Result') // TODO not just vweb
if node.method_name == 'method' {
// `app.$method()`
m := node.sym.find_method(g.comp_for_method) or {
return
}
m := node.sym.find_method(g.comp_for_method) or { return }
/*
vals := m.attrs[0].split('/')
args := vals.filter(it.starts_with(':')).map(it[1..])

View File

@ -99,9 +99,7 @@ pub fn (mut g Gen) generate_elf_footer() {
// -5 is for "e8 00 00 00 00"
g.write32_at(g.code_start_pos + 1, int(g.main_fn_addr - g.code_start_pos) - 5)
// Create the binary
mut f := os.create(g.out_name) or {
panic(err)
}
mut f := os.create(g.out_name) or { panic(err) }
os.chmod(g.out_name, 0o775) // make it an executable
f.write_bytes(g.buf.data, g.buf.len)
f.close()

View File

@ -165,9 +165,7 @@ pub fn parse_vet_file(path string, table_ &table.Table, pref &pref.Preferences)
global_scope: global_scope
}
if p.scanner.text.contains('\n ') {
source_lines := os.read_lines(path) or {
[]string{}
}
source_lines := os.read_lines(path) or { []string{} }
for lnumber, line in source_lines {
if line.starts_with(' ') {
p.vet_error('Looks like you are using spaces for indentation.', lnumber)

View File

@ -340,9 +340,7 @@ pub fn parse_args(args []string) (&Preferences, string) {
'-b' {
sbackend := cmdline.option(current_args, '-b', 'c')
res.build_options << '$arg $sbackend'
b := backend_from_string(sbackend) or {
continue
}
b := backend_from_string(sbackend) or { continue }
res.backend = b
i++
}

View File

@ -31,9 +31,7 @@ pub fn (mut table Table) parse_cflag(cflg string, mod string, ctimedefines []str
if !flag.starts_with(os_override) {
continue
}
pos := flag.index(' ') or {
return none
}
pos := flag.index(' ') or { return none }
fos = flag[..pos].trim_space()
flag = flag[pos..].trim_space()
}
@ -50,9 +48,7 @@ pub fn (mut table Table) parse_cflag(cflg string, mod string, ctimedefines []str
}
}
}
mut index := flag.index(' -') or {
-1
}
mut index := flag.index(' -') or { -1 }
for index > -1 {
mut has_next := false
for f in allowed_flags {

View File

@ -58,9 +58,7 @@ fn parse_valid_flag(mut t table.Table, flag string) {
}
fn assert_parse_invalid_flag(mut t table.Table, flag string) {
t.parse_cflag(flag, module_name, cdefines) or {
return
}
t.parse_cflag(flag, module_name, cdefines) or { return }
assert false
}

View File

@ -153,9 +153,7 @@ pub fn (t &Table) find_fn(name string) ?Fn {
}
pub fn (t &Table) known_fn(name string) bool {
t.find_fn(name) or {
return false
}
t.find_fn(name) or { return false }
return true
}
@ -272,9 +270,7 @@ pub fn (t &Table) struct_find_field(s &TypeSymbol, name string) ?Field {
if field := ts.info.find_field(name) {
return field
}
field := t.register_aggregate_field(mut ts, name) or {
return error(err)
}
field := t.register_aggregate_field(mut ts, name) or { return error(err) }
return field
}
if ts.parent_idx == 0 {
@ -400,9 +396,7 @@ pub fn (mut t Table) register_type_symbol(typ TypeSymbol) int {
}
pub fn (t &Table) known_type(name string) bool {
t.find_type(name) or {
return false
}
t.find_type(name) or { return false }
return true
}

View File

@ -1016,9 +1016,7 @@ pub fn (t &Table) fn_signature(func &Fn, opts FnSignatureOpts) string {
}
pub fn (t &TypeSymbol) has_method(name string) bool {
t.find_method(name) or {
return false
}
t.find_method(name) or { return false }
return true
}

View File

@ -22,9 +22,7 @@ pub fn find_working_diff_command() ?string {
}
continue
}
p := os.exec('$diffcmd --version') or {
continue
}
p := os.exec('$diffcmd --version') or { continue }
if p.exit_code == 127 && diffcmd == env_difftool {
// user setup is wonky, fix it
return error('could not find specified VDIFF_TOOL $diffcmd')
@ -43,9 +41,7 @@ pub fn find_working_diff_command() ?string {
// determine if the FileMerge opendiff tool is available
fn opendiff_exists() bool {
o := os.exec('opendiff') or {
return false
}
o := os.exec('opendiff') or { return false }
if o.exit_code == 1 { // failed (expected), but found (i.e. not 127)
if o.output.contains('too few arguments') { // got some exptected output
return true
@ -57,9 +53,7 @@ fn opendiff_exists() bool {
pub fn color_compare_files(diff_cmd string, file1 string, file2 string) string {
if diff_cmd != '' {
full_cmd := '$diff_cmd --minimal --text --unified=2 --show-function-line="fn " "$file1" "$file2" '
x := os.exec(full_cmd) or {
return 'comparison command: `$full_cmd` failed'
}
x := os.exec(full_cmd) or { return 'comparison command: `$full_cmd` failed' }
return x.output.trim_right('\r\n')
}
return ''

View File

@ -93,9 +93,7 @@ pub fn formatted_error(kind string, omsg string, filepath string, pos token.Posi
pub fn filepath_pos_to_source_and_column(filepath string, pos token.Position) (string, int) {
// TODO: optimize this; may be use a cache.
// The column should not be so computationally hard to get.
source := read_file(filepath) or {
''
}
source := read_file(filepath) or { '' }
mut p := imax(0, imin(source.len - 1, pos.pos))
if source.len > 0 {
for ; p >= 0; p-- {

View File

@ -71,9 +71,7 @@ pub fn githash(should_get_from_filesystem bool) string {
break
}
// 'ref: refs/heads/master' ... the current branch name
head_content := os.read_file(git_head_file) or {
break
}
head_content := os.read_file(git_head_file) or { break }
mut current_branch_hash := head_content
if head_content.starts_with('ref: ') {
gcbranch_rel_path := head_content.replace('ref: ', '').trim_space()
@ -83,9 +81,7 @@ pub fn githash(should_get_from_filesystem bool) string {
break
}
// get the full commit hash contained in the ref heads file
branch_hash := os.read_file(gcbranch_file) or {
break
}
branch_hash := os.read_file(gcbranch_file) or { break }
current_branch_hash = branch_hash
}
desired_hash_length := 7
@ -144,18 +140,14 @@ pub fn launch_tool(is_verbose bool, tool_name string, args []string) {
if should_compile {
emodules := external_module_dependencies_for_tool[tool_name]
for emodule in emodules {
check_module_is_installed(emodule, is_verbose) or {
panic(err)
}
check_module_is_installed(emodule, is_verbose) or { panic(err) }
}
mut compilation_command := '"$vexe" '
compilation_command += '"$tool_source"'
if is_verbose {
println('Compiling $tool_name with: "$compilation_command"')
}
tool_compilation := os.exec(compilation_command) or {
panic(err)
}
tool_compilation := os.exec(compilation_command) or { panic(err) }
if tool_compilation.exit_code != 0 {
eprintln('cannot compile `$tool_source`: \n$tool_compilation.output')
exit(1)
@ -227,9 +219,7 @@ pub fn path_of_executable(path string) string {
}
pub fn read_file(file_path string) ?string {
raw_text := os.read_file(file_path) or {
return error('failed to open $file_path')
}
raw_text := os.read_file(file_path) or { return error('failed to open $file_path') }
return skip_bom(raw_text)
}
@ -356,9 +346,7 @@ pub fn ensure_modules_for_all_tools_are_installed(is_verbose bool) {
eprintln('Installing modules for tool: $tool_name ...')
}
for emodule in tool_modules {
check_module_is_installed(emodule, is_verbose) or {
panic(err)
}
check_module_is_installed(emodule, is_verbose) or { panic(err) }
}
}
}

View File

@ -13,9 +13,7 @@ fn test_vet() {
}
fn get_tests_in_dir(dir string) []string {
files := os.ls(dir) or {
panic(err)
}
files := os.ls(dir) or { panic(err) }
mut tests := files.filter(it.ends_with('.vv'))
tests.sort()
return tests
@ -27,12 +25,8 @@ fn check_path(vexe string, dir string, tests []string) int {
for path in paths {
program := path
print(path + ' ')
res := os.exec('$vexe vet $program') or {
panic(err)
}
mut expected := os.read_file(program.replace('.vv', '') + '.out') or {
panic(err)
}
res := os.exec('$vexe vet $program') or { panic(err) }
mut expected := os.read_file(program.replace('.vv', '') + '.out') or { panic(err) }
expected = clean_line_endings(expected)
found := clean_line_endings(res.output)
if expected != found {

View File

@ -52,9 +52,7 @@ pub fn from_file(vmod_path string) ?Manifest {
if !os.exists(vmod_path) {
return error('v.mod: v.mod file not found.')
}
contents := os.read_file(vmod_path) or {
panic('v.mod: cannot parse v.mod')
}
contents := os.read_file(vmod_path) or { panic('v.mod: cannot parse v.mod') }
return decode(contents)
}