diff --git a/cmd/tools/check_os_api_parity.v b/cmd/tools/check_os_api_parity.v index 38dad2802b..adc364a68a 100644 --- a/cmd/tools/check_os_api_parity.v +++ b/cmd/tools/check_os_api_parity.v @@ -43,7 +43,7 @@ fn main() { vexe := pref.vexe_path() vroot := os.dir(vexe) util.set_vroot_folder(vroot) - os.chdir(vroot) ? + os.chdir(vroot)? cmd := diff.find_working_diff_command() or { '' } mut app := App{ diff_cmd: cmd diff --git a/cmd/tools/fast/fast.v b/cmd/tools/fast/fast.v index 938fdd4210..76d95d2d8f 100644 --- a/cmd/tools/fast/fast.v +++ b/cmd/tools/fast/fast.v @@ -15,7 +15,7 @@ const vdir = @VEXEROOT fn main() { dump(fast_dir) dump(vdir) - os.chdir(fast_dir) ? + os.chdir(fast_dir)? if !os.exists('$vdir/v') && !os.is_dir('$vdir/vlib') { println('fast.html generator needs to be located in `v/cmd/tools/fast`') } @@ -32,11 +32,11 @@ fn main() { // fetch the last commit's hash commit := exec('git rev-parse HEAD')[..8] if !os.exists('table.html') { - os.create('table.html') ? + os.create('table.html')? } - mut table := os.read_file('table.html') ? + mut table := os.read_file('table.html')? if os.exists('website/index.html') { - uploaded_index := os.read_file('website/index.html') ? + uploaded_index := os.read_file('website/index.html')? if uploaded_index.contains('>$commit<') { println('nothing to benchmark') exit(1) @@ -48,7 +48,7 @@ fn main() { // build an optimized V println(' Building vprod...') - os.chdir(vdir) ? + os.chdir(vdir)? if os.args.contains('-noprod') { exec('./v -o vprod cmd/v') // for faster debugging } else { @@ -82,8 +82,8 @@ fn main() { commit_date := exec('git log -n1 --pretty="format:%at" $commit') date := time.unix(commit_date.int()) - os.chdir(fast_dir) ? - mut out := os.create('table.html') ? + os.chdir(fast_dir)? + mut out := os.create('table.html')? // place the new row on top html_message := message.replace_each(['<', '<', '>', '>']) @@ -105,25 +105,25 @@ fn main() { ${int(f64(vlines) / f64(diff1) * 1000.0)} \n' + table.trim_space() - out.writeln(table) ? + out.writeln(table)? out.close() // regenerate index.html - header := os.read_file('header.html') ? - footer := os.read_file('footer.html') ? - mut res := os.create('index.html') ? - res.writeln(header) ? - res.writeln(table) ? - res.writeln(footer) ? + header := os.read_file('header.html')? + footer := os.read_file('footer.html')? + mut res := os.create('index.html')? + res.writeln(header)? + res.writeln(table)? + res.writeln(footer)? res.close() // upload the result to github pages if os.args.contains('-upload') { println('uploading...') - os.chdir('website') ? + os.chdir('website')? os.execute_or_exit('git checkout gh-pages') - os.cp('../index.html', 'index.html') ? - os.rm('../index.html') ? + os.cp('../index.html', 'index.html')? + os.rm('../index.html')? os.system('git commit -am "update benchmark"') os.system('git push origin gh-pages') } diff --git a/cmd/tools/oldv.v b/cmd/tools/oldv.v index e4e73866bb..b576815813 100644 --- a/cmd/tools/oldv.v +++ b/cmd/tools/oldv.v @@ -125,7 +125,7 @@ fn main() { should_sync := fp.bool('cache-sync', `s`, false, 'Update the local cache') context.is_bisect = fp.bool('bisect', `b`, false, 'Bisect mode. Use the current commit in the repo where oldv is.') if !should_sync && !context.is_bisect { - fp.limit_free_args(1, 1) ? + fp.limit_free_args(1, 1)? } //// context.cleanup = fp.bool('clean', 0, false, 'Clean before running (slower).') diff --git a/cmd/tools/performance_compare.v b/cmd/tools/performance_compare.v index 3d0db51636..5b421be247 100644 --- a/cmd/tools/performance_compare.v +++ b/cmd/tools/performance_compare.v @@ -194,7 +194,7 @@ fn main() { fp.description(tool_description) fp.arguments_description('COMMIT_BEFORE [COMMIT_AFTER]') fp.skip_executable() - fp.limit_free_args(1, 2) ? + fp.limit_free_args(1, 2)? context.vflags = fp.string('vflags', 0, '', 'Additional options to pass to the v commands, for example "-cc tcc"') context.hyperfineopts = fp.string('hyperfine_options', 0, '', 'Additional options passed to hyperfine. ${flag.space}For example on linux, you may want to pass: diff --git a/cmd/tools/repeat.v b/cmd/tools/repeat.v index b3b2ac56ec..d93bcc30d8 100644 --- a/cmd/tools/repeat.v +++ b/cmd/tools/repeat.v @@ -143,7 +143,7 @@ const ( fn main() { mut context := Context{} - context.parse_options() ? + context.parse_options()? context.run() context.show_diff_summary() } @@ -155,7 +155,7 @@ fn (mut context Context) parse_options() ? { fp.description('Repeat command(s) and collect statistics. Note: you have to quote each command, if it contains spaces.') fp.arguments_description('CMD1 CMD2 ...') fp.skip_executable() - fp.limit_free_args_to_at_least(1) ? + fp.limit_free_args_to_at_least(1)? context.count = fp.int('count', `c`, 10, 'Repetition count.') context.series = fp.int('series', `s`, 2, 'Series count. `-s 2 -c 4 a b` => aaaabbbbaaaabbbb, while `-s 3 -c 2 a b` => aabbaabbaabb.') context.warmup = fp.int('warmup', `w`, 2, 'Warmup runs. These are done *only at the start*, and are ignored.') diff --git a/cmd/tools/test_if_v_test_system_works.v b/cmd/tools/test_if_v_test_system_works.v index f20c552a2a..39d057230e 100644 --- a/cmd/tools/test_if_v_test_system_works.v +++ b/cmd/tools/test_if_v_test_system_works.v @@ -42,7 +42,7 @@ fn cleanup_tdir() { fn create_test(tname string, tcontent string) ?string { tpath := os.join_path(tdir, tname) - os.write_file(tpath, tcontent) ? + os.write_file(tpath, tcontent)? eprintln('>>>>>>>> tpath: $tpath | tcontent: $tcontent') return tpath } @@ -52,17 +52,17 @@ fn main() { os.chdir(os.wd_at_startup) or {} } println('> vroot: $vroot | vexe: $vexe | tdir: $tdir') - ok_fpath := create_test('a_single_ok_test.v', 'fn test_ok(){ assert true }') ? + ok_fpath := create_test('a_single_ok_test.v', 'fn test_ok(){ assert true }')? check_ok('"$vexe" "$ok_fpath"') check_ok('"$vexe" test "$ok_fpath"') check_ok('"$vexe" test "$tdir"') - fail_fpath := create_test('a_single_failing_test.v', 'fn test_fail(){ assert 1 == 2 }') ? + fail_fpath := create_test('a_single_failing_test.v', 'fn test_fail(){ assert 1 == 2 }')? check_fail('"$vexe" "$fail_fpath"') check_fail('"$vexe" test "$fail_fpath"') check_fail('"$vexe" test "$tdir"') rel_dir := os.join_path(tdir, rand.ulid()) - os.mkdir(rel_dir) ? - os.chdir(rel_dir) ? + os.mkdir(rel_dir)? + os.chdir(rel_dir)? check_ok('"$vexe" test "..${os.path_separator + os.base(ok_fpath)}"') println('> all done') } diff --git a/cmd/tools/vast/vast.v b/cmd/tools/vast/vast.v index 46124e73da..ffc4231f67 100644 --- a/cmd/tools/vast/vast.v +++ b/cmd/tools/vast/vast.v @@ -44,7 +44,7 @@ fn main() { for hf in hfields.split(',') { ctx.hide_names[hf] = true } - fp.limit_free_args_to_at_least(1) ? + fp.limit_free_args_to_at_least(1)? rest_of_args := fp.remaining_parameters() for vfile in rest_of_args { file := get_abs_path(vfile) diff --git a/cmd/tools/vbin2v.v b/cmd/tools/vbin2v.v index 8f22974c76..a67cfc0c1c 100644 --- a/cmd/tools/vbin2v.v +++ b/cmd/tools/vbin2v.v @@ -130,12 +130,12 @@ fn main() { } max_bname := context.max_bname_len(file_byte_map.keys()) if context.write_file.len > 0 { - mut out_file := os.create(context.write_file) ? - out_file.write_string(context.header()) ? + mut out_file := os.create(context.write_file)? + out_file.write_string(context.header())? for bname, fbytes in file_byte_map { - out_file.write_string(context.file2v(bname, fbytes, max_bname)) ? + out_file.write_string(context.file2v(bname, fbytes, max_bname))? } - out_file.write_string(context.footer()) ? + out_file.write_string(context.footer())? } else { print(context.header()) for bname, fbytes in file_byte_map { diff --git a/cmd/tools/vbuild-tools.v b/cmd/tools/vbuild-tools.v index 12793fcfc0..d8c34c85f8 100644 --- a/cmd/tools/vbuild-tools.v +++ b/cmd/tools/vbuild-tools.v @@ -23,7 +23,7 @@ fn main() { args_string := os.args[1..].join(' ') vexe := os.getenv('VEXE') vroot := os.dir(vexe) - os.chdir(vroot) ? + os.chdir(vroot)? folder := os.join_path('cmd', 'tools') tfolder := os.join_path(vroot, 'cmd', 'tools') main_label := 'Building $folder ...' @@ -47,7 +47,7 @@ fn main() { exit(1) } // - mut executables := os.ls(session.vtmp_dir) ? + mut executables := os.ls(session.vtmp_dir)? executables.sort() for texe in executables { tname := texe.replace(os.file_ext(texe), '') diff --git a/cmd/tools/vbump.v b/cmd/tools/vbump.v index 475167ffa2..f782fd235e 100644 --- a/cmd/tools/vbump.v +++ b/cmd/tools/vbump.v @@ -20,7 +20,7 @@ const ( tool_version = \'1.2.1\' version: \'0.2.42\' VERSION = "1.23.8" - + Examples: Bump the patch version in v.mod if it exists v bump --patch diff --git a/cmd/tools/vbump_test.v b/cmd/tools/vbump_test.v index c0b13706fd..6f8dbe0b71 100644 --- a/cmd/tools/vbump_test.v +++ b/cmd/tools/vbump_test.v @@ -68,21 +68,21 @@ fn run_individual_test(case BumpTestCase) ? { test_file := os.join_path_single(temp_dir, case.file_name) os.rm(test_file) or {} - os.write_file(test_file, case.contents) ? + os.write_file(test_file, case.contents)? // os.execute_or_exit('${os.quoted_path(vexe)} bump --patch ${os.quoted_path(test_file)}') - patch_lines := os.read_lines(test_file) ? + patch_lines := os.read_lines(test_file)? assert patch_lines[case.line] == case.expected_patch os.execute_or_exit('${os.quoted_path(vexe)} bump --minor ${os.quoted_path(test_file)}') - minor_lines := os.read_lines(test_file) ? + minor_lines := os.read_lines(test_file)? assert minor_lines[case.line] == case.expected_minor os.execute_or_exit('${os.quoted_path(vexe)} bump --major ${os.quoted_path(test_file)}') - major_lines := os.read_lines(test_file) ? + major_lines := os.read_lines(test_file)? assert major_lines[case.line] == case.expected_major // - os.rm(test_file) ? + os.rm(test_file)? } fn test_all_bump_cases() { diff --git a/cmd/tools/vcreate_test.v b/cmd/tools/vcreate_test.v index 3d07f4773a..ecf9e0e665 100644 --- a/cmd/tools/vcreate_test.v +++ b/cmd/tools/vcreate_test.v @@ -5,7 +5,7 @@ const test_path = 'vcreate_test' fn init_and_check() ? { os.execute_or_exit('${os.quoted_path(@VEXE)} init') - assert os.read_file('vcreate_test.v') ? == [ + assert os.read_file('vcreate_test.v')? == [ 'module main\n', 'fn main() {', " println('Hello World!')", @@ -13,7 +13,7 @@ fn init_and_check() ? { '', ].join_lines() - assert os.read_file('v.mod') ? == [ + assert os.read_file('v.mod')? == [ 'Module {', " name: 'vcreate_test'", " description: ''", @@ -24,7 +24,7 @@ fn init_and_check() ? { '', ].join_lines() - assert os.read_file('.gitignore') ? == [ + assert os.read_file('.gitignore')? == [ '# Binaries for programs and plugins', 'main', 'vcreate_test', @@ -37,7 +37,7 @@ fn init_and_check() ? { '', ].join_lines() - assert os.read_file('.gitattributes') ? == [ + assert os.read_file('.gitattributes')? == [ '*.v linguist-language=V text=auto eol=lf', '*.vv linguist-language=V text=auto eol=lf', '*.vsh linguist-language=V text=auto eol=lf', @@ -45,7 +45,7 @@ fn init_and_check() ? { '', ].join_lines() - assert os.read_file('.editorconfig') ? == [ + assert os.read_file('.editorconfig')? == [ '[*]', 'charset = utf-8', 'end_of_line = lf', @@ -66,9 +66,9 @@ fn test_v_init() ? { defer { os.rmdir_all(dir) or {} } - os.chdir(dir) ? + os.chdir(dir)? - init_and_check() ? + init_and_check()? } fn test_v_init_in_git_dir() ? { @@ -78,24 +78,24 @@ fn test_v_init_in_git_dir() ? { defer { os.rmdir_all(dir) or {} } - os.chdir(dir) ? + os.chdir(dir)? os.execute_or_exit('git init .') - init_and_check() ? + init_and_check()? } fn test_v_init_no_overwrite_gitignore() ? { dir := os.join_path(os.temp_dir(), test_path) os.rmdir_all(dir) or {} os.mkdir(dir) or {} - os.write_file('$dir/.gitignore', 'blah') ? + os.write_file('$dir/.gitignore', 'blah')? defer { os.rmdir_all(dir) or {} } - os.chdir(dir) ? + os.chdir(dir)? os.execute_or_exit('${os.quoted_path(@VEXE)} init') - assert os.read_file('.gitignore') ? == 'blah' + assert os.read_file('.gitignore')? == 'blah' } fn test_v_init_no_overwrite_gitattributes_and_editorconfig() ? { @@ -114,15 +114,15 @@ indent_size = 4 dir := os.join_path(os.temp_dir(), test_path) os.rmdir_all(dir) or {} os.mkdir(dir) or {} - os.write_file('$dir/.gitattributes', git_attributes_content) ? - os.write_file('$dir/.editorconfig', editor_config_content) ? + os.write_file('$dir/.gitattributes', git_attributes_content)? + os.write_file('$dir/.editorconfig', editor_config_content)? defer { os.rmdir_all(dir) or {} } - os.chdir(dir) ? + os.chdir(dir)? os.execute_or_exit('${os.quoted_path(@VEXE)} init') - assert os.read_file('.gitattributes') ? == git_attributes_content - assert os.read_file('.editorconfig') ? == editor_config_content + assert os.read_file('.gitattributes')? == git_attributes_content + assert os.read_file('.editorconfig')? == editor_config_content } diff --git a/cmd/tools/vdoc/tests/vdoc_file_test.v b/cmd/tools/vdoc/tests/vdoc_file_test.v index 1e92605bc5..7b011d5075 100644 --- a/cmd/tools/vdoc/tests/vdoc_file_test.v +++ b/cmd/tools/vdoc/tests/vdoc_file_test.v @@ -16,7 +16,7 @@ fn find_diff_cmd() string { fn test_vet() ? { os.setenv('VCOLORS', 'never', true) - os.chdir(vroot) ? + os.chdir(vroot)? test_dir := 'cmd/tools/vdoc/tests/testdata' main_files := get_main_files_in_dir(test_dir) fails := check_path(vexe, test_dir, main_files) diff --git a/cmd/tools/vgret.v b/cmd/tools/vgret.v index fbeceeb220..a9ae1c71a0 100644 --- a/cmd/tools/vgret.v +++ b/cmd/tools/vgret.v @@ -142,11 +142,11 @@ fn main() { exit(1) } - opt.config = new_config(opt.root_path, toml_conf) ? + opt.config = new_config(opt.root_path, toml_conf)? gen_in_path := arg_paths[0] if arg_paths.len >= 1 { - generate_screenshots(mut opt, gen_in_path) ? + generate_screenshots(mut opt, gen_in_path)? } if arg_paths.len > 1 { target_path := arg_paths[1] @@ -199,7 +199,7 @@ fn generate_screenshots(mut opt Options, output_path string) ? { if opt.verbose { eprintln('Creating output path `$dst_path`') } - os.mkdir_all(dst_path) ? + os.mkdir_all(dst_path)? } screenshot_path := os.join_path(dst_path, rel_out_path) @@ -332,7 +332,7 @@ fn take_screenshots(opt Options, app AppConfig) ?[]string { // ensure_env returns nothing if everything is okay. fn ensure_env(opt Options) ? { if !os.exists(tmp_dir) { - os.mkdir_all(tmp_dir) ? + os.mkdir_all(tmp_dir)? } if runtime_os !in supported_hosts { @@ -355,9 +355,9 @@ fn vexe() string { fn new_config(root_path string, toml_config string) ?Config { doc := if os.is_file(toml_config) { - toml.parse_file(toml_config) ? + toml.parse_file(toml_config)? } else { - toml.parse_text(toml_config) ? + toml.parse_text(toml_config)? } path := os.real_path(root_path).trim_right('/') diff --git a/cmd/tools/vscan.v b/cmd/tools/vscan.v index 46d08f717d..31d7d155a5 100644 --- a/cmd/tools/vscan.v +++ b/cmd/tools/vscan.v @@ -12,11 +12,11 @@ fn main() { fp.version('0.0.1') fp.description('\nScan .v source files, and print the V tokens contained in them.') fp.arguments_description('PATH [PATH]...') - fp.limit_free_args_to_at_least(1) ? + fp.limit_free_args_to_at_least(1)? pref := pref.new_preferences() mut all_paths := fp.remaining_parameters() for path in all_paths { - mut scanner := scanner.new_scanner_file(path, .parse_comments, pref) ? + mut scanner := scanner.new_scanner_file(path, .parse_comments, pref)? mut tok := token.Token{} for tok.kind != .eof { tok = scanner.scan() diff --git a/cmd/tools/vself.v b/cmd/tools/vself.v index 7774fc6ff4..b13466a592 100644 --- a/cmd/tools/vself.v +++ b/cmd/tools/vself.v @@ -15,7 +15,7 @@ fn main() { short_v_name := vexe_name.all_before('.') // recompilation.must_be_enabled(vroot, 'Please install V from source, to use `$vexe_name self` .') - os.chdir(vroot) ? + os.chdir(vroot)? os.setenv('VCOLORS', 'always', true) args := os.args[1..].filter(it != 'self') jargs := args.join(' ') diff --git a/cmd/tools/vsetup-freetype.v b/cmd/tools/vsetup-freetype.v index 16bbd2e2ea..a0409bcb69 100644 --- a/cmd/tools/vsetup-freetype.v +++ b/cmd/tools/vsetup-freetype.v @@ -11,7 +11,7 @@ fn main() { $if windows { println('Setup freetype...') vroot := os.dir(pref.vexe_path()) - os.chdir(vroot) ? + os.chdir(vroot)? if os.is_dir(freetype_folder) { println('Thirdparty "freetype" is already installed.') } else { diff --git a/cmd/tools/vshader.v b/cmd/tools/vshader.v index aabb82cd99..dfe644f932 100644 --- a/cmd/tools/vshader.v +++ b/cmd/tools/vshader.v @@ -172,7 +172,7 @@ fn compile_shaders(opt Options, input_path string) ? { // Currently sokol-shdc allows for multiple --input flags // - but it's only the last entry that's actually compiled/used // Given this fact - we can only compile one '.glsl' file to one C '.h' header - compile_shader(co, shader_file) ? + compile_shader(co, shader_file)? } } @@ -233,10 +233,10 @@ fn collect(path string, mut list []string) { // tools can be setup or is already in place. fn ensure_external_tools(opt Options) ? { if !os.exists(cache_dir) { - os.mkdir_all(cache_dir) ? + os.mkdir_all(cache_dir)? } if opt.force_update { - download_shdc(opt) ? + download_shdc(opt)? return } @@ -250,7 +250,7 @@ fn ensure_external_tools(opt Options) ? { return } - download_shdc(opt) ? + download_shdc(opt)? } // shdc_exe returns an absolute path to the `sokol-shdc` tool. @@ -277,26 +277,26 @@ fn download_shdc(opt Options) ? { } } if os.exists(file) { - os.rm(file) ? + os.rm(file)? } - mut dtmp_file, dtmp_path := util.temp_file(util.TempFileOptions{ path: os.dir(file) }) ? + mut dtmp_file, dtmp_path := util.temp_file(util.TempFileOptions{ path: os.dir(file) })? dtmp_file.close() if opt.verbose { eprintln('$tool_name downloading sokol-shdc from $download_url') } http.download_file(download_url, dtmp_path) or { - os.rm(dtmp_path) ? + os.rm(dtmp_path)? return error('$tool_name failed to download sokol-shdc needed for shader compiling: $err') } // Make it executable - os.chmod(dtmp_path, 0o775) ? + os.chmod(dtmp_path, 0o775)? // Move downloaded file in place - os.mv(dtmp_path, file) ? + os.mv(dtmp_path, file)? if runtime_os in ['linux', 'macos'] { // Use the .exe file ending to minimize platform friction. - os.mv(file, shdc) ? + os.mv(file, shdc)? } // Update internal version file - os.write_file(shdc_version_file, update_to_shdc_version) ? + os.write_file(shdc_version_file, update_to_shdc_version)? } diff --git a/cmd/tools/vtest-parser.v b/cmd/tools/vtest-parser.v index 0e41a98013..33e50e384d 100644 --- a/cmd/tools/vtest-parser.v +++ b/cmd/tools/vtest-parser.v @@ -54,7 +54,7 @@ fn main() { context.pref = &pref.Preferences{ output_mode: .silent } - mut source := os.read_file(context.path) ? + mut source := os.read_file(context.path)? source = source[..context.cut_index] go fn (ms int) { diff --git a/cmd/tools/vtracev.v b/cmd/tools/vtracev.v index 8fb32ce32f..504886a6ca 100644 --- a/cmd/tools/vtracev.v +++ b/cmd/tools/vtracev.v @@ -6,7 +6,7 @@ import v.pref fn main() { vexe := pref.vexe_path() vroot := os.dir(vexe) - os.chdir(vroot) ? + os.chdir(vroot)? os.setenv('VCOLORS', 'always', true) self_idx := os.args.index('tracev') args := os.args[1..self_idx] diff --git a/cmd/tools/vup.v b/cmd/tools/vup.v index e953d72e26..51d93940bd 100644 --- a/cmd/tools/vup.v +++ b/cmd/tools/vup.v @@ -26,7 +26,7 @@ fn new_app() App { fn main() { app := new_app() recompilation.must_be_enabled(app.vroot, 'Please install V from source, to use `v up` .') - os.chdir(app.vroot) ? + os.chdir(app.vroot)? println('Updating V...') app.update_from_master() v_hash := version.githash(false) diff --git a/cmd/tools/vvet/vet_test.v b/cmd/tools/vvet/vet_test.v index c46e0de525..b4eb2f5512 100644 --- a/cmd/tools/vvet/vet_test.v +++ b/cmd/tools/vvet/vet_test.v @@ -14,7 +14,7 @@ fn find_diff_cmd() string { fn test_vet() ? { vexe := os.getenv('VEXE') vroot := os.dir(vexe) - os.chdir(vroot) ? + os.chdir(vroot)? test_dir := 'cmd/tools/vvet/tests' tests := get_tests_in_dir(test_dir) fails := check_path(vexe, test_dir, tests) diff --git a/cmd/tools/vwatch.v b/cmd/tools/vwatch.v index 0870c1ec44..26afdf1132 100644 --- a/cmd/tools/vwatch.v +++ b/cmd/tools/vwatch.v @@ -313,7 +313,7 @@ fn main() { fp.description('Collect all .v files needed for a compilation, then re-run the compilation when any of the source changes.') fp.arguments_description('[--silent] [--clear] [--ignore .db] [--add /path/to/a/file.v] [run] program.v') fp.allow_unknown_args() - fp.limit_free_args_to_at_least(1) ? + fp.limit_free_args_to_at_least(1)? context.is_worker = fp.bool('vwatchworker', 0, false, 'Internal flag. Used to distinguish vwatch manager and worker processes.') context.silent = fp.bool('silent', `s`, false, 'Be more silent; do not print the watch timestamp before each re-run.') context.clear_terminal = fp.bool('clear', `c`, false, 'Clears the terminal before each re-run.') diff --git a/doc/docs.md b/doc/docs.md index 627e0ca89d..e75c605098 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1303,7 +1303,7 @@ large_index := 999 val := arr[large_index] or { panic('out of bounds') } println(val) // you can also do this, if you want to *propagate* the access error: -val2 := arr[333] ? +val2 := arr[333]? println(val2) ``` @@ -1893,7 +1893,7 @@ enum State { // write log file and return number of bytes written fn write_log(s State) ?int { - mut f := os.create('log.txt') ? + mut f := os.create('log.txt')? defer { f.close() } @@ -3419,7 +3419,7 @@ propagate the error: import net.http fn f(url string) ?string { - resp := http.get(url) ? + resp := http.get(url)? return resp.text } ``` @@ -3937,7 +3937,7 @@ println(user.last_name) println(user.age) // You can also decode JSON arrays: sfoos := '[{"x":123},{"x":456}]' -foos := json.decode([]Foo, sfoos) ? +foos := json.decode([]Foo, sfoos)? println(foos[0].x) println(foos[1].x) ``` @@ -4042,8 +4042,8 @@ If a test function has an error return type, any propagated errors will fail the import strconv fn test_atoi() ? { - assert strconv.atoi('1') ? == 1 - assert strconv.atoi('one') ? == 1 // test will fail + assert strconv.atoi('1')? == 1 + assert strconv.atoi('one')? == 1 // test will fail } ``` @@ -4435,7 +4435,7 @@ struct Customer { country string [nonull] } -db := sqlite.connect('customers.db') ? +db := sqlite.connect('customers.db')? // you can create tables: // CREATE TABLE IF NOT EXISTS `Customer` ( @@ -5356,7 +5356,7 @@ Full list of builtin options: import os fn main() { embedded_file := $embed_file('v.png') - os.write_file('exported.png', embedded_file.to_string()) ? + os.write_file('exported.png', embedded_file.to_string())? } ``` @@ -5380,7 +5380,7 @@ Currently only one compression type is supported: `zlib` import os fn main() { embedded_file := $embed_file('v.png', .zlib) // compressed using zlib - os.write_file('exported.png', embedded_file.to_string()) ? + os.write_file('exported.png', embedded_file.to_string())? } ``` @@ -5833,7 +5833,7 @@ fn sh(cmd string){ rmdir_all('build') or { } // Create build/, never fails as build/ does not exist -mkdir('build') ? +mkdir('build')? // Move *.v files to build/ result := execute('mv *.v build/') @@ -5844,7 +5844,7 @@ if result.exit_code != 0 { sh('ls') // Similar to: -// files := ls('.') ? +// files := ls('.')? // mut count := 0 // if files.len > 0 { // for file in files { diff --git a/examples/buf_reader.v b/examples/buf_reader.v index e754f61cdb..a3f708ef2a 100644 --- a/examples/buf_reader.v +++ b/examples/buf_reader.v @@ -5,9 +5,9 @@ import io fn main() { // Make a new connection - mut conn := net.dial_tcp('google.com:80') ? + mut conn := net.dial_tcp('google.com:80')? // Simple http HEAD request for a file - conn.write_string('GET /index.html HTTP/1.0\r\n\r\n') ? + conn.write_string('GET /index.html HTTP/1.0\r\n\r\n')? // Wrap in a buffered reader mut r := io.new_buffered_reader(reader: conn) for { diff --git a/examples/concurrency/concurrency_http.v b/examples/concurrency/concurrency_http.v index b5b0b5883f..a62348308e 100644 --- a/examples/concurrency/concurrency_http.v +++ b/examples/concurrency/concurrency_http.v @@ -4,7 +4,7 @@ import time fn vlang_time(mut wg sync.WaitGroup) ?string { start := time.ticks() - data := http.get('https://vlang.io/utc_now') ? + data := http.get('https://vlang.io/utc_now')? finish := time.ticks() println('Finish getting time ${finish - start} ms') println(data.text) @@ -14,7 +14,7 @@ fn vlang_time(mut wg sync.WaitGroup) ?string { fn remote_ip(mut wg sync.WaitGroup) ?string { start := time.ticks() - data := http.get('https://api.ipify.org') ? + data := http.get('https://api.ipify.org')? finish := time.ticks() println('Finish getting ip ${finish - start} ms') println(data.text) diff --git a/examples/database/mysql.v b/examples/database/mysql.v index 97e0888583..0e8a594202 100644 --- a/examples/database/mysql.v +++ b/examples/database/mysql.v @@ -8,8 +8,8 @@ fn main() { password: '' dbname: 'mysql' } - conn.connect() ? - res := conn.query('show tables') ? + conn.connect()? + res := conn.query('show tables')? for row in res.rows() { println(row.vals.join(', ')) } diff --git a/examples/database/sqlite.v b/examples/database/sqlite.v index a3c71768ed..623fdd97a1 100644 --- a/examples/database/sqlite.v +++ b/examples/database/sqlite.v @@ -1,7 +1,7 @@ import sqlite fn main() { - db := sqlite.connect(':memory:') ? + db := sqlite.connect(':memory:')? db.exec("create table users (id integer primary key, name text default '');") db.exec("insert into users (name) values ('Sam')") diff --git a/examples/dynamic_library_loading/use.v b/examples/dynamic_library_loading/use.v index 38b7122435..91e2dd9817 100644 --- a/examples/dynamic_library_loading/use.v +++ b/examples/dynamic_library_loading/use.v @@ -7,9 +7,9 @@ type FNAdder = fn (int, int) int fn main() { library_file_path := os.join_path(os.getwd(), dl.get_libname('library')) - handle := dl.open_opt(library_file_path, dl.rtld_lazy) ? + handle := dl.open_opt(library_file_path, dl.rtld_lazy)? eprintln('handle: ${ptr_str(handle)}') - f := FNAdder(dl.sym_opt(handle, 'add_1') ?) + f := FNAdder(dl.sym_opt(handle, 'add_1')?) eprintln('f: ${ptr_str(f)}') res := f(1, 2) eprintln('res: $res') diff --git a/examples/http_server.v b/examples/http_server.v index 9d7b04351c..adeb8fa987 100644 --- a/examples/http_server.v +++ b/examples/http_server.v @@ -34,5 +34,5 @@ fn main() { mut server := Server{ handler: ExampleHandler{} } - server.listen_and_serve() ? + server.listen_and_serve()? } diff --git a/examples/js_dom_cube/cube.js.v b/examples/js_dom_cube/cube.js.v index 198af4b8f8..6f1453bd2f 100644 --- a/examples/js_dom_cube/cube.js.v +++ b/examples/js_dom_cube/cube.js.v @@ -348,19 +348,19 @@ fn animate(mut state State, time f64) { fn main() { canvas, gl := get_webgl() - vertex_buffer := gl.createBuffer() ? + vertex_buffer := gl.createBuffer()? gl.bindBuffer(dom.gl_array_buffer(), vertex_buffer) gl.bufferData(dom.gl_array_buffer(), float32_array(vertices), dom.gl_static_draw()) - color_buffer := gl.createBuffer() ? + color_buffer := gl.createBuffer()? gl.bindBuffer(dom.gl_array_buffer(), color_buffer) gl.bufferData(dom.gl_array_buffer(), float32_array(colors), dom.gl_static_draw()) - index_buffer := gl.createBuffer() ? + index_buffer := gl.createBuffer()? gl.bindBuffer(dom.gl_element_array_buffer(), index_buffer) gl.bufferData(dom.gl_element_array_buffer(), uint16_array(indices), dom.gl_static_draw()) - vert_shader := gl.createShader(dom.gl_vertex_shader()) ? + vert_shader := gl.createShader(dom.gl_vertex_shader())? gl.shaderSource(vert_shader, vert_code.str) gl.compileShader(vert_shader) @@ -368,14 +368,14 @@ fn main() { panic('An error occurred when compiling vertex shader: ${string(gl.getShaderInfoLog(vert_shader))}') } - frag_shader := gl.createShader(dom.gl_fragment_shader()) ? + frag_shader := gl.createShader(dom.gl_fragment_shader())? gl.shaderSource(frag_shader, frag_code.str) gl.compileShader(frag_shader) if !bool(JS.Boolean(gl.getShaderParameter(frag_shader, dom.gl_compile_status()))) { panic('An error occurred when compiling fragment shader: ${string(gl.getShaderInfoLog(frag_shader))}') } - shader_program := gl.createProgram() ? + shader_program := gl.createProgram()? gl.attachShader(shader_program, vert_shader) gl.attachShader(shader_program, frag_shader) gl.linkProgram(shader_program) @@ -384,9 +384,9 @@ fn main() { panic('unable to initialize the shader program: ${string(gl.getProgramInfoLog(shader_program))}') } - pmatrix := gl.getUniformLocation(shader_program, 'Pmatrix'.str) ? - vmatrix := gl.getUniformLocation(shader_program, 'Vmatrix'.str) ? - mmatrix := gl.getUniformLocation(shader_program, 'Mmatrix'.str) ? + pmatrix := gl.getUniformLocation(shader_program, 'Pmatrix'.str)? + vmatrix := gl.getUniformLocation(shader_program, 'Vmatrix'.str)? + mmatrix := gl.getUniformLocation(shader_program, 'Mmatrix'.str)? gl.bindBuffer(dom.gl_array_buffer(), vertex_buffer) position := gl.getAttribLocation(shader_program, 'position'.str) diff --git a/examples/js_dom_draw/draw.js.v b/examples/js_dom_draw/draw.js.v index f14cd1dbd4..7259f2214f 100644 --- a/examples/js_dom_draw/draw.js.v +++ b/examples/js_dom_draw/draw.js.v @@ -32,10 +32,10 @@ mut: fn main() { window := dom.window() document := dom.document - clear_btn := document.getElementById('clearButton'.str) ? - canvas_elem := document.getElementById('canvas'.str) ? + clear_btn := document.getElementById('clearButton'.str)? + canvas_elem := document.getElementById('canvas'.str)? canvas := get_canvas(canvas_elem) - ctx := canvas.getContext('2d'.str, js_undefined()) ? + ctx := canvas.getContext('2d'.str, js_undefined())? context := match ctx { JS.CanvasRenderingContext2D { ctx diff --git a/examples/net_peer_ip.v b/examples/net_peer_ip.v index 7f84deb98f..9c45c08b94 100644 --- a/examples/net_peer_ip.v +++ b/examples/net_peer_ip.v @@ -1,5 +1,5 @@ import net -conn := net.dial_tcp('google.com:80') ? -peer_addr := conn.peer_addr() ? +conn := net.dial_tcp('google.com:80')? +peer_addr := conn.peer_addr()? println('$peer_addr') diff --git a/examples/net_raw_http.v b/examples/net_raw_http.v index 5cfb61a631..08a2c3f901 100644 --- a/examples/net_raw_http.v +++ b/examples/net_raw_http.v @@ -3,18 +3,18 @@ import io fn main() { // Make a new connection - mut conn := net.dial_tcp('google.com:80') ? + mut conn := net.dial_tcp('google.com:80')? defer { conn.close() or {} } - println(' peer: ${conn.peer_addr() ?}') - println('local: ${conn.addr() ?}') + println(' peer: ${conn.peer_addr()?}') + println('local: ${conn.addr()?}') // Simple http HEAD request for a file - conn.write_string('HEAD /index.html HTTP/1.0\r\n\r\n') ? + conn.write_string('HEAD /index.html HTTP/1.0\r\n\r\n')? // Read all the data that is waiting - result := io.read_all(reader: conn) ? + result := io.read_all(reader: conn)? // Cast to string and print result println(result.bytestr()) } diff --git a/examples/net_t.v b/examples/net_t.v index 8e8255a8d1..38b9011c10 100644 --- a/examples/net_t.v +++ b/examples/net_t.v @@ -4,7 +4,7 @@ import time fn send_request(mut wg sync.WaitGroup) ?string { start := time.ticks() - data := http.get('https://google.com') ? + data := http.get('https://google.com')? finish := time.ticks() println('Finish getting time ${finish - start} ms') wg.done() diff --git a/examples/net_udp_server_and_client.v b/examples/net_udp_server_and_client.v index 03a3e0b189..7aa0ef6690 100644 --- a/examples/net_udp_server_and_client.v +++ b/examples/net_udp_server_and_client.v @@ -12,7 +12,7 @@ fn main() { mut buf := []u8{len: 100} if is_server { println('UDP echo server, listening for udp packets on port: $port') - mut c := net.listen_udp(':$port') ? + mut c := net.listen_udp(':$port')? for { read, addr := c.read(mut buf) or { continue } println('received $read bytes from $addr') @@ -23,7 +23,7 @@ fn main() { } } else { println('UDP client, sending packets to port: ${port}.\nType `exit` to exit.') - mut c := net.dial_udp('localhost:$port') ? + mut c := net.dial_udp('localhost:$port')? for { mut line := os.input('client > ') match line { @@ -36,8 +36,8 @@ fn main() { } else {} } - c.write_string(line) ? - read, _ := c.read(mut buf) ? + c.write_string(line)? + read, _ := c.read(mut buf)? println('server : ' + buf[0..read].bytestr()) } } diff --git a/examples/pendulum-simulation/animation.v b/examples/pendulum-simulation/animation.v index 369efd2645..fe48e7ca04 100644 --- a/examples/pendulum-simulation/animation.v +++ b/examples/pendulum-simulation/animation.v @@ -6,7 +6,7 @@ import sim.anim import sim.args as simargs fn main() { - args := simargs.parse_args(extra_workers: 1) ? as simargs.ParallelArgs + args := simargs.parse_args(extra_workers: 1)? as simargs.ParallelArgs mut app := anim.new_app(args) mut workers := []thread{cap: args.workers} diff --git a/examples/pendulum-simulation/full.v b/examples/pendulum-simulation/full.v index 301e629caf..b72140769e 100644 --- a/examples/pendulum-simulation/full.v +++ b/examples/pendulum-simulation/full.v @@ -7,11 +7,11 @@ import sim.args as simargs import sim.img fn main() { - args := simargs.parse_args(extra_workers: 2) ? as simargs.ParallelArgs + args := simargs.parse_args(extra_workers: 2)? as simargs.ParallelArgs img_settings := img.image_settings_from_grid(args.grid) - mut writer := img.ppm_writer_for_fname(args.filename, img_settings) ? + mut writer := img.ppm_writer_for_fname(args.filename, img_settings)? mut app := anim.new_app(args) mut workers := []thread{cap: args.workers + 1} diff --git a/examples/pendulum-simulation/modules/sim/args/parser.v b/examples/pendulum-simulation/modules/sim/args/parser.v index 88578982e1..56ff96e63a 100644 --- a/examples/pendulum-simulation/modules/sim/args/parser.v +++ b/examples/pendulum-simulation/modules/sim/args/parser.v @@ -33,10 +33,10 @@ pub type SimArgs = ParallelArgs | SequentialArgs pub fn parse_args(config ParserSettings) ?SimArgs { if config.sequential { - args := parse_sequential_args() ? + args := parse_sequential_args()? return SimArgs(args) } else { - args := parse_parallel_args(config.extra_workers) ? + args := parse_parallel_args(config.extra_workers)? return SimArgs(args) } } @@ -45,7 +45,7 @@ fn parse_sequential_args() ?SequentialArgs { mut fp := flag.new_flag_parser(os.args) fp.application('vps') fp.version('v0.1.0') - fp.limit_free_args(0, 0) ? + fp.limit_free_args(0, 0)? fp.description('This is a pendulum simulation written in pure V') fp.skip_executable() @@ -96,7 +96,7 @@ fn parse_parallel_args(extra_workers int) ?ParallelArgs { mut fp := flag.new_flag_parser(os.args) fp.application('vps') fp.version('v0.1.0') - fp.limit_free_args(0, 0) ? + fp.limit_free_args(0, 0)? fp.description('This is a pendulum simulation written in pure V') fp.skip_executable() diff --git a/examples/pendulum-simulation/modules/sim/img/ppm.v b/examples/pendulum-simulation/modules/sim/img/ppm.v index e6c940085e..bb1517f27d 100644 --- a/examples/pendulum-simulation/modules/sim/img/ppm.v +++ b/examples/pendulum-simulation/modules/sim/img/ppm.v @@ -44,19 +44,19 @@ pub fn ppm_writer_for_fname(fname string, settings ImageSettings) ?&PPMWriter { cache_size: settings.cache_size cache: []u8{cap: settings.cache_size} } - writer.start_for_file(fname, settings) ? + writer.start_for_file(fname, settings)? return writer } pub fn (mut writer PPMWriter) start_for_file(fname string, settings ImageSettings) ? { - writer.file = os.create(fname) ? - writer.file.writeln('P6 $settings.width $settings.height 255') ? + writer.file = os.create(fname)? + writer.file.writeln('P6 $settings.width $settings.height 255')? } pub fn (mut writer PPMWriter) handle_pixel(p gx.Color) ? { if writer.cache.len >= writer.cache_size { - writer.write() ? - writer.flush() ? + writer.write()? + writer.flush()? } writer.cache << [p.r, p.g, p.b] } @@ -66,7 +66,7 @@ pub fn (mut writer PPMWriter) flush() ? { } pub fn (mut writer PPMWriter) write() ? { - writer.file.write(writer.cache) ? + writer.file.write(writer.cache)? } pub fn (mut writer PPMWriter) close() { diff --git a/examples/pendulum-simulation/parallel.v b/examples/pendulum-simulation/parallel.v index 809976dadd..8412885226 100644 --- a/examples/pendulum-simulation/parallel.v +++ b/examples/pendulum-simulation/parallel.v @@ -6,7 +6,7 @@ import sim.args as simargs import sim.img fn main() { - args := simargs.parse_args() ? as simargs.ParallelArgs + args := simargs.parse_args()? as simargs.ParallelArgs img_settings := img.image_settings_from_grid(args.grid) @@ -17,7 +17,7 @@ fn main() { request_chan := chan &sim.SimRequest{cap: args.workers} result_chan := chan &sim.SimResult{cap: args.workers} - mut writer := img.ppm_writer_for_fname(args.filename, img_settings) ? + mut writer := img.ppm_writer_for_fname(args.filename, img_settings)? mut image_writer := img.new_image_writer(mut writer, img_settings) mut workers := []thread{cap: args.workers} diff --git a/examples/pendulum-simulation/parallel_with_iw.v b/examples/pendulum-simulation/parallel_with_iw.v index c2feed3708..eeab7b9010 100644 --- a/examples/pendulum-simulation/parallel_with_iw.v +++ b/examples/pendulum-simulation/parallel_with_iw.v @@ -6,14 +6,14 @@ import sim.args as simargs import sim.img fn main() { - args := simargs.parse_args(extra_workers: 1) ? as simargs.ParallelArgs + args := simargs.parse_args(extra_workers: 1)? as simargs.ParallelArgs img_settings := img.image_settings_from_grid(args.grid) request_chan := chan &sim.SimRequest{cap: args.workers} result_chan := chan &sim.SimResult{cap: args.workers} - mut writer := img.ppm_writer_for_fname(args.filename, img_settings) ? + mut writer := img.ppm_writer_for_fname(args.filename, img_settings)? mut workers := []thread{cap: args.workers + 1} mut bmark := benchmark.start() diff --git a/examples/pendulum-simulation/sequential.v b/examples/pendulum-simulation/sequential.v index 9ec41a38d3..9437400a15 100644 --- a/examples/pendulum-simulation/sequential.v +++ b/examples/pendulum-simulation/sequential.v @@ -6,14 +6,14 @@ import sim.args as simargs import sim.img fn main() { - args := simargs.parse_args(sequential: true) ? as simargs.SequentialArgs + args := simargs.parse_args(sequential: true)? as simargs.SequentialArgs mut bmark := benchmark.start() defer { bmark.measure(@FN) } - mut writer := img.ppm_writer_for_fname(args.filename, img.image_settings_from_grid(args.grid)) ? + mut writer := img.ppm_writer_for_fname(args.filename, img.image_settings_from_grid(args.grid))? defer { writer.close() } @@ -26,5 +26,5 @@ fn main() { sim.run(args.params, grid: args.grid, on_request: sim.SimRequestHandler(handle_request)) - writer.write() ? + writer.write()? } diff --git a/examples/random_ips.v b/examples/random_ips.v index c570ef81d3..b4fd6a584a 100644 --- a/examples/random_ips.v +++ b/examples/random_ips.v @@ -2,6 +2,6 @@ import rand fn main() { for _ in 0 .. 10 { - println('${rand.intn(255) ?}.${rand.intn(255) ?}.${rand.intn(255) ?}.${rand.intn(255) ?}') + println('${rand.intn(255)?}.${rand.intn(255)?}.${rand.intn(255)?}.${rand.intn(255)?}') } } diff --git a/examples/sokol/sounds/wav_player.v b/examples/sokol/sounds/wav_player.v index ce06366df3..b781be3ac2 100644 --- a/examples/sokol/sounds/wav_player.v +++ b/examples/sokol/sounds/wav_player.v @@ -12,10 +12,10 @@ mut: fn main() { if os.args.len < 2 { eprintln('Usage: play_wav file1.wav file2.wav ...') - play_sounds([os.resource_abs_path('uhoh.wav')]) ? + play_sounds([os.resource_abs_path('uhoh.wav')])? exit(1) } - play_sounds(os.args[1..]) ? + play_sounds(os.args[1..])? } fn play_sounds(files []string) ? { @@ -31,7 +31,7 @@ fn play_sounds(files []string) ? { eprintln('skipping "$f" (not a .wav file)') continue } - player.play_wav_file(f) ? + player.play_wav_file(f)? } player.stop() } @@ -67,7 +67,7 @@ fn (mut p Player) stop() { fn (mut p Player) play_wav_file(fpath string) ? { println('> play_wav_file: $fpath') - samples := read_wav_file_samples(fpath) ? + samples := read_wav_file_samples(fpath)? p.finished = true p.samples << samples p.finished = false @@ -119,7 +119,7 @@ struct RIFFFormat { fn read_wav_file_samples(fpath string) ?[]f32 { mut res := []f32{} // eprintln('> read_wav_file_samples: $fpath -------------------------------------------------') - mut bytes := os.read_bytes(fpath) ? + mut bytes := os.read_bytes(fpath)? mut pbytes := &u8(bytes.data) mut offset := u32(0) rh := unsafe { &RIFFHeader(pbytes) } diff --git a/examples/tcp_echo_server.v b/examples/tcp_echo_server.v index e5a0973263..5c50f4640c 100644 --- a/examples/tcp_echo_server.v +++ b/examples/tcp_echo_server.v @@ -9,11 +9,11 @@ import net // telnet 127.0.0.1 12345 fn main() { - mut server := net.listen_tcp(.ip6, ':12345') ? - laddr := server.addr() ? + mut server := net.listen_tcp(.ip6, ':12345')? + laddr := server.addr()? eprintln('Listen on $laddr ...') for { - mut socket := server.accept() ? + mut socket := server.accept()? go handle_client(mut socket) } } diff --git a/examples/tcp_notify_echo_server.v b/examples/tcp_notify_echo_server.v index 0e2d0bf9bb..b20cbe000b 100644 --- a/examples/tcp_notify_echo_server.v +++ b/examples/tcp_notify_echo_server.v @@ -14,21 +14,21 @@ fn main() { } // create TCP listener - mut listener := net.listen_tcp(.ip, 'localhost:9001') ? + mut listener := net.listen_tcp(.ip, 'localhost:9001')? defer { listener.close() or {} } - addr := listener.addr() ? + addr := listener.addr()? eprintln('Listening on $addr') eprintln('Type `stop` to stop the server') // create file descriptor notifier - mut notifier := notify.new() ? + mut notifier := notify.new()? defer { notifier.close() or {} } - notifier.add(os.stdin().fd, .read) ? - notifier.add(listener.sock.handle, .read) ? + notifier.add(os.stdin().fd, .read)? + notifier.add(listener.sock.handle, .read)? for { for event in notifier.wait(time.infinite) { diff --git a/examples/term.ui/cursor_chaser.v b/examples/term.ui/cursor_chaser.v index dd987e6dba..df83dbbd2e 100644 --- a/examples/term.ui/cursor_chaser.v +++ b/examples/term.ui/cursor_chaser.v @@ -96,5 +96,5 @@ fn main() { event_fn: event hide_cursor: true ) - app.tui.run() ? + app.tui.run()? } diff --git a/examples/term.ui/event_viewer.v b/examples/term.ui/event_viewer.v index f9c443fd87..75f9d39339 100644 --- a/examples/term.ui/event_viewer.v +++ b/examples/term.ui/event_viewer.v @@ -43,5 +43,5 @@ fn main() { use_alternate_buffer: false ) println('V term.ui event viewer (press `esc` to exit)\n\n') - app.tui.run() ? + app.tui.run()? } diff --git a/examples/term.ui/pong.v b/examples/term.ui/pong.v index 375261f769..48e3338d6e 100644 --- a/examples/term.ui/pong.v +++ b/examples/term.ui/pong.v @@ -495,5 +495,5 @@ fn main() { hide_cursor: true frame_rate: 60 ) - app.tui.run() ? + app.tui.run()? } diff --git a/examples/term.ui/rectangles.v b/examples/term.ui/rectangles.v index f71be145c2..36c0aa7c60 100644 --- a/examples/term.ui/rectangles.v +++ b/examples/term.ui/rectangles.v @@ -93,5 +93,5 @@ fn main() { hide_cursor: true frame_rate: 60 ) - app.tui.run() ? + app.tui.run()? } diff --git a/examples/term.ui/term_drawing.v b/examples/term.ui/term_drawing.v index df08cb78f0..d04904230d 100644 --- a/examples/term.ui/term_drawing.v +++ b/examples/term.ui/term_drawing.v @@ -125,7 +125,7 @@ fn main() { app.mouse_pos.x = 40 app.mouse_pos.y = 15 app.ui.clear() - app.ui.run() ? + app.ui.run()? } fn frame(x voidptr) { diff --git a/examples/term.ui/text_editor.v b/examples/term.ui/text_editor.v index 8d19be5baa..fd4dd24e3d 100644 --- a/examples/term.ui/text_editor.v +++ b/examples/term.ui/text_editor.v @@ -649,5 +649,5 @@ fn main() { event_fn: event capture_events: true ) - a.tui.run() ? + a.tui.run()? } diff --git a/examples/term.ui/vyper.v b/examples/term.ui/vyper.v index 5a5f4cbcb0..eedcde6687 100644 --- a/examples/term.ui/vyper.v +++ b/examples/term.ui/vyper.v @@ -471,5 +471,5 @@ fn main() { hide_cursor: true frame_rate: 10 ) - app.termui.run() ? + app.termui.run()? } diff --git a/examples/v_script.vsh b/examples/v_script.vsh index 89f033b779..121b13e487 100755 --- a/examples/v_script.vsh +++ b/examples/v_script.vsh @@ -9,24 +9,24 @@ for _ in 0 .. 3 { } println('\nMaking dir "v_script_dir".') -mkdir('v_script_dir') ? +mkdir('v_script_dir')? println("\nEntering into v_script_dir and listing it's files.") -chdir('v_script_dir') ? +chdir('v_script_dir')? files := ls('.') or { panic(err) } println(files) println('\nCreating foo.txt') -create('foo.txt') ? +create('foo.txt')? println('\nFiles:') again_ls := ls('.') or { panic(err) } println(again_ls) println('\nRemoving foo.txt and v_script_dir') -rm('foo.txt') ? -chdir('../') ? -rmdir('v_script_dir') ? +rm('foo.txt')? +chdir('../')? +rmdir('v_script_dir')? print('\nDoes v_script_dir still exist? ') println(exists('v_script_dir')) diff --git a/examples/viewer/file_scan.v b/examples/viewer/file_scan.v index da84fc1376..119c03e7bf 100644 --- a/examples/viewer/file_scan.v +++ b/examples/viewer/file_scan.v @@ -153,7 +153,7 @@ fn (item_list Item_list) get_file_path() string { fn (mut item_list Item_list) scan_folder(path string, in_index int) ? { println('Scanning [$path]') mut folder_list := []string{} - lst := os.ls(path) ? + lst := os.ls(path)? // manage the single files for c, x in lst { @@ -171,7 +171,7 @@ fn (mut item_list Item_list) scan_folder(path string, in_index int) ? { if ext == .zip { item.i_type = .zip item_list.lst << item - item_list.scan_zip(pt, item_list.lst.len - 1) ? + item_list.scan_zip(pt, item_list.lst.len - 1)? continue } if is_image(ext) == true { @@ -194,7 +194,7 @@ fn (mut item_list Item_list) scan_folder(path string, in_index int) ? { i_type: .folder } item_list.lst << item - item_list.scan_folder(pt, item_list.lst.len - 1) ? + item_list.scan_folder(pt, item_list.lst.len - 1)? } // println(item_list.lst.len) // println("==================================") diff --git a/examples/viewer/zip_container.v b/examples/viewer/zip_container.v index 5f06a746b7..0c8bde0b49 100644 --- a/examples/viewer/zip_container.v +++ b/examples/viewer/zip_container.v @@ -13,12 +13,12 @@ import szip fn (mut il Item_list) scan_zip(path string, in_index int) ? { println('Scanning ZIP [$path]') - mut zp := szip.open(path, szip.CompressionLevel.no_compression, szip.OpenMode.read_only) ? - n_entries := zp.total() ? + mut zp := szip.open(path, szip.CompressionLevel.no_compression, szip.OpenMode.read_only)? + n_entries := zp.total()? // println(n_entries) for index in 0 .. n_entries { - zp.open_entry_by_index(index) ? - is_dir := zp.is_dir() ? + zp.open_entry_by_index(index)? + is_dir := zp.is_dir()? name := zp.name() size := zp.size() // println("$index ${name} ${size:10} $is_dir") @@ -58,15 +58,15 @@ fn (mut app App) load_texture_from_zip() ?(gfx.Image, int, int) { } app.zip_index = item.container_index // println("Opening the zip [${item.path}]") - app.zip = szip.open(item.path, szip.CompressionLevel.no_compression, szip.OpenMode.read_only) ? + app.zip = szip.open(item.path, szip.CompressionLevel.no_compression, szip.OpenMode.read_only)? } // println("Now get the image") - app.zip.open_entry_by_index(item.container_item_index) ? + app.zip.open_entry_by_index(item.container_item_index)? zip_entry_size := int(item.size) app.resize_buf_if_needed(zip_entry_size) - app.zip.read_entry_buf(app.mem_buf, app.mem_buf_size) ? + app.zip.read_entry_buf(app.mem_buf, app.mem_buf_size)? app.zip.close_entry() return app.load_texture_from_buffer(app.mem_buf, zip_entry_size) } diff --git a/examples/vpwgen.v b/examples/vpwgen.v index c12e75d87b..ea04ebb2a4 100644 --- a/examples/vpwgen.v +++ b/examples/vpwgen.v @@ -10,7 +10,7 @@ fn main() { for _ in 0 .. repeats { mut sb := strings.new_builder(blocksize) for { - x := rand.read(blocksize) ? + x := rand.read(blocksize)? for c in x { if c >= `0` && c <= `~` { sb.write_u8(c) diff --git a/examples/vweb/vweb_assets/vweb_assets.v b/examples/vweb/vweb_assets/vweb_assets.v index 1033f7ea8f..97fda32cc2 100644 --- a/examples/vweb/vweb_assets/vweb_assets.v +++ b/examples/vweb/vweb_assets/vweb_assets.v @@ -17,7 +17,7 @@ fn main() { mut app := &App{} app.serve_static('/favicon.ico', 'favicon.ico') // Automatically make available known static mime types found in given directory. - os.chdir(os.dir(os.executable())) ? + os.chdir(os.dir(os.executable()))? app.handle_static('assets', true) vweb.run(app, port) } diff --git a/examples/websocket/client-server/client.v b/examples/websocket/client-server/client.v index b039415936..eac41cafb5 100644 --- a/examples/websocket/client-server/client.v +++ b/examples/websocket/client-server/client.v @@ -8,7 +8,7 @@ import term // it connects to the server who will broadcast your messages // to all other connected clients fn main() { - mut ws := start_client() ? + mut ws := start_client()? println(term.green('client $ws.id ready')) println('Write message and enter to send...') for { @@ -16,7 +16,7 @@ fn main() { if line == '' { break } - ws.write_string(line) ? + ws.write_string(line)? } ws.close(1000, 'normal') or { println(term.red('panicing $err')) } unsafe { @@ -25,7 +25,7 @@ fn main() { } fn start_client() ?&websocket.Client { - mut ws := websocket.new_client('ws://localhost:30000') ? + mut ws := websocket.new_client('ws://localhost:30000')? // mut ws := websocket.new_client('wss://echo.websocket.org:443')? // use on_open_ref if you want to send any reference object ws.on_open(fn (mut ws websocket.Client) ? { diff --git a/examples/websocket/client-server/server.v b/examples/websocket/client-server/server.v index db419131db..d60aaa71af 100644 --- a/examples/websocket/client-server/server.v +++ b/examples/websocket/client-server/server.v @@ -6,7 +6,7 @@ import term // this server accepts client connections and broadcast all messages to other connected clients fn main() { println('press ctrl-c to quit...') - start_server() ? + start_server()? } fn start_server() ? { @@ -20,7 +20,7 @@ fn start_server() ? { return false } return true - }) ? + })? // on_message_ref, broadcast all incoming messages to all clients except the one sent it s.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut m websocket.Server) ? { diff --git a/examples/websocket/ping.v b/examples/websocket/ping.v index 3599ec37c3..23f027c340 100644 --- a/examples/websocket/ping.v +++ b/examples/websocket/ping.v @@ -25,7 +25,7 @@ fn start_server() ? { return false } return true - }) ? + })? s.on_message(fn (mut ws websocket.Client, msg &websocket.Message) ? { ws.write(msg.payload, msg.opcode) or { panic(err) } }) @@ -41,7 +41,7 @@ fn start_server() ? { // start_client starts the websocket client, it writes a message to // the server and prints all the messages received fn start_client() ? { - mut ws := websocket.new_client('ws://localhost:30000') ? + mut ws := websocket.new_client('ws://localhost:30000')? // mut ws := websocket.new_client('wss://echo.websocket.org:443')? // use on_open_ref if you want to send any reference object ws.on_open(fn (mut ws websocket.Client) ? { @@ -64,7 +64,7 @@ fn start_client() ? { }) // you can add any pointer reference to use in callback // t := TestRef{count: 10} - // ws.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, r &SomeRef)? { + // ws.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, r &SomeRef) ? { // // println('type: $msg.opcode payload:\n$msg.payload ref: $r') // }, &r) ws.connect() or { println('error on connect: $err') } diff --git a/thirdparty/stdatomic/nix/cpp/gen.v b/thirdparty/stdatomic/nix/cpp/gen.v index 1ef52022b3..6e0b6868ae 100644 --- a/thirdparty/stdatomic/nix/cpp/gen.v +++ b/thirdparty/stdatomic/nix/cpp/gen.v @@ -85,15 +85,15 @@ fn find_file(search_paths []string, file string) ?string { } fn patch_atomic(outfile string, infile string) ? { - lines := os.read_file(infile) ?.split('\n') + lines := os.read_file(infile)?.split('\n') outlines := lines.filter(!it.contains('atomic(const atomic&) = delete;')) outtext := outlines.join('\n').replace('#include ', '#include "bitsatomicbase.h"') - os.write_file(outfile, outtext) ? + os.write_file(outfile, outtext)? } fn patch_bitsatomicbase(outfile string, infile string) ? { - lines := os.read_file(infile) ?.split('\n') + lines := os.read_file(infile)?.split('\n') outlines := lines.filter(!it.contains('__atomic_base(const __atomic_base&) = delete;')) outtext := outlines.join('\n').replace('#include ', '#include "bitsatomicbase.h"') - os.write_file(outfile, outtext) ? + os.write_file(outfile, outtext)? } diff --git a/tutorials/building_a_simple_web_blog_with_vweb/README.md b/tutorials/building_a_simple_web_blog_with_vweb/README.md index fe1a611f21..05c8698f14 100644 --- a/tutorials/building_a_simple_web_blog_with_vweb/README.md +++ b/tutorials/building_a_simple_web_blog_with_vweb/README.md @@ -5,21 +5,21 @@ Hello, In this guide, we'll build a simple web blog in V. The benefits of using V for web: + - A safe, fast, language with the development agility of Python or Ruby and -the performance of C. + the performance of C. - Zero dependencies: everything you need for web development comes with the language -in a 1 MB package. + in a 1 MB package. - Very small resulting binaries: the blog we'll create in this tutorial is about 150 KB. -- Easy deployments: a single binary file that even includes the precompiled templates. +- Easy deployments: a single binary file that even includes the precompiled templates. - Runs on the cheapest hardware with minimum footprint: for most apps a $3 instance -is enough. + is enough. - Fast development without any boilerplate. -*Please note that V and Vweb are at a very early stage and are changing rapidly.* +_Please note that V and Vweb are at a very early stage and are changing rapidly._ The code is available here. - ### Installing V ``` @@ -32,17 +32,15 @@ sudo ./v symlink Now V should be globally available on your system. > On macOS use `v_macos.zip`, on Windows - `v_windows.zip`. -If you use a BSD system, Solaris, Android, or simply want to install V -from source, follow the simple instructions here: -https://github.com/vlang/v#installing-v-from-source - +> If you use a BSD system, Solaris, Android, or simply want to install V +> from source, follow the simple instructions here: +> https://github.com/vlang/v#installing-v-from-source ### Install SQLite development dependency If you don't have it already installed, look at the [`sqlite` README](../../vlib/sqlite/README.md) for instructions. - ### Creating a new Vweb project V projects can be created anywhere and don't need to have a certain structure: @@ -94,7 +92,6 @@ with an MVC web framework, you can think of it as a controller. (Vweb is not an MVC framework however.) It embeds the vweb Context object, that's why we get access to methods like `.text()`. - As you can see, there are no routing rules. The `index()` action handles the `/` request by default. Vweb often uses convention over configuration and adding a new action requires no routing rules either: @@ -109,29 +106,27 @@ fn (mut app App) time() vweb.Result { } ``` - ->TIP: run the following command to live-reload the server: `v watch run blog.v` +> TIP: run the following command to live-reload the server: `v watch run blog.v` The `.text(string)` method returns a plain text document with the provided text, which isn't frequently used in websites. - ### HTML View Let's return an HTML view instead. Create `index.html` in the same directory: ```html - - V Blog - - - @message -
- - + + V Blog + + + @message +
+ + ``` @@ -169,14 +164,13 @@ that's done by the `$vweb.html()` line. (`$` always means compile time actions in V.) offering the following benefits: - Great performance, since the templates don't need to be compiled -on every request, like in almost every major web framework. + on every request, like in almost every major web framework. -- Easier deployment, since all your HTML templates are compiled -into a single binary file together with the web application itself. +- Easier deployment, since all your HTML templates are compiled + into a single binary file together with the web application itself. - All errors in the templates are guaranteed to be caught during compilation. - ### Fetching data with V ORM Now let's display some articles! @@ -184,7 +178,6 @@ Now let's display some articles! We'll be using V's builtin ORM and a SQLite database. (V ORM will also support MySQL, Postgre, and SQL Server soon.) - Add a SQLite handle to `App`: ```v oksyntax @@ -199,14 +192,11 @@ pub mut: } ``` - - In `fn main()` we'll connect to a database. Code in the `main()` function is run only once during app's startup, so we are going to have one DB connection for all requests. This improves the performance of the web application, since a DB connection doesn't have to be set up for each request. - ```v oksyntax // blog.v fn main() { @@ -268,17 +258,16 @@ pub fn (app &App) index() vweb.Result { } ``` - Finally, let's update our view: ```html - @for article in articles -
- @article.title
- @article.text -
- @end + @for article in articles +
+ @article.title
+ @article.text +
+ @end ``` @@ -323,23 +312,22 @@ article := app.retrieve_article(10) or { } ``` - ### Adding new articles Create `new.html`: ```html - - V Blog - - -
-
- - -
- + + V Blog + + +
+
+ + +
+ ``` @@ -373,7 +361,7 @@ not necessary). We need to update `index.html` to add a link to the "new article" page: ```html -New article +New article ``` Next we need to add the HTML endpoint to our code like we did with `index.html`: @@ -387,7 +375,6 @@ pub fn (mut app App) new() vweb.Result { Re-running this code will now allow us to add new posts to our blog endpoint - ### JSON endpoints This tutorial used the traditional server-side rendering. If you prefer @@ -406,10 +393,10 @@ pub fn (mut app App) articles() vweb.Result { } ``` - ### Persistent data + If one wants to persist data they need to use a file instead of memory SQLite Database. Replace the db setup code with this instead: @@ -422,7 +409,6 @@ If the database file doesn't exist it will create it. The second command will create the table `Article` if none exists already. Now every time the app is run you will see the articles created from the previous executions - To be continued... For an example of a more sophisticated web app written in V, check out Vorum: https://github.com/vlang/vorum diff --git a/vlib/arrays/README.md b/vlib/arrays/README.md index 8028cd6c4c..d370d180f9 100644 --- a/vlib/arrays/README.md +++ b/vlib/arrays/README.md @@ -9,8 +9,8 @@ import arrays fn main() { a := [1, 5, 7, 0, 9] - assert arrays.min(a) ? == 0 - assert arrays.max(a) ? == 9 - assert arrays.idx_min(a) ? == 3 + assert arrays.min(a)? == 0 + assert arrays.max(a)? == 9 + assert arrays.idx_min(a)? == 3 } ``` diff --git a/vlib/arrays/arrays.v b/vlib/arrays/arrays.v index 6be23995f2..431dc50de2 100644 --- a/vlib/arrays/arrays.v +++ b/vlib/arrays/arrays.v @@ -369,7 +369,7 @@ pub fn upper_bound(arr []T, val T) ?T { // binary search, requires `arr` to be sorted, returns index of found item or error. // Binary searches on sorted lists can be faster than other array searches because at maximum // the algorithm only has to traverse log N elements -// Example: arrays.binary_search([1, 2, 3, 4], 4) ? // => 3 +// Example: arrays.binary_search([1, 2, 3, 4], 4)? // => 3 pub fn binary_search(arr []T, target T) ?int { mut left := 0 mut right := arr.len - 1 diff --git a/vlib/arrays/arrays_test.v b/vlib/arrays/arrays_test.v index 06832e930e..43afd49b34 100644 --- a/vlib/arrays/arrays_test.v +++ b/vlib/arrays/arrays_test.v @@ -2,61 +2,61 @@ module arrays fn test_min() ? { a := [8, 2, 6, 4] - mut ri := min(a) ? + mut ri := min(a)? assert ri == 2 - ri = min(a[2..]) ? + ri = min(a[2..])? assert ri == 4 b := [f32(5.1), 3.1, 1.1, 9.1] - mut rf := min(b) ? + mut rf := min(b)? assert rf == f32(1.1) - rf = min(b[..2]) ? + rf = min(b[..2])? assert rf == f32(3.1) c := [u8(4), 9, 3, 1] - mut rb := min(c) ? + mut rb := min(c)? assert rb == u8(1) - rb = min(c[..3]) ? + rb = min(c[..3])? assert rb == u8(3) } fn test_max() ? { a := [8, 2, 6, 4] - mut ri := max(a) ? + mut ri := max(a)? assert ri == 8 - ri = max(a[1..]) ? + ri = max(a[1..])? assert ri == 6 b := [f32(5.1), 3.1, 1.1, 9.1] - mut rf := max(b) ? + mut rf := max(b)? assert rf == f32(9.1) - rf = max(b[..3]) ? + rf = max(b[..3])? assert rf == f32(5.1) c := [u8(4), 9, 3, 1] - mut rb := max(c) ? + mut rb := max(c)? assert rb == u8(9) - rb = max(c[2..]) ? + rb = max(c[2..])? assert rb == u8(3) } fn test_idx_min() ? { a := [8, 2, 6, 4] - ri := idx_min(a) ? + ri := idx_min(a)? assert ri == 1 b := [f32(5.1), 3.1, 1.1, 9.1] - rf := idx_min(b) ? + rf := idx_min(b)? assert rf == 2 c := [u8(4), 9, 3, 1] - rb := idx_min(c) ? + rb := idx_min(c)? assert rb == 3 } fn test_idx_max() ? { a := [8, 2, 6, 4] - ri := idx_max(a) ? + ri := idx_max(a)? assert ri == 0 b := [f32(5.1), 3.1, 1.1, 9.1] - rf := idx_max(b) ? + rf := idx_max(b)? assert rf == 3 c := [u8(4), 9, 3, 1] - rb := idx_max(c) ? + rb := idx_max(c)? assert rb == 1 } @@ -197,7 +197,7 @@ fn test_concat_string() { fn test_binary_search() ? { a := [1, 3, 3, 4, 5, 6, 7, 8, 10] - assert binary_search(a, 3) ? == 1 + assert binary_search(a, 3)? == 1 assert (binary_search(a, 0) or { -1 }) == -1 } @@ -205,18 +205,18 @@ fn test_lower_bound() ? { a := [1, 3, 3, 4, 5, 6, 7, 8, 10] b := []int{} c := [1, 2, 3] - assert lower_bound(a, 2) ? == 3 + assert lower_bound(a, 2)? == 3 assert (lower_bound(b, 4) or { -1 }) == -1 - assert lower_bound(c, 3) ? == 3 + assert lower_bound(c, 3)? == 3 } fn test_upper_bound() ? { a := [1, 3, 3, 4, 5, 6, 7, 8, 10] b := []int{} c := [1, 2, 3] - assert upper_bound(a, 9) ? == 8 + assert upper_bound(a, 9)? == 8 assert (upper_bound(b, 4) or { -1 }) == -1 - assert upper_bound(c, 2) ? == 2 + assert upper_bound(c, 2)? == 2 } fn test_rotate_right() { diff --git a/vlib/builtin/int.v b/vlib/builtin/int.v index 8a27c1e091..005edf6855 100644 --- a/vlib/builtin/int.v +++ b/vlib/builtin/int.v @@ -556,7 +556,7 @@ pub fn (b []u8) bytestr() string { // it will produce an error if there are more than // four bytes in the array. pub fn (b []u8) byterune() ?rune { - r := b.utf8_to_utf32() ? + r := b.utf8_to_utf32()? return rune(r) } diff --git a/vlib/builtin/js/jsfns_browser.js.v b/vlib/builtin/js/jsfns_browser.js.v index 35f64aa935..715d195c36 100644 --- a/vlib/builtin/js/jsfns_browser.js.v +++ b/vlib/builtin/js/jsfns_browser.js.v @@ -40,7 +40,7 @@ fn JS.moveBy(int, int) fn JS.moveTo(int, int) fn JS.msWriteProfilerMark(string) -// fn JS.open(string, string, string, bool) ?Window +// fn JS.open(string, string, string, bool)?Window // fn JS.postMessage(any, string, []Transferable) fn JS.print() fn JS.prompt(string, string) ?string diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index c22c7fb66b..1ae0d289f6 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -145,15 +145,15 @@ fn test_ranges() { } fn ranges_propagate_first(s string) ?string { - return s[10..] ? + return s[10..]? } fn ranges_propagate_last(s string) ?string { - return s[..20] ? + return s[..20]? } fn ranges_propagate_both(s string) ?string { - return s[1..20] ? + return s[1..20]? } fn test_split_nth() { diff --git a/vlib/cli/command_test.v b/vlib/cli/command_test.v index e3c69b1cdb..f04677b1df 100644 --- a/vlib/cli/command_test.v +++ b/vlib/cli/command_test.v @@ -52,7 +52,7 @@ fn test_if_command_has_default_version_subcommand_if_version_is_set() { } fn flag_should_be_set(cmd cli.Command) ? { - flag := cmd.flags.get_string('flag') ? + flag := cmd.flags.get_string('flag')? assert flag == 'value' } @@ -96,9 +96,9 @@ fn test_if_flag_gets_set_with_long_arg() { } fn flag_should_have_value_of_42(cmd cli.Command) ? { - flag := cmd.flags.get_string('flag') ? + flag := cmd.flags.get_string('flag')? assert flag == 'value' - value := cmd.flags.get_int('value') ? + value := cmd.flags.get_int('value')? assert value == 42 } diff --git a/vlib/cli/flag.v b/vlib/cli/flag.v index fb8fa09d93..3f228ea18d 100644 --- a/vlib/cli/flag.v +++ b/vlib/cli/flag.v @@ -55,7 +55,7 @@ pub fn (flag Flag) get_bool() ?bool { // get_bool returns `true` if the flag specified in `name` is set. // get_bool returns an error if the `FlagType` is not boolean. pub fn (flags []Flag) get_bool(name string) ?bool { - flag := flags.get(name) ? + flag := flags.get(name)? return flag.get_bool() } @@ -100,14 +100,14 @@ pub fn (flag Flag) get_ints() ?[]int { // get_int returns the `int` value argument of the flag specified in `name`. // get_int returns an error if the `FlagType` is not integer. pub fn (flags []Flag) get_int(name string) ?int { - flag := flags.get(name) ? + flag := flags.get(name)? return flag.get_int() } // get_ints returns the array of `int` value argument of the flag specified in `name`. // get_ints returns an error if the `FlagType` is not integer. pub fn (flags []Flag) get_ints(name string) ?[]int { - flag := flags.get(name) ? + flag := flags.get(name)? return flag.get_ints() } @@ -152,14 +152,14 @@ pub fn (flag Flag) get_floats() ?[]f64 { // get_float returns the `f64` value argument of the flag specified in `name`. // get_float returns an error if the `FlagType` is not floating point. pub fn (flags []Flag) get_float(name string) ?f64 { - flag := flags.get(name) ? + flag := flags.get(name)? return flag.get_float() } // get_floats returns the array of `f64` value argument of the flag specified in `name`. // get_floats returns an error if the `FlagType` is not floating point. pub fn (flags []Flag) get_floats(name string) ?[]f64 { - flag := flags.get(name) ? + flag := flags.get(name)? return flag.get_floats() } @@ -198,14 +198,14 @@ pub fn (flag Flag) get_strings() ?[]string { // get_string returns the `string` value argument of the flag specified in `name`. // get_string returns an error if the `FlagType` is not string. pub fn (flags []Flag) get_string(name string) ?string { - flag := flags.get(name) ? + flag := flags.get(name)? return flag.get_string() } // get_strings returns the `string` value argument of the flag specified in `name`. // get_strings returns an error if the `FlagType` is not string. pub fn (flags []Flag) get_strings(name string) ?[]string { - flag := flags.get(name) ? + flag := flags.get(name)? return flag.get_strings() } @@ -214,7 +214,7 @@ pub fn (flags []Flag) get_strings(name string) ?[]string { fn (mut flag Flag) parse(args []string, posix_mode bool) ?[]string { if flag.matches(args, posix_mode) { if flag.flag == .bool { - new_args := flag.parse_bool(args) ? + new_args := flag.parse_bool(args)? return new_args } else { if flag.value.len > 0 && flag.flag != .int_array && flag.flag != .float_array @@ -222,7 +222,7 @@ fn (mut flag Flag) parse(args []string, posix_mode bool) ?[]string { return error('The argument `$flag.name` accept only one value!') } - new_args := flag.parse_raw(args) ? + new_args := flag.parse_raw(args)? return new_args } } else { diff --git a/vlib/compress/zlib/README.md b/vlib/compress/zlib/README.md index 44b667764a..ec6f940007 100644 --- a/vlib/compress/zlib/README.md +++ b/vlib/compress/zlib/README.md @@ -10,8 +10,8 @@ import compress.zlib fn main() { uncompressed := 'Hello world!' - compressed := zlib.compress(uncompressed.bytes()) ? - decompressed := zlib.decompress(compressed) ? + compressed := zlib.compress(uncompressed.bytes())? + decompressed := zlib.decompress(compressed)? assert decompressed == uncompressed.bytes() } ``` diff --git a/vlib/compress/zlib/zlib.v b/vlib/compress/zlib/zlib.v index 36b4722eee..d72800e613 100644 --- a/vlib/compress/zlib/zlib.v +++ b/vlib/compress/zlib/zlib.v @@ -9,7 +9,7 @@ fn C.tdefl_compress_mem_to_heap(source_buf voidptr, source_buf_len usize, out_le fn C.tinfl_decompress_mem_to_heap(source_buf voidptr, source_buf_len usize, out_len &usize, flags int) voidptr // compresses an array of bytes using zlib and returns the compressed bytes in a new array -// Example: compressed := zlib.compress(b) ? +// Example: compressed := zlib.compress(b)? [manualfree] pub fn compress(data []u8) ?[]u8 { if u64(data.len) > zlib.max_size { @@ -36,7 +36,7 @@ pub fn compress(data []u8) ?[]u8 { } // decompresses an array of bytes using zlib and returns the decompressed bytes in a new array -// Example: decompressed := zlib.decompress(b) ? +// Example: decompressed := zlib.decompress(b)? [manualfree] pub fn decompress(data []u8) ?[]u8 { mut out_len := usize(0) diff --git a/vlib/compress/zlib/zlib_test.v b/vlib/compress/zlib/zlib_test.v index fdbe2e53d5..e15743497e 100644 --- a/vlib/compress/zlib/zlib_test.v +++ b/vlib/compress/zlib/zlib_test.v @@ -2,7 +2,7 @@ module zlib fn test_zlib() ? { uncompressed := 'Hello world!' - compressed := compress(uncompressed.bytes()) ? - decompressed := decompress(compressed) ? + compressed := compress(uncompressed.bytes())? + decompressed := decompress(compressed)? assert decompressed == uncompressed.bytes() } diff --git a/vlib/context/cancel.v b/vlib/context/cancel.v index 86fd9379c0..9f1d7b4b50 100644 --- a/vlib/context/cancel.v +++ b/vlib/context/cancel.v @@ -171,7 +171,7 @@ fn parent_cancel_context(mut parent Context) ?&CancelContext { if done.closed { return none } - mut p := parent.value(cancel_context_key) ? + mut p := parent.value(cancel_context_key)? match mut p { CancelContext { pdone := p.done() diff --git a/vlib/crypto/README.md b/vlib/crypto/README.md index c2e161f3bf..76ed2961ab 100644 --- a/vlib/crypto/README.md +++ b/vlib/crypto/README.md @@ -21,7 +21,7 @@ import crypto.rand fn main() { // remember to save this key somewhere if you ever want to decrypt your data - key := rand.bytes(32) ? + key := rand.bytes(32)? println('KEY: $key') // this data is one block (16 bytes) big diff --git a/vlib/crypto/ed25519/ed25519.v b/vlib/crypto/ed25519/ed25519.v index c4aafb39d9..e57162c4a3 100644 --- a/vlib/crypto/ed25519/ed25519.v +++ b/vlib/crypto/ed25519/ed25519.v @@ -62,7 +62,7 @@ pub fn (priv PrivateKey) sign(message []u8) ?[]u8 { // sign`signs the message with privatekey and returns a signature pub fn sign(privatekey PrivateKey, message []u8) ?[]u8 { mut signature := []u8{len: ed25519.signature_size} - sign_generic(mut signature, privatekey, message) ? + sign_generic(mut signature, privatekey, message)? return signature } @@ -74,31 +74,31 @@ fn sign_generic(mut signature []u8, privatekey []u8, message []u8) ? { mut h := sha512.sum512(seed) mut s := edwards25519.new_scalar() - s.set_bytes_with_clamping(h[..32]) ? + s.set_bytes_with_clamping(h[..32])? mut prefix := h[32..] mut mh := sha512.new() - mh.write(prefix) ? - mh.write(message) ? + mh.write(prefix)? + mh.write(message)? mut msg_digest := []u8{cap: sha512.size} msg_digest = mh.sum(msg_digest) mut r := edwards25519.new_scalar() - r.set_uniform_bytes(msg_digest) ? + r.set_uniform_bytes(msg_digest)? mut rr := edwards25519.Point{} rr.scalar_base_mult(mut r) mut kh := sha512.new() - kh.write(rr.bytes()) ? - kh.write(publickey) ? - kh.write(message) ? + kh.write(rr.bytes())? + kh.write(publickey)? + kh.write(message)? mut hram_digest := []u8{cap: sha512.size} hram_digest = kh.sum(hram_digest) mut k := edwards25519.new_scalar() - k.set_uniform_bytes(hram_digest) ? + k.set_uniform_bytes(hram_digest)? mut ss := edwards25519.new_scalar() ss.multiply_add(k, s, r) @@ -118,21 +118,21 @@ pub fn verify(publickey PublicKey, message []u8, sig []u8) ?bool { } mut aa := edwards25519.Point{} - aa.set_bytes(publickey) ? + aa.set_bytes(publickey)? mut kh := sha512.new() - kh.write(sig[..32]) ? - kh.write(publickey) ? - kh.write(message) ? + kh.write(sig[..32])? + kh.write(publickey)? + kh.write(message)? mut hram_digest := []u8{cap: sha512.size} hram_digest = kh.sum(hram_digest) mut k := edwards25519.new_scalar() - k.set_uniform_bytes(hram_digest) ? + k.set_uniform_bytes(hram_digest)? mut ss := edwards25519.new_scalar() - ss.set_canonical_bytes(sig[32..]) ? + ss.set_canonical_bytes(sig[32..])? // [S]B = R + [k]A --> [k](-A) + [S]B = R mut minus_a := edwards25519.Point{} @@ -145,7 +145,7 @@ pub fn verify(publickey PublicKey, message []u8, sig []u8) ?bool { // generate_key generates a public/private key pair entropy using `crypto.rand`. pub fn generate_key() ?(PublicKey, PrivateKey) { - mut seed := rand.bytes(ed25519.seed_size) ? + mut seed := rand.bytes(ed25519.seed_size)? privatekey := new_key_from_seed(seed) mut publickey := []u8{len: ed25519.public_key_size} diff --git a/vlib/crypto/ed25519/examples/example.v b/vlib/crypto/ed25519/examples/example.v index 02919accaf..dd0e21df37 100644 --- a/vlib/crypto/ed25519/examples/example.v +++ b/vlib/crypto/ed25519/examples/example.v @@ -8,11 +8,11 @@ import crypto.ed25519 fn main() { msg := 'Hello Girl' - publ, priv := ed25519.generate_key() ? + publ, priv := ed25519.generate_key()? m := msg.bytes() - sig := ed25519.sign(priv, m) ? + sig := ed25519.sign(priv, m)? println('=== Message ===') println('Msg: $msg \nHash: $m') @@ -31,7 +31,7 @@ fn main() { println('signature: R=${sig[0..32].hex()} s=${sig[32..64].hex()}') println(' signature (Base64)=${base64.encode(sig)}') - rtn := ed25519.verify(publ, m, sig) ? + rtn := ed25519.verify(publ, m, sig)? if rtn { println('Signature verified :$rtn') diff --git a/vlib/crypto/ed25519/internal/ed25519_test.v b/vlib/crypto/ed25519/internal/ed25519_test.v index b55d077c70..adb2f088ab 100644 --- a/vlib/crypto/ed25519/internal/ed25519_test.v +++ b/vlib/crypto/ed25519/internal/ed25519_test.v @@ -29,20 +29,20 @@ fn (z ZeroReader) read(mut buf []u8) ?int { fn test_sign_verify() ? { // mut zero := ZeroReader{} - public, private := ed25519.generate_key() ? + public, private := ed25519.generate_key()? message := 'test message'.bytes() - sig := ed25519.sign(private, message) ? + sig := ed25519.sign(private, message)? res := ed25519.verify(public, message, sig) or { false } assert res == true wrongmessage := 'wrong message'.bytes() - res2 := ed25519.verify(public, wrongmessage, sig) ? + res2 := ed25519.verify(public, wrongmessage, sig)? assert res2 == false } fn test_equal() ? { - public, private := ed25519.generate_key() ? + public, private := ed25519.generate_key()? assert public.equal(public) == true @@ -53,7 +53,7 @@ fn test_equal() ? { }*/ assert private.equal(private) == true - otherpub, otherpriv := ed25519.generate_key() ? + otherpub, otherpriv := ed25519.generate_key()? assert public.equal(otherpub) == false assert private.equal(otherpriv) == false @@ -174,10 +174,10 @@ fn test_input_from_djb_ed25519_crypto_sign_input_without_syncpool() ? { lg.fatal('not contains len 5') }*/ assert parts.len == 5 - privbytes := hex.decode(parts[0]) ? - pubkey := hex.decode(parts[1]) ? - msg := hex.decode(parts[2]) ? - mut sig := hex.decode(parts[3]) ? + privbytes := hex.decode(parts[0])? + pubkey := hex.decode(parts[1])? + msg := hex.decode(parts[2])? + mut sig := hex.decode(parts[3])? assert pubkey.len == public_key_size sig = sig[..signature_size] @@ -185,10 +185,10 @@ fn test_input_from_djb_ed25519_crypto_sign_input_without_syncpool() ? { copy(mut priv[..], privbytes) copy(mut priv[32..], pubkey) - sig2 := ed25519.sign(priv[..], msg) ? + sig2 := ed25519.sign(priv[..], msg)? assert sig == sig2[..] - res := ed25519.verify(pubkey, msg, sig2) ? + res := ed25519.verify(pubkey, msg, sig2)? assert res == true priv2 := new_key_from_seed(priv[..32]) diff --git a/vlib/crypto/ed25519/internal/edwards25519/element_test.v b/vlib/crypto/ed25519/internal/edwards25519/element_test.v index 8625ff3bb4..233aa0d70b 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/element_test.v +++ b/vlib/crypto/ed25519/internal/edwards25519/element_test.v @@ -188,9 +188,9 @@ fn test_sqrt_ratio() ? { mut elw := Element{} mut elg := Element{} - u := elu.set_bytes(hex.decode(tt.u) ?) ? - v := elv.set_bytes(hex.decode(tt.v) ?) ? - want := elw.set_bytes(hex.decode(tt.r) ?) ? + u := elu.set_bytes(hex.decode(tt.u)?)? + v := elv.set_bytes(hex.decode(tt.v)?)? + want := elw.set_bytes(hex.decode(tt.r)?)? mut got, was_square := elg.sqrt_ratio(u, v) assert got.equal(want) != 0 @@ -204,9 +204,9 @@ fn test_sqrt_ratio() ? { fn test_set_bytes_normal() ? { for i in 0 .. 15 { mut el := Element{} - mut random_inp := rand.bytes(32) ? + mut random_inp := rand.bytes(32)? - el = el.set_bytes(random_inp.clone()) ? + el = el.set_bytes(random_inp.clone())? random_inp[random_inp.len - 1] &= (1 << 7) - 1 // assert f1(random_inp, el) == true @@ -249,7 +249,7 @@ fn test_set_bytes_from_dalek_test_vectors() ? { for _, mut tt in tests { b := tt.fe.bytes() mut el := Element{} - mut fe := el.set_bytes(tt.b) ? + mut fe := el.set_bytes(tt.b)? assert b == tt.b assert fe.equal(tt.fe) == 1 @@ -280,7 +280,7 @@ fn test_invert() ? { assert one == r bytes := rand.bytes(32) or { return err } - x.set_bytes(bytes) ? + x.set_bytes(bytes)? xinv.invert(x) r.multiply(x, xinv) @@ -369,20 +369,20 @@ fn (mut v Element) from_big_integer(n big.Integer) ?Element { } mut bytes, _ := n.bytes() swap_endianness(mut bytes) // SHOULD I SWAP IT? - v.set_bytes(bytes) ? + v.set_bytes(bytes)? return v } fn (mut v Element) from_decimal_string(s string) ?Element { - num := big.integer_from_string(s) ? + num := big.integer_from_string(s)? - v = v.from_big_integer(num) ? + v = v.from_big_integer(num)? return v } fn test_bytes_big_equivalence() ? { - mut inp := rand.bytes(32) ? + mut inp := rand.bytes(32)? el := Element{} mut fe := el.generate_element() mut fe1 := el.generate_element() @@ -407,12 +407,12 @@ fn test_bytes_big_equivalence() ? { fn test_decimal_constants() ? { sqrtm1string := '19681161376707505956807079304988542015446066515923890162744021073123829784752' mut el := Element{} - mut exp := el.from_decimal_string(sqrtm1string) ? + mut exp := el.from_decimal_string(sqrtm1string)? assert sqrt_m1.equal(exp) == 1 dstring := '37095705934669439343138083508754565189542113879843219016388785533085940283555' - exp = el.from_decimal_string(dstring) ? + exp = el.from_decimal_string(dstring)? mut d := d_const assert d.equal(exp) == 1 diff --git a/vlib/crypto/ed25519/internal/edwards25519/extra_test.v b/vlib/crypto/ed25519/internal/edwards25519/extra_test.v index af492a9e40..779ffe500f 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/extra_test.v +++ b/vlib/crypto/ed25519/internal/edwards25519/extra_test.v @@ -49,7 +49,7 @@ fn test_bytes_montgomery_sodium() ? { // crypto_sign_keypair().pubkey pubkey := '3bf918ffc2c955dc895bf145f566fb96623c1cadbe040091175764b5fde322c0' mut p := Point{} - p.set_bytes(hex.decode(pubkey) ?) ? + p.set_bytes(hex.decode(pubkey)?)? // crypto_sign_ed25519_pk_to_curve25519(pubkey) want := 'efc6c9d0738e9ea18d738ad4a2653631558931b0f1fde4dd58c436d19686dc28' @@ -115,7 +115,7 @@ fn fn_cofactor(mut data []u8) bool { fn test_mult_by_cofactor() ? { mut loworder := Point{} - mut data := rand.bytes(64) ? + mut data := rand.bytes(64)? assert fn_cofactor(mut data) == true } diff --git a/vlib/crypto/ed25519/internal/edwards25519/point.v b/vlib/crypto/ed25519/internal/edwards25519/point.v index 1604dd54ac..e2ca0ecd68 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/point.v +++ b/vlib/crypto/ed25519/internal/edwards25519/point.v @@ -20,7 +20,7 @@ const ( fn d_const_generate() ?Element { mut v := Element{} - v.set_bytes(edwards25519.d_bytes) ? + v.set_bytes(edwards25519.d_bytes)? return v } @@ -33,7 +33,7 @@ fn d2_const_generate() ?Element { // id_point_generate is the point at infinity. fn id_point_generate() ?Point { mut p := Point{} - p.set_bytes(edwards25519.id_bytes) ? + p.set_bytes(edwards25519.id_bytes)? return p } @@ -41,7 +41,7 @@ fn id_point_generate() ?Point { // correspondence of this encoding with the values in RFC 8032. fn generator() ?Point { mut p := Point{} - p.set_bytes(edwards25519.gen_bytes) ? + p.set_bytes(edwards25519.gen_bytes)? return p } diff --git a/vlib/crypto/ed25519/internal/edwards25519/point_test.v b/vlib/crypto/ed25519/internal/edwards25519/point_test.v index fabf08dd1f..4da2b5ca82 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/point_test.v +++ b/vlib/crypto/ed25519/internal/edwards25519/point_test.v @@ -96,11 +96,11 @@ fn test_non_canonical_points() ? { // t.Run(tt.name, func(t *testing.T) { // p1, err := new(Point).SetBytes(decodeHex(tt.encoding)) mut p1 := Point{} - p1.set_bytes(hex.decode(tt.encoding) ?) ? + p1.set_bytes(hex.decode(tt.encoding)?)? // p2, err := new(Point).SetBytes(decodeHex(tt.canonical)) mut p2 := Point{} - p2.set_bytes(hex.decode(tt.canonical) ?) ? + p2.set_bytes(hex.decode(tt.canonical)?)? assert p1.equal(p2) == 1 assert p1.bytes() == p2.bytes() diff --git a/vlib/crypto/ed25519/internal/edwards25519/scalar.v b/vlib/crypto/ed25519/internal/edwards25519/scalar.v index 7642e3b14f..07660398d4 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/scalar.v +++ b/vlib/crypto/ed25519/internal/edwards25519/scalar.v @@ -1115,7 +1115,7 @@ fn generate_scalar(size int) ?Scalar { // rand.Read(s.s[:16]) // read random bytes and fill buf // using builtin rand.read([]buf) rand.read(mut s.s[..16]) - // buf := rand.read(s.s[..16].len) ? + // buf := rand.read(s.s[..16].len)? // copy(mut s.s[..16], buf) /* @@ -1132,7 +1132,7 @@ fn generate_scalar(size int) ?Scalar { // Read generates len(p) random bytes and writes them into p // rand.Read(s.s[:16]) rand.read(mut s.s[..16]) - // buf := rand.read(s.s[..16].len) ? + // buf := rand.read(s.s[..16].len)? // copy(mut s.s[..16], buf) /* @@ -1148,7 +1148,7 @@ fn generate_scalar(size int) ?Scalar { // of being out of the latter range). // rand.Read(s.s[:]) rand.read(mut s.s[..]) - // buf := crand.read(s.s.len) ? + // buf := crand.read(s.s.len)? // copy(mut s.s[..], buf) /* @@ -1167,7 +1167,7 @@ type NotZeroScalar = Scalar fn generate_notzero_scalar(size int) ?NotZeroScalar { mut s := Scalar{} for s == edwards25519.sc_zero { - s = generate_scalar(size) ? + s = generate_scalar(size)? } return NotZeroScalar(s) } diff --git a/vlib/crypto/ed25519/internal/edwards25519/scalar_alias_test.v b/vlib/crypto/ed25519/internal/edwards25519/scalar_alias_test.v index ad73c77b2d..0c82aedb66 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/scalar_alias_test.v +++ b/vlib/crypto/ed25519/internal/edwards25519/scalar_alias_test.v @@ -25,8 +25,8 @@ fn negate_aliasing(mut v Scalar, x Scalar) Scalar { } fn test_check_aliasing_oneargs() ? { - x := generate_notzero_scalar(10) ? - mut v := generate_notzero_scalar(10) ? + x := generate_notzero_scalar(10)? + mut v := generate_notzero_scalar(10)? out := check_aliasing_onearg(negate_aliasing, mut v, x) assert out == true } @@ -46,9 +46,9 @@ fn subtract_aliasing(mut v Scalar, x Scalar, y Scalar) Scalar { fn test_check_aliasing_twoargs() ? { fn_with_twoargs := [add_aliasing, multiply_aliasing, subtract_aliasing] for f in fn_with_twoargs { - mut v := generate_notzero_scalar(10) ? - x := generate_notzero_scalar(10) ? - y := generate_notzero_scalar(10) ? + mut v := generate_notzero_scalar(10)? + x := generate_notzero_scalar(10)? + y := generate_notzero_scalar(10)? out := check_aliasing_twoargs(f, mut v, x, y) assert out == true } diff --git a/vlib/crypto/ed25519/internal/edwards25519/scalar_test.v b/vlib/crypto/ed25519/internal/edwards25519/scalar_test.v index 638fe8df03..1f4e4c57ed 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/scalar_test.v +++ b/vlib/crypto/ed25519/internal/edwards25519/scalar_test.v @@ -91,8 +91,8 @@ fn test_scalar_set_canonical_bytes() ? { fn test_scalar_set_canonical_bytes_round_trip() ? { for i in 0 .. 10 { - mut sc1 := generate_scalar(2) ? - mut sc2 := generate_scalar(6) ? + mut sc1 := generate_scalar(2)? + mut sc2 := generate_scalar(6)? sc2.set_canonical_bytes(sc1.bytes()) or { panic(err) } assert sc1 == sc2 @@ -117,14 +117,14 @@ fn test_scalar_set_canonical_bytes_on_noncanonical_value() ? { fn test_scalar_set_uniform_bytes() ? { // mod, _ := new(big.Integer).SetString("27742317777372353535851937790883648493", 10) - mut mod := big.integer_from_string('27742317777372353535851937790883648493') ? + mut mod := big.integer_from_string('27742317777372353535851937790883648493')? // mod.Add(mod, new(big.Integer).Lsh(big.NewInt(1), 252)) mod = mod + big.integer_from_i64(1).lshift(252) - mut sc := generate_scalar(100) ? - inp := rand.bytes(64) ? + mut sc := generate_scalar(100)? + inp := rand.bytes(64)? - sc.set_uniform_bytes(inp[..]) ? + sc.set_uniform_bytes(inp[..])? assert is_reduced(sc) == true scbig := bigint_from_le_bytes(sc.s[..]) @@ -190,9 +190,9 @@ fn test_scalar_set_bytes_with_clamping() { } fn test_scalar_multiply_distributes_over_add() ? { - x := generate_scalar(100) ? - y := generate_scalar(100) ? - z := generate_scalar(100) ? + x := generate_scalar(100)? + y := generate_scalar(100)? + z := generate_scalar(100)? // Compute t1 = (x+y)*z mut t1 := Scalar{} diff --git a/vlib/crypto/ed25519/internal/edwards25519/scalarmult_test.v b/vlib/crypto/ed25519/internal/edwards25519/scalarmult_test.v index f3b270aaf0..c5f0cb96f4 100644 --- a/vlib/crypto/ed25519/internal/edwards25519/scalarmult_test.v +++ b/vlib/crypto/ed25519/internal/edwards25519/scalarmult_test.v @@ -95,7 +95,7 @@ fn test_scalarmult_non_identity_point() ? { // Check whether p.ScalarMult and q.ScalaBaseMult give the same, // when p and q are originally set to the base point. - mut x := generate_scalar(5000) ? + mut x := generate_scalar(5000)? mut p := Point{} mut q := Point{} diff --git a/vlib/crypto/rand/crypto_rand_bytes_test.v b/vlib/crypto/rand/crypto_rand_bytes_test.v index 824923d96c..db2d0a4c00 100644 --- a/vlib/crypto/rand/crypto_rand_bytes_test.v +++ b/vlib/crypto/rand/crypto_rand_bytes_test.v @@ -1,7 +1,7 @@ import crypto.rand fn test_reading() ? { - a := rand.read(32) ? + a := rand.read(32)? // dump(a.hex()) assert a.len == 32 mut histogram := [256]int{} diff --git a/vlib/crypto/rand/utils.v b/vlib/crypto/rand/utils.v index 52ed7b600e..3e0f80261d 100644 --- a/vlib/crypto/rand/utils.v +++ b/vlib/crypto/rand/utils.v @@ -20,7 +20,7 @@ pub fn int_u64(max u64) ?u64 { } mut n := u64(0) for { - mut bytes := read(k) ? + mut bytes := read(k)? bytes[0] &= u8(int(u64(1) << b) - 1) x := bytes_to_u64(bytes) n = x[0] diff --git a/vlib/datatypes/doubly_linked_list_test.v b/vlib/datatypes/doubly_linked_list_test.v index 43193afcdf..3bb7dda5a6 100644 --- a/vlib/datatypes/doubly_linked_list_test.v +++ b/vlib/datatypes/doubly_linked_list_test.v @@ -12,16 +12,16 @@ fn test_len() ? { assert list.len() == 0 list.push_back(1) assert list.len() == 1 - list.pop_back() ? + list.pop_back()? assert list.len() == 0 } fn test_first() ? { mut list := DoublyLinkedList{} list.push_back(1) - assert list.first() ? == 1 + assert list.first()? == 1 list.push_back(2) - assert list.first() ? == 1 + assert list.first()? == 1 list = DoublyLinkedList{} list.first() or { return } assert false @@ -30,9 +30,9 @@ fn test_first() ? { fn test_last() ? { mut list := DoublyLinkedList{} list.push_back(1) - assert list.last() ? == 1 + assert list.last()? == 1 list.push_back(2) - assert list.last() ? == 2 + assert list.last()? == 2 list = DoublyLinkedList{} list.last() or { return } assert false @@ -41,11 +41,11 @@ fn test_last() ? { fn test_push() ? { mut list := DoublyLinkedList{} list.push_back(1) - assert list.last() ? == 1 + assert list.last()? == 1 list.push_back(2) - assert list.last() ? == 2 + assert list.last()? == 2 list.push_back(3) - assert list.last() ? == 3 + assert list.last()? == 3 } fn test_pop() ? { @@ -53,10 +53,10 @@ fn test_pop() ? { list.push_back(1) list.push_back(2) list.push_back(3) - assert list.pop_back() ? == 3 + assert list.pop_back()? == 3 list.push_back(4) - assert list.pop_back() ? == 4 - assert list.pop_back() ? == 2 + assert list.pop_back()? == 4 + assert list.pop_back()? == 2 list = DoublyLinkedList{} list.pop_back() or { return } assert false @@ -67,10 +67,10 @@ fn test_pop_front() ? { list.push_back(1) list.push_back(2) list.push_back(3) - assert list.pop_front() ? == 1 + assert list.pop_front()? == 1 list.push_back(4) - assert list.pop_front() ? == 2 - assert list.pop_front() ? == 3 + assert list.pop_front()? == 2 + assert list.pop_front()? == 3 list = DoublyLinkedList{} list.pop_front() or { return } assert false @@ -82,14 +82,14 @@ fn test_insert() ? { list.push_back(2) list.push_back(3) // [1, 2, 3] - list.insert(1, 111) ? + list.insert(1, 111)? // [1, 111, 2, 3] - list.insert(3, 222) ? + list.insert(3, 222)? // [1, 111, 2, 222, 3] - assert list.pop_back() ? == 3 - assert list.pop_back() ? == 222 - assert list.pop_front() ? == 1 - assert list.pop_front() ? == 111 + assert list.pop_back()? == 3 + assert list.pop_back()? == 222 + assert list.pop_front()? == 1 + assert list.pop_front()? == 111 } fn test_push_front() ? { @@ -98,7 +98,7 @@ fn test_push_front() ? { list.push_back(2) list.push_back(3) list.push_front(111) - assert list.first() ? == 111 + assert list.first()? == 111 } fn test_delete() ? { @@ -107,12 +107,12 @@ fn test_delete() ? { list.push_back(1) list.push_back(2) list.delete(1) - assert list.first() ? == 0 - assert list.last() ? == 2 + assert list.first()? == 0 + assert list.last()? == 2 assert list.len() == 2 list.delete(1) - assert list.first() ? == 0 - assert list.last() ? == 0 + assert list.first()? == 0 + assert list.last()? == 0 assert list.len() == 1 list.delete(0) assert list.len() == 0 @@ -147,7 +147,7 @@ fn test_index() ? { } for i := 0; i < 10; i++ { - assert list.index(i * 10) ? == i + assert list.index(i * 10)? == i } } diff --git a/vlib/datatypes/fsm/fsm_test.v b/vlib/datatypes/fsm/fsm_test.v index ef4136ea36..ad00325fb5 100644 --- a/vlib/datatypes/fsm/fsm_test.v +++ b/vlib/datatypes/fsm/fsm_test.v @@ -17,7 +17,7 @@ fn default_setup() (MyReceiver, fsm.StateMachine) { fn test_statemachine_number_of_callbacks_correct_when_single_transition() ? { mut receiver, mut s := default_setup() - s.run(receiver) ? + s.run(receiver)? assert receiver.data.len == 3 } @@ -25,7 +25,7 @@ fn test_statemachine_number_of_callbacks_correct_when_single_transition() ? { fn test_statemachine_sequence_works_when_typical() ? { mut receiver, mut s := default_setup() - s.run(receiver) ? + s.run(receiver)? assert receiver.data[0] == 'on_state_exit: A -> B' assert receiver.data[1] == 'on_state_entry: A -> B' @@ -36,7 +36,7 @@ fn test_statemachine_works_when_final_state() ? { mut receiver, mut s := default_setup() // current state `A`, with a possible transition to `B`: - s.run(receiver) ? // run should not error here + s.run(receiver)? // run should not error here // Note: run will now return error, because for state `B`, // there are no more transitions: diff --git a/vlib/datatypes/fsm/tools/fsm_graph.v b/vlib/datatypes/fsm/tools/fsm_graph.v index 996ba01c80..63ffc17f1f 100644 --- a/vlib/datatypes/fsm/tools/fsm_graph.v +++ b/vlib/datatypes/fsm/tools/fsm_graph.v @@ -13,7 +13,7 @@ pub fn read_file(file string) ?[]string { pub fn extract_transitions(line string) ?string { mut result := ' ' - first_comma := line.index(',') ? + first_comma := line.index(',')? second_comma := line.index_after(',', first_comma + 1) from := line[..first_comma] @@ -32,11 +32,11 @@ pub fn get_transitions(line string) ?string { pub fn main() { mut fp := flag.new_flag_parser(os.args) file := fp.string('file', `f`, '', 'input V file with transitions to generate graph from.') - lines := read_file(file) ? + lines := read_file(file)? println('digraph fsm {') for line in lines { if line.contains('add_transition') { - println(get_transitions(line) ?) + println(get_transitions(line)?) } } diff --git a/vlib/datatypes/heap_test.v b/vlib/datatypes/heap_test.v index bb3087fb96..e715f2cc6d 100644 --- a/vlib/datatypes/heap_test.v +++ b/vlib/datatypes/heap_test.v @@ -8,11 +8,11 @@ fn test_min_heap() ? { heap.insert(4) heap.insert(1) - assert heap.pop() ? == 0 - assert heap.pop() ? == 1 - assert heap.pop() ? == 2 - assert heap.pop() ? == 4 - assert heap.pop() ? == 8 + assert heap.pop()? == 0 + assert heap.pop()? == 1 + assert heap.pop()? == 2 + assert heap.pop()? == 4 + assert heap.pop()? == 8 if _ := heap.pop() { panic('expected none') } @@ -35,11 +35,11 @@ fn test_min_heap_custom() ? { heap.insert(Item{'foo', 100}) heap.insert(Item{'bar', 80}) - assert heap.pop() ?.data == 'foo' - assert heap.pop() ?.data == 'bar' - assert heap.pop() ?.data == 'baz' - assert heap.pop() ?.data == 'buz' - assert heap.pop() ?.data == 'qux' + assert heap.pop()?.data == 'foo' + assert heap.pop()?.data == 'bar' + assert heap.pop()?.data == 'baz' + assert heap.pop()?.data == 'buz' + assert heap.pop()?.data == 'qux' if _ := heap.pop() { panic('expected none') } @@ -56,12 +56,12 @@ fn test_heap_len() ? { heap.insert(1) assert heap.len() == 5 - heap.pop() ? - heap.pop() ? - heap.pop() ? + heap.pop()? + heap.pop()? + heap.pop()? assert heap.len() == 2 - heap.pop() ? - heap.pop() ? + heap.pop()? + heap.pop()? assert heap.len() == 0 heap.pop() or {} assert heap.len() == 0 diff --git a/vlib/datatypes/linked_list_test.v b/vlib/datatypes/linked_list_test.v index 72469dd503..23be1dc12e 100644 --- a/vlib/datatypes/linked_list_test.v +++ b/vlib/datatypes/linked_list_test.v @@ -12,16 +12,16 @@ fn test_len() ? { assert list.len() == 0 list.push(1) assert list.len() == 1 - list.pop() ? + list.pop()? assert list.len() == 0 } fn test_first() ? { mut list := LinkedList{} list.push(1) - assert list.first() ? == 1 + assert list.first()? == 1 list.push(2) - assert list.first() ? == 1 + assert list.first()? == 1 list = LinkedList{} list.first() or { return } assert false @@ -30,9 +30,9 @@ fn test_first() ? { fn test_last() ? { mut list := LinkedList{} list.push(1) - assert list.last() ? == 1 + assert list.last()? == 1 list.push(2) - assert list.last() ? == 2 + assert list.last()? == 2 list = LinkedList{} list.last() or { return } assert false @@ -41,10 +41,10 @@ fn test_last() ? { fn test_index() ? { mut list := LinkedList{} list.push(1) - assert list.index(0) ? == 1 + assert list.index(0)? == 1 list.push(2) - assert list.index(1) ? == 2 - list.pop() ? + assert list.index(1)? == 2 + list.pop()? list.index(1) or { return } assert false } @@ -52,11 +52,11 @@ fn test_index() ? { fn test_push() ? { mut list := LinkedList{} list.push(1) - assert list.last() ? == 1 + assert list.last()? == 1 list.push(2) - assert list.last() ? == 2 + assert list.last()? == 2 list.push(3) - assert list.last() ? == 3 + assert list.last()? == 3 } fn test_pop() ? { @@ -64,10 +64,10 @@ fn test_pop() ? { list.push(1) list.push(2) list.push(3) - assert list.pop() ? == 3 + assert list.pop()? == 3 list.push(4) - assert list.pop() ? == 4 - assert list.pop() ? == 2 + assert list.pop()? == 4 + assert list.pop()? == 2 list = LinkedList{} list.pop() or { return } assert false @@ -78,10 +78,10 @@ fn test_shift() ? { list.push(1) list.push(2) list.push(3) - assert list.shift() ? == 1 + assert list.shift()? == 1 list.push(4) - assert list.shift() ? == 2 - assert list.shift() ? == 3 + assert list.shift()? == 2 + assert list.shift()? == 3 list = LinkedList{} list.shift() or { return } assert false @@ -102,7 +102,7 @@ fn test_prepend() ? { list.push(2) list.push(3) list.prepend(111) - assert list.first() ? == 111 + assert list.first()? == 111 } fn test_str() ? { diff --git a/vlib/datatypes/queue_test.v b/vlib/datatypes/queue_test.v index 5ffc387f59..fbbd5b56dd 100644 --- a/vlib/datatypes/queue_test.v +++ b/vlib/datatypes/queue_test.v @@ -12,16 +12,16 @@ fn test_len() ? { assert queue.len() == 0 queue.push(1) assert queue.len() == 1 - queue.pop() ? + queue.pop()? assert queue.len() == 0 } fn test_peek() ? { mut queue := Queue{} queue.push(1) - assert queue.peek() ? == 1 + assert queue.peek()? == 1 queue.push(2) - assert queue.peek() ? == 1 + assert queue.peek()? == 1 queue = Queue{} queue.peek() or { return } assert false @@ -30,9 +30,9 @@ fn test_peek() ? { fn test_last() ? { mut queue := Queue{} queue.push(1) - assert queue.last() ? == 1 + assert queue.last()? == 1 queue.push(2) - assert queue.last() ? == 2 + assert queue.last()? == 2 queue = Queue{} queue.last() or { return } assert false @@ -41,10 +41,10 @@ fn test_last() ? { fn test_index() ? { mut queue := Queue{} queue.push(1) - assert queue.index(0) ? == 1 + assert queue.index(0)? == 1 queue.push(2) - assert queue.index(1) ? == 2 - queue.pop() ? + assert queue.index(1)? == 2 + queue.pop()? queue.index(1) or { return } assert false } @@ -53,7 +53,7 @@ fn test_push() ? { mut queue := Queue{} queue.push(1) queue.push(2) - assert queue.peek() ? == 1 + assert queue.peek()? == 1 } fn test_pop() ? { @@ -61,10 +61,10 @@ fn test_pop() ? { queue.push(1) queue.push(2) queue.push(3) - assert queue.pop() ? == 1 + assert queue.pop()? == 1 queue.push(4) - assert queue.pop() ? == 2 - assert queue.pop() ? == 3 + assert queue.pop()? == 2 + assert queue.pop()? == 3 queue = Queue{} queue.pop() or { return } assert false diff --git a/vlib/datatypes/stack_test.v b/vlib/datatypes/stack_test.v index 12a84e14f9..e3687059b7 100644 --- a/vlib/datatypes/stack_test.v +++ b/vlib/datatypes/stack_test.v @@ -12,16 +12,16 @@ fn test_len() ? { assert stack.len() == 0 stack.push(1) assert stack.len() == 1 - stack.pop() ? + stack.pop()? assert stack.len() == 0 } fn test_peek() ? { mut stack := dt.Stack{} stack.push(1) - assert stack.peek() ? == 1 + assert stack.peek()? == 1 stack.push(2) - assert stack.peek() ? == 2 + assert stack.peek()? == 2 stack = dt.Stack{} stack.peek() or { return } assert false @@ -30,11 +30,11 @@ fn test_peek() ? { fn test_push() ? { mut stack := dt.Stack{} stack.push(1) - assert stack.peek() ? == 1 + assert stack.peek()? == 1 stack.push(2) - assert stack.peek() ? == 2 + assert stack.peek()? == 2 stack.push(3) - assert stack.peek() ? == 3 + assert stack.peek()? == 3 } fn test_pop() ? { @@ -42,10 +42,10 @@ fn test_pop() ? { stack.push(1) stack.push(2) stack.push(3) - assert stack.pop() ? == 3 + assert stack.pop()? == 3 stack.push(4) - assert stack.pop() ? == 4 - assert stack.pop() ? == 2 + assert stack.pop()? == 4 + assert stack.pop()? == 2 stack = dt.Stack{} stack.pop() or { return } assert false diff --git a/vlib/encoding/base58/base58_test.v b/vlib/encoding/base58/base58_test.v index 5cbd37b5bd..2b4df94760 100644 --- a/vlib/encoding/base58/base58_test.v +++ b/vlib/encoding/base58/base58_test.v @@ -9,9 +9,9 @@ fn main() { fn test_encode_int() ? { a := 0x24 // should be 'd' in base58 - assert encode_int(a) ? == 'd' + assert encode_int(a)? == 'd' - test_encode_int_walpha() ? + test_encode_int_walpha()? } fn test_encode_int_walpha() ? { @@ -20,14 +20,14 @@ fn test_encode_int_walpha() ? { panic(@MOD + '.' + @FN + ': this should never happen') } a := 0x24 // should be '_' in base58 with our custom alphabet - assert encode_int_walpha(a, abc) ? == '_' + assert encode_int_walpha(a, abc)? == '_' } fn test_decode_int() ? { a := 'd' - assert decode_int(a) ? == 0x24 + assert decode_int(a)? == 0x24 - test_decode_int_walpha() ? + test_decode_int_walpha()? } fn test_decode_int_walpha() ? { @@ -35,7 +35,7 @@ fn test_decode_int_walpha() ? { panic(@MOD + '.' + @FN + ': this should never happen') } a := '_' - assert decode_int_walpha(a, abc) ? == 0x24 + assert decode_int_walpha(a, abc)? == 0x24 } fn test_encode_string() { @@ -51,13 +51,13 @@ fn test_encode_string() { fn test_decode_string() ? { a := 'TtaR6twpTGu8VpY' - assert decode(a) ? == 'lorem ipsum' + assert decode(a)? == 'lorem ipsum' abc := new_alphabet('abcdefghij\$lmnopqrstuvwxyz0123456789_ABCDEFGHIJLMNOPQRSTUV') or { panic(@MOD + '.' + @FN + ': this should never happen') } b := '0P7yfPSL0pQh2L5' - assert decode_walpha(b, abc) ? == 'lorem ipsum' + assert decode_walpha(b, abc)? == 'lorem ipsum' } fn test_fails() ? { diff --git a/vlib/encoding/csv/reader.v b/vlib/encoding/csv/reader.v index b3901b74ea..c87e84dc8d 100644 --- a/vlib/encoding/csv/reader.v +++ b/vlib/encoding/csv/reader.v @@ -69,7 +69,7 @@ pub fn new_reader(data string, config ReaderConfig) &Reader { // read reads a row from the CSV data. // If successful, the result holds an array of each column's data. pub fn (mut r Reader) read() ?[]string { - l := r.read_record() ? + l := r.read_record()? return l } @@ -133,7 +133,7 @@ fn (mut r Reader) read_record() ?[]string { mut i := -1 for { if need_read { - l := r.read_line() ? + l := r.read_line()? if l.len <= 0 { if keep_raw { line += '\n' diff --git a/vlib/encoding/hex/hex.v b/vlib/encoding/hex/hex.v index d847d5d3dc..13d36f8410 100644 --- a/vlib/encoding/hex/hex.v +++ b/vlib/encoding/hex/hex.v @@ -15,24 +15,24 @@ pub fn decode(s string) ?[]u8 { if hex_str.len == 0 { return []u8{} } else if hex_str.len == 1 { - return [char2nibble(hex_str[0]) ?] + return [char2nibble(hex_str[0])?] } else if hex_str.len == 2 { - n1 := char2nibble(hex_str[0]) ? - n0 := char2nibble(hex_str[1]) ? + n1 := char2nibble(hex_str[0])? + n0 := char2nibble(hex_str[1])? return [(n1 << 4) | n0] } // calculate the first byte depending on if hex_str.len is odd - mut val := char2nibble(hex_str[0]) ? + mut val := char2nibble(hex_str[0])? if hex_str.len & 1 == 0 { - val = (val << 4) | char2nibble(hex_str[1]) ? + val = (val << 4) | char2nibble(hex_str[1])? } // set cap to hex_str.len/2 rounded up mut bytes := []u8{len: 1, cap: (hex_str.len + 1) >> 1, init: val} // iterate over every 2 bytes // the start index depends on if hex_str.len is odd for i := 2 - (hex_str.len & 1); i < hex_str.len; i += 2 { - n1 := char2nibble(hex_str[i]) ? - n0 := char2nibble(hex_str[i + 1]) ? + n1 := char2nibble(hex_str[i])? + n0 := char2nibble(hex_str[i + 1])? bytes << (n1 << 4) | n0 } return bytes diff --git a/vlib/encoding/hex/hex_test.v b/vlib/encoding/hex/hex_test.v index 81ffb045a7..e3d2748c22 100644 --- a/vlib/encoding/hex/hex_test.v +++ b/vlib/encoding/hex/hex_test.v @@ -1,16 +1,16 @@ module hex fn test_decode() ? { - assert decode('') ? == [] - assert decode('0') ? == [u8(0x0)] - assert decode('f') ? == [u8(0xf)] - assert decode('0f') ? == [u8(0x0f)] - assert decode('ff') ? == [u8(0xff)] - assert decode('123') ? == [u8(0x1), 0x23] - assert decode('1234') ? == [u8(0x12), 0x34] - assert decode('12345') ? == [u8(0x1), 0x23, 0x45] - assert decode('0123456789abcdef') ? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] - assert decode('123456789ABCDEF') ? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] + assert decode('')? == [] + assert decode('0')? == [u8(0x0)] + assert decode('f')? == [u8(0xf)] + assert decode('0f')? == [u8(0x0f)] + assert decode('ff')? == [u8(0xff)] + assert decode('123')? == [u8(0x1), 0x23] + assert decode('1234')? == [u8(0x12), 0x34] + assert decode('12345')? == [u8(0x1), 0x23, 0x45] + assert decode('0123456789abcdef')? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] + assert decode('123456789ABCDEF')? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] } fn test_decode_fails() ? { @@ -32,23 +32,23 @@ fn test_decode_fails() ? { } fn test_encode() ? { - assert encode(decode('') ?) == '' - assert encode(decode('0') ?) == '00' - assert encode(decode('f') ?) == '0f' - assert encode(decode('0f') ?) == '0f' - assert encode(decode('ff') ?) == 'ff' - assert encode(decode('123') ?) == '0123' - assert encode(decode('1234') ?) == '1234' - assert encode(decode('12345') ?) == '012345' - assert encode(decode('abcdef') ?) == 'abcdef' - assert encode(decode('ABCDEF') ?) == 'abcdef' + assert encode(decode('')?) == '' + assert encode(decode('0')?) == '00' + assert encode(decode('f')?) == '0f' + assert encode(decode('0f')?) == '0f' + assert encode(decode('ff')?) == 'ff' + assert encode(decode('123')?) == '0123' + assert encode(decode('1234')?) == '1234' + assert encode(decode('12345')?) == '012345' + assert encode(decode('abcdef')?) == 'abcdef' + assert encode(decode('ABCDEF')?) == 'abcdef' } fn test_decode_0x() ? { - assert decode('0x') ? == [] - assert decode('0x0') ? == [u8(0x0)] - assert decode('0X1234') ? == [u8(0x12), 0x34] - assert decode('0x12345') ? == [u8(0x1), 0x23, 0x45] - assert decode('0x0123456789abcdef') ? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] - assert decode('0X123456789ABCDEF') ? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] + assert decode('0x')? == [] + assert decode('0x0')? == [u8(0x0)] + assert decode('0X1234')? == [u8(0x12), 0x34] + assert decode('0x12345')? == [u8(0x1), 0x23, 0x45] + assert decode('0x0123456789abcdef')? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] + assert decode('0X123456789ABCDEF')? == [u8(0x01), 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef] } diff --git a/vlib/flag/README.md b/vlib/flag/README.md index b840a9db53..1f221245ec 100644 --- a/vlib/flag/README.md +++ b/vlib/flag/README.md @@ -24,7 +24,7 @@ fn main() { mut fp := flag.new_flag_parser(os.args) fp.application('flag_example_tool') fp.version('v0.0.1') - fp.limit_free_args(0, 0) ? // comment this, if you expect arbitrary texts after the options + fp.limit_free_args(0, 0)? // comment this, if you expect arbitrary texts after the options fp.description('This tool is only designed to show how the flag lib is working') fp.skip_executable() an_int := fp.int('an_int', 0, 0o123, 'some int to define 0o123 is its default value') diff --git a/vlib/flag/flag.v b/vlib/flag/flag.v index 49e8de30b6..e14dd9071b 100644 --- a/vlib/flag/flag.v +++ b/vlib/flag/flag.v @@ -71,7 +71,7 @@ pub fn (af []Flag) str() string { // That structure is created with `mut parser := flag.new_flag_parser(os.args)`, // The returned instance can be further customised by calling various methods, // for specifying the accepted options and their values. The user should finally -// call `rest := parser.finalize() ?` to get the rest of the non optional arguments +// call `rest := parser.finalize()?` to get the rest of the non optional arguments // (if there are any left). pub struct FlagParser { pub: diff --git a/vlib/flag/flag_test.v b/vlib/flag/flag_test.v index 501293aefc..1d6497d645 100644 --- a/vlib/flag/flag_test.v +++ b/vlib/flag/flag_test.v @@ -155,7 +155,7 @@ fn test_finalize_returns_error_for_unknown_flags_short() { fn test_allow_to_build_usage_message() ? { mut fp := flag.new_flag_parser([]) - fp.limit_free_args(1, 4) ? + fp.limit_free_args(1, 4)? fp.application('flag_tool') fp.version('v0.0.0') fp.description('some short information about this tool') @@ -196,7 +196,7 @@ fn test_if_no_options_given_usage_message_does_not_contain_options() { fn test_free_args_could_be_limited() ? { mut fp1 := flag.new_flag_parser(['a', 'b', 'c']) - fp1.limit_free_args(1, 4) ? + fp1.limit_free_args(1, 4)? args := fp1.finalize() or { assert false return @@ -208,7 +208,7 @@ fn test_free_args_could_be_limited() ? { fn test_error_for_to_few_free_args() ? { mut fp1 := flag.new_flag_parser(['a', 'b', 'c']) - fp1.limit_free_args(5, 6) ? + fp1.limit_free_args(5, 6)? args := fp1.finalize() or { assert err.msg().starts_with('Expected at least 5 arguments') return @@ -218,7 +218,7 @@ fn test_error_for_to_few_free_args() ? { fn test_error_for_to_much_free_args() ? { mut fp1 := flag.new_flag_parser(['a', 'b', 'c']) - fp1.limit_free_args(1, 2) ? + fp1.limit_free_args(1, 2)? args := fp1.finalize() or { assert err.msg().starts_with('Expected at most 2 arguments') return @@ -228,7 +228,7 @@ fn test_error_for_to_much_free_args() ? { fn test_could_expect_no_free_args() ? { mut fp1 := flag.new_flag_parser(['a']) - fp1.limit_free_args(0, 0) ? + fp1.limit_free_args(0, 0)? args := fp1.finalize() or { assert err.msg().starts_with('Expected no arguments') return @@ -392,7 +392,7 @@ fn test_dashdash_acts_as_parser_full_stop() ? { assert a == false assert b == 5 assert c == 'default' - args := fp.finalize() ? + args := fp.finalize()? assert args.len > 0 assert args[0] != '--' assert args == ['-d', '-x', '-b', '4', '-a', '-c', 'hello', 'some', 'other', 'parameters'] @@ -402,7 +402,7 @@ fn test_dashdash_acts_as_parser_full_stop_dashdash_at_end() ? { mut fp := flag.new_flag_parser(['-b', '5', '-b', '4', 'other', 'params', '--']) b := fp.int_multi('an-int-flag', `b`, '') assert b == [5, 4] - args := fp.finalize() ? + args := fp.finalize()? assert args.len > 0 } diff --git a/vlib/gg/m4/graphic.v b/vlib/gg/m4/graphic.v index e134e80478..f028319f6c 100644 --- a/vlib/gg/m4/graphic.v +++ b/vlib/gg/m4/graphic.v @@ -40,7 +40,7 @@ pub fn ortho(left f32, right f32, bottom f32, top f32, z_near f32, z_far f32) Ma 0 , 0, 0, 1, ]! } - } + } return Mat4{ e: [ 2 / rml, 0 , 0, -(rpl / rml), 0 , 2 / tmb, 0, -(tpb / tmb), diff --git a/vlib/io/io_cp_test.v b/vlib/io/io_cp_test.v index 0a6863a40a..a53fc91a14 100644 --- a/vlib/io/io_cp_test.v +++ b/vlib/io/io_cp_test.v @@ -8,6 +8,6 @@ fn test_cp() ? { } mut r := io.new_buffered_reader(reader: f) mut stdout := os.stdout() - io.cp(mut r, mut stdout) ? + io.cp(mut r, mut stdout)? assert true } diff --git a/vlib/io/multi_writer.v b/vlib/io/multi_writer.v index 165911131e..4007dae657 100644 --- a/vlib/io/multi_writer.v +++ b/vlib/io/multi_writer.v @@ -24,7 +24,7 @@ pub mut: // is returned immediately and writing to other writers stops. pub fn (mut m MultiWriter) write(buf []u8) ?int { for mut w in m.writers { - n := w.write(buf) ? + n := w.write(buf)? if n != buf.len { return error('io: incomplete write to writer of MultiWriter') } diff --git a/vlib/json/README.md b/vlib/json/README.md index 3a7e468f9c..5d1abfa4b1 100644 --- a/vlib/json/README.md +++ b/vlib/json/README.md @@ -28,7 +28,7 @@ fn main() { println('Employee x: $s') assert s == '{"name":"Peter","age":28,"salary":95000.5,"title":2}' // - y := json.decode(Employee, s) ? + y := json.decode(Employee, s)? // println(y) assert y == x diff --git a/vlib/json/json_decode_test.v b/vlib/json/json_decode_test.v index 7e69ebdb63..45fa20096d 100644 --- a/vlib/json/json_decode_test.v +++ b/vlib/json/json_decode_test.v @@ -40,7 +40,7 @@ struct Mount { fn test_decode_u64() ? { data := '{"size": 10737418240}' - m := json.decode(Mount, data) ? + m := json.decode(Mount, data)? assert m.size == 10737418240 // println(m) } @@ -64,7 +64,7 @@ mut: fn test_skip_fields_should_be_initialised_by_json_decode() ? { data := '{"total_comments": 55, "id": 123}' - mut task := json.decode(Task, data) ? + mut task := json.decode(Task, data)? assert task.id == 123 assert task.total_comments == 55 assert task.comments == [] diff --git a/vlib/json/json_decode_with_encode_arg_test.v b/vlib/json/json_decode_with_encode_arg_test.v index 4224d542f7..2c41999359 100644 --- a/vlib/json/json_decode_with_encode_arg_test.v +++ b/vlib/json/json_decode_with_encode_arg_test.v @@ -6,7 +6,7 @@ struct TodoDto { fn test_decode_with_encode_arg() ? { body := TodoDto{} - ret := json.decode(TodoDto, json.encode(body)) ? + ret := json.decode(TodoDto, json.encode(body))? println(ret) assert ret.foo == 0 } diff --git a/vlib/json/json_decode_with_optional_arg_test.v b/vlib/json/json_decode_with_optional_arg_test.v index 97b4932b8b..32aec2f9be 100644 --- a/vlib/json/json_decode_with_optional_arg_test.v +++ b/vlib/json/json_decode_with_optional_arg_test.v @@ -13,7 +13,7 @@ fn test_json_decode_with_optional_arg() { } fn print_info() ?string { - dbconf := json.decode(DbConfig, os.read_file('dbconf.json') ?) ? + dbconf := json.decode(DbConfig, os.read_file('dbconf.json')?)? println(dbconf) return '$dbconf' } diff --git a/vlib/json/json_decode_with_sumtype_test.v b/vlib/json/json_decode_with_sumtype_test.v index 4bf76bcead..36e9c0bc52 100644 --- a/vlib/json/json_decode_with_sumtype_test.v +++ b/vlib/json/json_decode_with_sumtype_test.v @@ -7,15 +7,15 @@ struct Some { } fn test_json_decode_with_sumtype() ? { - v1 := json.decode(Some, '{"t": ["string", "string2"]}') ? + v1 := json.decode(Some, '{"t": ["string", "string2"]}')? println(v1) assert v1.t == Test(['string', 'string2']) - v2 := json.decode(Some, '{"t": [11, 22]}') ? + v2 := json.decode(Some, '{"t": [11, 22]}')? println(v2) assert v2.t == Test([11, 22]) - v3 := json.decode(Some, '{"t": [true, false]}') ? + v3 := json.decode(Some, '{"t": [true, false]}')? println(v3) assert v3.t == Test([true, false]) } diff --git a/vlib/json/json_test.v b/vlib/json/json_test.v index 37c38c168f..2cb15870b1 100644 --- a/vlib/json/json_test.v +++ b/vlib/json/json_test.v @@ -19,7 +19,7 @@ fn test_simple() ? { s := json.encode(x) eprintln('Employee x: $s') assert s == '{"name":"Peter","age":28,"salary":95000.5,"title":2}' - y := json.decode(Employee, s) ? + y := json.decode(Employee, s)? eprintln('Employee y: $y') assert y.name == 'Peter' assert y.age == 28 @@ -78,7 +78,7 @@ fn test_encode_decode_sumtype() ? { assert enc == '{"title":"Super Mega Game","player":{"name":"Monke","_type":"Human"},"other":[{"tag":"Pen","_type":"Item"},{"tag":"Cookie","_type":"Item"},1,"Stool",{"_type":"Time","value":$t.unix_time()}]}' - dec := json.decode(SomeGame, enc) ? + dec := json.decode(SomeGame, enc)? eprintln('Decoded Game: $dec') assert game.title == dec.title @@ -88,7 +88,7 @@ fn test_encode_decode_sumtype() ? { } fn bar(payload string) ?Bar { // ?T doesn't work currently - result := json.decode(T, payload) ? + result := json.decode(T, payload)? return result } @@ -118,9 +118,9 @@ struct User { fn test_parse_user() ? { s := '{"age": 10, "nums": [1,2,3], "type": 1, "lastName": "Johnson", "IsRegistered": true, "pet_animals": {"name": "Bob", "animal": "Dog"}}' - u2 := json.decode(User2, s) ? + u2 := json.decode(User2, s)? println(u2) - u := json.decode(User, s) ? + u := json.decode(User, s)? println(u) assert u.age == 10 assert u.last_name == 'Johnson' @@ -141,7 +141,7 @@ fn test_encode_decode_time() ? { s := json.encode(user) println(s) assert s.contains('"reg_date":1608621780') - user2 := json.decode(User2, s) ? + user2 := json.decode(User2, s)? assert user2.reg_date.str() == '2020-12-22 07:23:00' println(user2) println(user2.reg_date) @@ -201,7 +201,7 @@ struct Country { } fn test_struct_in_struct() ? { - country := json.decode(Country, '{ "name": "UK", "cities": [{"name":"London"}, {"name":"Manchester"}]}') ? + country := json.decode(Country, '{ "name": "UK", "cities": [{"name":"London"}, {"name":"Manchester"}]}')? assert country.name == 'UK' assert country.cities.len == 2 assert country.cities[0].name == 'London' @@ -229,7 +229,7 @@ fn test_parse_map() ? { 'three': 3 'four': 4 } - out := json.decode(map[string]int, '{"one":1,"two":2,"three":3,"four":4}') ? + out := json.decode(map[string]int, '{"one":1,"two":2,"three":3,"four":4}')? println(out) assert out == expected } @@ -289,7 +289,7 @@ fn test_nested_type() ? { out := json.encode(data) println(out) assert out == data_expected - data2 := json.decode(Data, data_expected) ? + data2 := json.decode(Data, data_expected)? assert data2.countries.len == data.countries.len for i in 0 .. 1 { assert data2.countries[i].name == data.countries[i].name @@ -323,7 +323,7 @@ fn test_generic_struct() ? { foo_int := Foo{'bar', 12} foo_enc := json.encode(foo_int) assert foo_enc == '{"name":"bar","data":12}' - foo_dec := json.decode(Foo, foo_enc) ? + foo_dec := json.decode(Foo, foo_enc)? assert foo_dec.name == 'bar' assert foo_dec.data == 12 } @@ -358,7 +358,7 @@ struct Message { } fn test_decode_alias_struct() ? { - msg := json.decode(Message, '{"id": "118499178790780929"}') ? + msg := json.decode(Message, '{"id": "118499178790780929"}')? // hacky way of comparing aliased strings assert msg.id.str() == '118499178790780929' } @@ -376,19 +376,19 @@ struct List { } fn test_list() ? { - list := json.decode(List, '{"id": 1, "items": ["1", "2"]}') ? + list := json.decode(List, '{"id": 1, "items": ["1", "2"]}')? assert list.id == 1 assert list.items == ['1', '2'] } fn test_list_no_id() ? { - list := json.decode(List, '{"items": ["1", "2"]}') ? + list := json.decode(List, '{"items": ["1", "2"]}')? assert list.id == 0 assert list.items == ['1', '2'] } fn test_list_no_items() ? { - list := json.decode(List, '{"id": 1}') ? + list := json.decode(List, '{"id": 1}')? assert list.id == 1 assert list.items == [] } @@ -400,7 +400,7 @@ struct Info { } fn test_decode_null_object() ? { - info := json.decode(Info, '{"id": 22, "items": null, "maps": null}') ? + info := json.decode(Info, '{"id": 22, "items": null, "maps": null}')? assert info.id == 22 assert '$info.items' == '[]' assert '$info.maps' == '{}' diff --git a/vlib/math/big/integer.v b/vlib/math/big/integer.v index 3602118677..acae9bec1f 100644 --- a/vlib/math/big/integer.v +++ b/vlib/math/big/integer.v @@ -144,7 +144,7 @@ pub fn integer_from_radix(all_characters string, radix u32) ?Integer { return error('Radix must be between 2 and 36 (inclusive)') } characters := all_characters.to_lower() - validate_string(characters, radix) ? + validate_string(characters, radix)? return match radix { 2 { integer_from_special_string(characters, 1) diff --git a/vlib/mssql/README.md b/vlib/mssql/README.md index ff4fefc22b..80f8181766 100644 --- a/vlib/mssql/README.md +++ b/vlib/mssql/README.md @@ -50,7 +50,7 @@ fn test_example() ? { mut conn := mssql.Connection{} - conn.connect(config.get_conn_str()) ? + conn.connect(config.get_conn_str())? defer { conn.close() @@ -58,7 +58,7 @@ fn test_example() ? { // get current db name mut query := 'SELECT DB_NAME()' - mut res := conn.query(query) ? + mut res := conn.query(query)? assert res == mssql.Result{ rows: [mssql.Row{ vals: ['master'] diff --git a/vlib/mssql/mssql.v b/vlib/mssql/mssql.v index a885e4b8da..e31b00d7cd 100644 --- a/vlib/mssql/mssql.v +++ b/vlib/mssql/mssql.v @@ -15,31 +15,31 @@ pub fn (mut conn Connection) connect(conn_str string) ?bool { // Allocate environment handle retcode = C.SQLAllocHandle(C.SQLSMALLINT(C.SQL_HANDLE_ENV), C.SQLHANDLE(C.SQL_NULL_HANDLE), unsafe { &C.SQLHANDLE(&conn.henv) }) - check_error(retcode, 'SQLAllocHandle(SQL_HANDLE_ENV)', C.SQLHANDLE(conn.henv), C.SQLSMALLINT(C.SQL_HANDLE_ENV)) ? + check_error(retcode, 'SQLAllocHandle(SQL_HANDLE_ENV)', C.SQLHANDLE(conn.henv), C.SQLSMALLINT(C.SQL_HANDLE_ENV))? // Set the ODBC version environment attribute retcode = C.SQLSetEnvAttr(conn.henv, C.SQLINTEGER(C.SQL_ATTR_ODBC_VERSION), &C.SQLPOINTER(C.SQL_OV_ODBC3), C.SQLINTEGER(0)) check_error(retcode, 'SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)', C.SQLHANDLE(conn.henv), - C.SQLSMALLINT(C.SQL_HANDLE_ENV)) ? + C.SQLSMALLINT(C.SQL_HANDLE_ENV))? // Allocate connection handle retcode = C.SQLAllocHandle(C.SQLSMALLINT(C.SQL_HANDLE_DBC), C.SQLHANDLE(conn.henv), unsafe { &C.SQLHANDLE(&conn.hdbc) }) - check_error(retcode, 'SQLAllocHandle(SQL_HANDLE_DBC)', C.SQLHANDLE(conn.hdbc), C.SQLSMALLINT(C.SQL_HANDLE_DBC)) ? + check_error(retcode, 'SQLAllocHandle(SQL_HANDLE_DBC)', C.SQLHANDLE(conn.hdbc), C.SQLSMALLINT(C.SQL_HANDLE_DBC))? // Set login timeout to 5 seconds retcode = C.SQLSetConnectAttr(conn.hdbc, C.SQLINTEGER(C.SQL_LOGIN_TIMEOUT), C.SQLPOINTER(5), C.SQLINTEGER(0)) check_error(retcode, 'SQLSetConnectAttr(SQL_LOGIN_TIMEOUT)', C.SQLHANDLE(conn.hdbc), - C.SQLSMALLINT(C.SQL_HANDLE_DBC)) ? + C.SQLSMALLINT(C.SQL_HANDLE_DBC))? // Connect to data source mut outstr := [1024]char{} mut outstrlen := C.SQLSMALLINT(0) retcode = C.SQLDriverConnect(conn.hdbc, C.SQLHWND(0), conn_str_c, C.SQLSMALLINT(C.SQL_NTS), &C.SQLCHAR(&outstr[0]), C.SQLSMALLINT(sizeof(outstr)), &outstrlen, C.SQLUSMALLINT(C.SQL_DRIVER_NOPROMPT)) - check_error(retcode, 'SQLDriverConnect()', C.SQLHANDLE(conn.hdbc), C.SQLSMALLINT(C.SQL_HANDLE_DBC)) ? + check_error(retcode, 'SQLDriverConnect()', C.SQLHANDLE(conn.hdbc), C.SQLSMALLINT(C.SQL_HANDLE_DBC))? conn.conn_str = conn_str return true } @@ -61,17 +61,17 @@ pub fn (mut conn Connection) close() { // query executes a sql query pub fn (mut conn Connection) query(q string) ?Result { - mut hstmt := new_hstmt(conn.hdbc) ? + mut hstmt := new_hstmt(conn.hdbc)? defer { hstmt.close() } - hstmt.exec(q) ? + hstmt.exec(q)? - affected := hstmt.retrieve_affected_rows() ? + affected := hstmt.retrieve_affected_rows()? - hstmt.prepare_read() ? - raw_rows := hstmt.read_rows() ? + hstmt.prepare_read()? + raw_rows := hstmt.read_rows()? mut res := Result{ rows: []Row{} diff --git a/vlib/mssql/stmt_handle.v b/vlib/mssql/stmt_handle.v index 8e0b7923e8..392d983e6c 100644 --- a/vlib/mssql/stmt_handle.v +++ b/vlib/mssql/stmt_handle.v @@ -21,7 +21,7 @@ fn new_hstmt(hdbc C.SQLHDBC) ?HStmt { mut hstmt := C.SQLHSTMT(C.SQL_NULL_HSTMT) // Allocate statement handle retcode = C.SQLAllocHandle(C.SQLSMALLINT(C.SQL_HANDLE_STMT), C.SQLHANDLE(hdbc), unsafe { &C.SQLHANDLE(&hstmt) }) - check_error(retcode, 'SQLAllocHandle(SQL_HANDLE_STMT)', C.SQLHANDLE(hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT)) ? + check_error(retcode, 'SQLAllocHandle(SQL_HANDLE_STMT)', C.SQLHANDLE(hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT))? return HStmt{ hdbc: hdbc @@ -42,14 +42,14 @@ fn (mut h HStmt) close() { // exec executes a Sql statement. Result is stored in odbc driver, and not yet read. fn (h HStmt) exec(sql string) ? { retcode := C.SQLExecDirect(h.hstmt, sql.str, C.SQLINTEGER(C.SQL_NTS)) - check_error(retcode, 'SQLExecDirect()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT)) ? + check_error(retcode, 'SQLExecDirect()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT))? } // retrieve_affected_rows returns number of rows affected/modified by the last operation. -1 if not applicable. fn (h HStmt) retrieve_affected_rows() ?int { count_ret := C.SQLLEN(0) retcode := C.SQLRowCount(h.hstmt, &count_ret) - check_error(retcode, 'SQLRowCount()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT)) ? + check_error(retcode, 'SQLRowCount()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT))? return int(count_ret) } @@ -57,7 +57,7 @@ fn (h HStmt) retrieve_column_count() ?int { mut retcode := C.SQLRETURN(C.SQL_SUCCESS) col_count_buff := C.SQLSMALLINT(0) retcode = C.SQLNumResultCols(h.hstmt, &col_count_buff) - check_error(retcode, 'SQLNumResultCols()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT)) ? + check_error(retcode, 'SQLNumResultCols()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT))? return int(col_count_buff) } @@ -65,7 +65,7 @@ fn (h HStmt) retrieve_column_count() ?int { fn (mut h HStmt) prepare_read() ? { mut retcode := C.SQLRETURN(C.SQL_SUCCESS) - column_count := h.retrieve_column_count() ? + column_count := h.retrieve_column_count()? h.column_count = column_count // remember the count because read will need it h.buffers = [][]char{len: h.column_count, cap: h.column_count} @@ -77,7 +77,7 @@ fn (mut h HStmt) prepare_read() ? { // find out buffer size needed to read data in this column retcode = C.SQLColAttribute(h.hstmt, i_col, C.SQLUSMALLINT(C.SQL_DESC_LENGTH), C.SQLPOINTER(0), C.SQLSMALLINT(0), C.SQLSMALLINT(0), &size_ret) - check_error(retcode, 'SQLColAttribute()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT)) ? + check_error(retcode, 'SQLColAttribute()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT))? // buffer allocation is the size + 1 to include termination char, since SQL_DESC_LENGTH does not include it. allocate_size := size_ret + C.SQLLEN(1) @@ -87,7 +87,7 @@ fn (mut h HStmt) prepare_read() ? { // bind the buffer retcode = C.SQLBindCol(h.hstmt, C.SQLUSMALLINT(i_col), C.SQLSMALLINT(C.SQL_C_CHAR), C.SQLPOINTER(&buff[0]), allocate_size, &h.indicators[i]) - check_error(retcode, 'SQLBindCol()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT)) ? + check_error(retcode, 'SQLBindCol()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT))? // record the buffer in HStmt h.buffers[i] = buff @@ -116,7 +116,7 @@ fn (h HStmt) read_rows() ?[][]string { } } else { if retcode != C.SQLRETURN(C.SQL_NO_DATA) { - check_error(retcode, 'SQLFetch()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT)) ? + check_error(retcode, 'SQLFetch()', C.SQLHANDLE(h.hstmt), C.SQLSMALLINT(C.SQL_HANDLE_STMT))? } else { break } diff --git a/vlib/mysql/README.md b/vlib/mysql/README.md index 3d0ab97531..5ff3d1a3d7 100644 --- a/vlib/mysql/README.md +++ b/vlib/mysql/README.md @@ -13,11 +13,11 @@ mut connection := mysql.Connection{ dbname: 'mysql' } // Connect to server -connection.connect() ? +connection.connect()? // Change the default database -connection.select_db('db_users') ? +connection.select_db('db_users')? // Do a query -get_users_query_result := connection.query('SELECT * FROM users') ? +get_users_query_result := connection.query('SELECT * FROM users')? // Get the result as maps for user in get_users_query_result.maps() { // Access the name of user diff --git a/vlib/mysql/orm.v b/vlib/mysql/orm.v index 498244c84a..35a57f6c90 100644 --- a/vlib/mysql/orm.v +++ b/vlib/mysql/orm.v @@ -11,15 +11,15 @@ pub fn (db Connection) @select(config orm.SelectConfig, data orm.QueryData, wher query := orm.orm_select_gen(config, '`', false, '?', 0, where) mut ret := [][]orm.Primitive{} mut stmt := db.init_stmt(query) - stmt.prepare() ? + stmt.prepare()? - mysql_stmt_binder(mut stmt, where) ? - mysql_stmt_binder(mut stmt, data) ? + mysql_stmt_binder(mut stmt, where)? + mysql_stmt_binder(mut stmt, data)? if data.data.len > 0 || where.data.len > 0 { - stmt.bind_params() ? + stmt.bind_params()? } - mut status := stmt.execute() ? + mut status := stmt.execute()? num_fields := stmt.get_field_count() metadata := stmt.gen_metadata() fields := stmt.fetch_fields(metadata) @@ -66,23 +66,23 @@ pub fn (db Connection) @select(config orm.SelectConfig, data orm.QueryData, wher lens := []u32{len: int(num_fields), init: 0} stmt.bind_res(fields, vptr, lens, num_fields) - stmt.bind_result_buffer() ? - stmt.store_result() ? + stmt.bind_result_buffer()? + stmt.store_result()? mut row := 0 for { - status = stmt.fetch_stmt() ? + status = stmt.fetch_stmt()? if status == 1 || status == 100 { break } row++ - data_list := buffer_to_primitive(vptr, config.types) ? + data_list := buffer_to_primitive(vptr, config.types)? ret << data_list } - stmt.close() ? + stmt.close()? return ret } @@ -91,17 +91,17 @@ pub fn (db Connection) @select(config orm.SelectConfig, data orm.QueryData, wher pub fn (db Connection) insert(table string, data orm.QueryData) ? { query := orm.orm_stmt_gen(table, '`', .insert, false, '?', 1, data, orm.QueryData{}) - mysql_stmt_worker(db, query, data, orm.QueryData{}) ? + mysql_stmt_worker(db, query, data, orm.QueryData{})? } pub fn (db Connection) update(table string, data orm.QueryData, where orm.QueryData) ? { query := orm.orm_stmt_gen(table, '`', .update, false, '?', 1, data, where) - mysql_stmt_worker(db, query, data, where) ? + mysql_stmt_worker(db, query, data, where)? } pub fn (db Connection) delete(table string, where orm.QueryData) ? { query := orm.orm_stmt_gen(table, '`', .delete, false, '?', 1, orm.QueryData{}, where) - mysql_stmt_worker(db, query, orm.QueryData{}, where) ? + mysql_stmt_worker(db, query, orm.QueryData{}, where)? } pub fn (db Connection) last_id() orm.Primitive { @@ -119,24 +119,24 @@ pub fn (db Connection) create(table string, fields []orm.TableField) ? { query := orm.orm_table_gen(table, '`', false, 0, fields, mysql_type_from_v, false) or { return err } - mysql_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{}) ? + mysql_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})? } pub fn (db Connection) drop(table string) ? { query := 'DROP TABLE `$table`;' - mysql_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{}) ? + mysql_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})? } fn mysql_stmt_worker(db Connection, query string, data orm.QueryData, where orm.QueryData) ? { mut stmt := db.init_stmt(query) - stmt.prepare() ? - mysql_stmt_binder(mut stmt, data) ? - mysql_stmt_binder(mut stmt, where) ? + stmt.prepare()? + mysql_stmt_binder(mut stmt, data)? + mysql_stmt_binder(mut stmt, where)? if data.data.len > 0 || where.data.len > 0 { - stmt.bind_params() ? + stmt.bind_params()? } - stmt.execute() ? - stmt.close() ? + stmt.execute()? + stmt.close()? } fn mysql_stmt_binder(mut stmt Stmt, d orm.QueryData) ? { diff --git a/vlib/net/address.v b/vlib/net/address.v index d8ab22fb6a..41467c86be 100644 --- a/vlib/net/address.v +++ b/vlib/net/address.v @@ -49,10 +49,10 @@ fn temp_unix() ?Addr { // close it // remove it // then reuse the filename - mut file, filename := util.temp_file() ? + mut file, filename := util.temp_file()? file.close() - os.rm(filename) ? - addrs := resolve_addrs(filename, .unix, .udp) ? + os.rm(filename)? + addrs := resolve_addrs(filename, .unix, .udp)? return addrs[0] } @@ -161,7 +161,7 @@ pub fn resolve_addrs_fuzzy(addr string, @type SocketType) ?[]Addr { } pub fn resolve_ipaddrs(addr string, family AddrFamily, typ SocketType) ?[]Addr { - address, port := split_address(addr) ? + address, port := split_address(addr)? if addr[0] == `:` { match family { @@ -191,10 +191,10 @@ pub fn resolve_ipaddrs(addr string, family AddrFamily, typ SocketType) ?[]Addr { // This might look silly but is recommended by MSDN $if windows { - socket_error(0 - C.getaddrinfo(&char(address.str), &char(sport.str), &hints, &results)) ? + socket_error(0 - C.getaddrinfo(&char(address.str), &char(sport.str), &hints, &results))? } $else { x := C.getaddrinfo(&char(address.str), &char(sport.str), &hints, &results) - wrap_error(x) ? + wrap_error(x)? } defer { diff --git a/vlib/net/common.v b/vlib/net/common.v index 1b571f8c59..4fae84d7cd 100644 --- a/vlib/net/common.v +++ b/vlib/net/common.v @@ -20,10 +20,10 @@ pub const infinite_timeout = time.infinite fn shutdown(handle int) ? { $if windows { C.shutdown(handle, C.SD_BOTH) - socket_error(C.closesocket(handle)) ? + socket_error(C.closesocket(handle))? } $else { C.shutdown(handle, C.SHUT_RDWR) - socket_error(C.close(handle)) ? + socket_error(C.close(handle))? } } @@ -52,13 +52,13 @@ fn @select(handle int, test Select, timeout time.Duration) ?bool { match test { .read { - socket_error(C.@select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout)) ? + socket_error(C.@select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout))? } .write { - socket_error(C.@select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout)) ? + socket_error(C.@select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout))? } .except { - socket_error(C.@select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout)) ? + socket_error(C.@select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout))? } } @@ -104,7 +104,7 @@ fn wait_for_common(handle int, deadline time.Time, timeout time.Duration, test S time.now().add(timeout) } - ready := select_deadline(handle, test, real_deadline) ? + ready := select_deadline(handle, test, real_deadline)? if ready { return diff --git a/vlib/net/ftp/ftp.v b/vlib/net/ftp/ftp.v index adb8a0daf8..f397da3e08 100644 --- a/vlib/net/ftp/ftp.v +++ b/vlib/net/ftp/ftp.v @@ -82,7 +82,7 @@ fn (mut zftp FTP) write(data string) ?int { } fn (mut zftp FTP) read() ?(int, string) { - mut data := zftp.reader.read_line() ? + mut data := zftp.reader.read_line()? $if debug { println('FTP.v <<< $data') } @@ -92,7 +92,7 @@ fn (mut zftp FTP) read() ?(int, string) { code := data[..3].int() if data[3] == `-` { for { - data = zftp.reader.read_line() ? + data = zftp.reader.read_line()? if data[..3].int() == code && data[3] != `-` { break } @@ -102,9 +102,9 @@ fn (mut zftp FTP) read() ?(int, string) { } pub fn (mut zftp FTP) connect(ip string) ?bool { - zftp.conn = net.dial_tcp('$ip:21') ? + zftp.conn = net.dial_tcp('$ip:21')? zftp.reader = io.new_buffered_reader(reader: zftp.conn) - code, _ := zftp.read() ? + code, _ := zftp.read()? if code == ftp.connected { return true } @@ -118,7 +118,7 @@ pub fn (mut zftp FTP) login(user string, passwd string) ?bool { } return false } - mut code, _ := zftp.read() ? + mut code, _ := zftp.read()? if code == ftp.logged_in { return true } @@ -131,7 +131,7 @@ pub fn (mut zftp FTP) login(user string, passwd string) ?bool { } return false } - code, _ = zftp.read() ? + code, _ = zftp.read()? if code == ftp.logged_in { return true } @@ -139,13 +139,13 @@ pub fn (mut zftp FTP) login(user string, passwd string) ?bool { } pub fn (mut zftp FTP) close() ? { - zftp.write('QUIT') ? - zftp.conn.close() ? + zftp.write('QUIT')? + zftp.conn.close()? } pub fn (mut zftp FTP) pwd() ?string { - zftp.write('PWD') ? - _, data := zftp.read() ? + zftp.write('PWD')? + _, data := zftp.read()? spl := data.split('"') // " if spl.len >= 2 { return spl[1] @@ -155,7 +155,7 @@ pub fn (mut zftp FTP) pwd() ?string { pub fn (mut zftp FTP) cd(dir string) ? { zftp.write('CWD $dir') or { return } - mut code, mut data := zftp.read() ? + mut code, mut data := zftp.read()? match int(code) { ftp.denied { $if debug { @@ -163,7 +163,7 @@ pub fn (mut zftp FTP) cd(dir string) ? { } } ftp.complete { - code, data = zftp.read() ? + code, data = zftp.read()? } else {} } @@ -189,30 +189,30 @@ fn new_dtp(msg string) ?&DTP { } fn (mut zftp FTP) pasv() ?&DTP { - zftp.write('PASV') ? - code, data := zftp.read() ? + zftp.write('PASV')? + code, data := zftp.read()? $if debug { println('pass: $data') } if code != ftp.passive_mode { return error('pasive mode not allowed') } - dtp := new_dtp(data) ? + dtp := new_dtp(data)? return dtp } pub fn (mut zftp FTP) dir() ?[]string { mut dtp := zftp.pasv() or { return error('Cannot establish data connection') } - zftp.write('LIST') ? - code, _ := zftp.read() ? + zftp.write('LIST')? + code, _ := zftp.read()? if code == ftp.denied { return error('`LIST` denied') } if code != ftp.open_data_connection { return error('Data channel empty') } - list_dir := dtp.read() ? - result, _ := zftp.read() ? + list_dir := dtp.read()? + result, _ := zftp.read()? if result != ftp.close_data_connection { println('`LIST` not ok') } @@ -229,15 +229,15 @@ pub fn (mut zftp FTP) dir() ?[]string { pub fn (mut zftp FTP) get(file string) ?[]u8 { mut dtp := zftp.pasv() or { return error('Cannot stablish data connection') } - zftp.write('RETR $file') ? - code, _ := zftp.read() ? + zftp.write('RETR $file')? + code, _ := zftp.read()? if code == ftp.denied { return error('Permission denied') } if code != ftp.open_data_connection { return error('Data connection not ready') } - blob := dtp.read() ? + blob := dtp.read()? dtp.close() return blob } diff --git a/vlib/net/ftp/ftp_test.v b/vlib/net/ftp/ftp_test.v index 1c16a197ae..8e03e0063f 100644 --- a/vlib/net/ftp/ftp_test.v +++ b/vlib/net/ftp/ftp_test.v @@ -17,11 +17,11 @@ fn ftp_client_test_inside() ? { defer { zftp.close() or { panic(err) } } - connect_result := zftp.connect('ftp.redhat.com') ? + connect_result := zftp.connect('ftp.redhat.com')? assert connect_result - login_result := zftp.login('ftp', 'ftp') ? + login_result := zftp.login('ftp', 'ftp')? assert login_result - pwd := zftp.pwd() ? + pwd := zftp.pwd()? assert pwd.len > 0 zftp.cd('/') or { assert false diff --git a/vlib/net/http/backend_nix.c.v b/vlib/net/http/backend_nix.c.v index 4f84b86c64..be8519d00d 100644 --- a/vlib/net/http/backend_nix.c.v +++ b/vlib/net/http/backend_nix.c.v @@ -33,13 +33,13 @@ fn (req &Request) ssl_do(port int, method Method, host_name string, path string) cert = os.temp_dir() + '/v_cert' + now cert_key = os.temp_dir() + '/v_cert_key' + now if req.verify != '' { - os.write_file(verify, req.verify) ? + os.write_file(verify, req.verify)? } if req.cert != '' { - os.write_file(cert, req.cert) ? + os.write_file(cert, req.cert)? } if req.cert_key != '' { - os.write_file(cert_key, req.cert_key) ? + os.write_file(cert_key, req.cert_key)? } } mut res := 0 diff --git a/vlib/net/http/download.v b/vlib/net/http/download.v index 5f704dc6f6..e00137ff05 100644 --- a/vlib/net/http/download.v +++ b/vlib/net/http/download.v @@ -18,7 +18,7 @@ pub fn download_file(url string, out_file_path string) ? { $if debug_http ? { println('http.download_file saving $s.text.len bytes') } - os.write_file(out_file_path, s.text) ? + os.write_file(out_file_path, s.text)? } // TODO: implement download_file_with_progress diff --git a/vlib/net/http/header.v b/vlib/net/http/header.v index 49b987d988..4402065543 100644 --- a/vlib/net/http/header.v +++ b/vlib/net/http/header.v @@ -365,7 +365,7 @@ pub fn new_header_from_map(kvs map[CommonHeader]string) Header { // new_custom_header_from_map creates a Header from string key value pairs pub fn new_custom_header_from_map(kvs map[string]string) ?Header { mut h := new_header() - h.add_custom_map(kvs) ? + h.add_custom_map(kvs)? return h } @@ -379,7 +379,7 @@ pub fn (mut h Header) add(key CommonHeader, value string) { // add_custom appends a value to a custom header key. This function will // return an error if the key contains invalid header characters. pub fn (mut h Header) add_custom(key string, value string) ? { - is_valid(key) ? + is_valid(key)? h.data[key] << value h.add_key(key) } @@ -394,7 +394,7 @@ pub fn (mut h Header) add_map(kvs map[CommonHeader]string) { // add_custom_map appends the value for each custom header key. pub fn (mut h Header) add_custom_map(kvs map[string]string) ? { for k, v in kvs { - h.add_custom(k, v) ? + h.add_custom(k, v)? } } @@ -411,7 +411,7 @@ pub fn (mut h Header) set(key CommonHeader, value string) { // function will return an error if the key contains invalid header // characters. pub fn (mut h Header) set_custom(key string, value string) ? { - is_valid(key) ? + is_valid(key)? h.data[key] = [value] h.add_key(key) } @@ -689,11 +689,11 @@ fn parse_headers(s string) ?Header { last_value += ' ${line.trim(' \t')}' continue } else if last_key != '' { - h.add_custom(last_key, last_value) ? + h.add_custom(last_key, last_value)? } - last_key, last_value = parse_header(line) ? + last_key, last_value = parse_header(line)? } - h.add_custom(last_key, last_value) ? + h.add_custom(last_key, last_value)? return h } diff --git a/vlib/net/http/header_test.v b/vlib/net/http/header_test.v index 4f5f2cef64..dbbc16df04 100644 --- a/vlib/net/http/header_test.v +++ b/vlib/net/http/header_test.v @@ -29,7 +29,7 @@ fn test_header_adds_multiple() { fn test_header_get() ? { mut h := new_header(key: .dnt, value: 'one') - h.add_custom('dnt', 'two') ? + h.add_custom('dnt', 'two')? dnt := h.get_custom('dnt') or { '' } exact := h.get_custom('dnt', exact: true) or { '' } assert dnt == 'one' @@ -42,7 +42,7 @@ fn test_header_set() ? { value: 'two' ) assert h.values(.dnt) == ['one', 'two'] - h.set_custom('DNT', 'three') ? + h.set_custom('DNT', 'three')? assert h.values(.dnt) == ['three'] } @@ -67,8 +67,8 @@ fn test_header_delete_not_existing() { fn test_custom_header() ? { mut h := new_header() - h.add_custom('AbC', 'dEf') ? - h.add_custom('aBc', 'GhI') ? + h.add_custom('AbC', 'dEf')? + h.add_custom('aBc', 'GhI')? assert h.custom_values('AbC', exact: true) == ['dEf'] assert h.custom_values('aBc', exact: true) == ['GhI'] assert h.custom_values('ABC') == ['dEf', 'GhI'] @@ -77,13 +77,13 @@ fn test_custom_header() ? { h.delete_custom('AbC') h.delete_custom('aBc') - h.add_custom('abc', 'def') ? + h.add_custom('abc', 'def')? assert h.custom_values('abc') == ['def'] assert h.custom_values('ABC') == ['def'] assert h.keys() == ['abc'] h.delete_custom('abc') - h.add_custom('accEPT', '*/*') ? + h.add_custom('accEPT', '*/*')? assert h.custom_values('ACCept') == ['*/*'] assert h.values(.accept) == ['*/*'] assert h.keys() == ['accEPT'] @@ -91,7 +91,7 @@ fn test_custom_header() ? { fn test_contains_custom() ? { mut h := new_header() - h.add_custom('Hello', 'world') ? + h.add_custom('Hello', 'world')? assert h.contains_custom('hello') assert h.contains_custom('HELLO') assert h.contains_custom('Hello', exact: true) @@ -101,10 +101,10 @@ fn test_contains_custom() ? { fn test_get_custom() ? { mut h := new_header() - h.add_custom('Hello', 'world') ? - assert h.get_custom('hello') ? == 'world' - assert h.get_custom('HELLO') ? == 'world' - assert h.get_custom('Hello', exact: true) ? == 'world' + h.add_custom('Hello', 'world')? + assert h.get_custom('hello')? == 'world' + assert h.get_custom('HELLO')? == 'world' + assert h.get_custom('Hello', exact: true)? == 'world' if _ := h.get_custom('hello', exact: true) { // should be none assert false @@ -117,15 +117,15 @@ fn test_get_custom() ? { fn test_starting_with() ? { mut h := new_header() - h.add_custom('Hello-1', 'world') ? - h.add_custom('Hello-21', 'world') ? - assert h.starting_with('Hello-') ? == 'Hello-1' - assert h.starting_with('Hello-2') ? == 'Hello-21' + h.add_custom('Hello-1', 'world')? + h.add_custom('Hello-21', 'world')? + assert h.starting_with('Hello-')? == 'Hello-1' + assert h.starting_with('Hello-2')? == 'Hello-21' } fn test_custom_values() ? { mut h := new_header() - h.add_custom('Hello', 'world') ? + h.add_custom('Hello', 'world')? assert h.custom_values('hello') == ['world'] assert h.custom_values('HELLO') == ['world'] assert h.custom_values('Hello', exact: true) == ['world'] @@ -135,7 +135,7 @@ fn test_custom_values() ? { fn test_coerce() ? { mut h := new_header() - h.add_custom('accept', 'foo') ? + h.add_custom('accept', 'foo')? h.add(.accept, 'bar') assert h.values(.accept) == ['foo', 'bar'] assert h.keys().len == 2 @@ -147,7 +147,7 @@ fn test_coerce() ? { fn test_coerce_canonicalize() ? { mut h := new_header() - h.add_custom('accept', 'foo') ? + h.add_custom('accept', 'foo')? h.add(.accept, 'bar') assert h.values(.accept) == ['foo', 'bar'] assert h.keys().len == 2 @@ -159,9 +159,9 @@ fn test_coerce_canonicalize() ? { fn test_coerce_custom() ? { mut h := new_header() - h.add_custom('Hello', 'foo') ? - h.add_custom('hello', 'bar') ? - h.add_custom('HELLO', 'baz') ? + h.add_custom('Hello', 'foo')? + h.add_custom('hello', 'bar')? + h.add_custom('HELLO', 'baz')? assert h.custom_values('hello') == ['foo', 'bar', 'baz'] assert h.keys().len == 3 @@ -172,8 +172,8 @@ fn test_coerce_custom() ? { fn test_coerce_canonicalize_custom() ? { mut h := new_header() - h.add_custom('foo-BAR', 'foo') ? - h.add_custom('FOO-bar', 'bar') ? + h.add_custom('foo-BAR', 'foo')? + h.add_custom('FOO-bar', 'bar')? assert h.custom_values('foo-bar') == ['foo', 'bar'] assert h.keys().len == 2 @@ -184,8 +184,8 @@ fn test_coerce_canonicalize_custom() ? { fn test_render_version() ? { mut h := new_header() - h.add_custom('accept', 'foo') ? - h.add_custom('Accept', 'bar') ? + h.add_custom('accept', 'foo')? + h.add_custom('Accept', 'bar')? h.add(.accept, 'baz') s1_0 := h.render(version: .v1_0) @@ -206,8 +206,8 @@ fn test_render_version() ? { fn test_render_coerce() ? { mut h := new_header() - h.add_custom('accept', 'foo') ? - h.add_custom('Accept', 'bar') ? + h.add_custom('accept', 'foo')? + h.add_custom('Accept', 'bar')? h.add(.accept, 'baz') h.add(.host, 'host') @@ -232,8 +232,8 @@ fn test_render_coerce() ? { fn test_render_canonicalize() ? { mut h := new_header() - h.add_custom('accept', 'foo') ? - h.add_custom('Accept', 'bar') ? + h.add_custom('accept', 'foo')? + h.add_custom('Accept', 'bar')? h.add(.accept, 'baz') h.add(.host, 'host') @@ -258,8 +258,8 @@ fn test_render_canonicalize() ? { fn test_render_coerce_canonicalize() ? { mut h := new_header() - h.add_custom('accept', 'foo') ? - h.add_custom('Accept', 'bar') ? + h.add_custom('accept', 'foo')? + h.add_custom('Accept', 'bar')? h.add(.accept, 'baz') h.add(.host, 'host') @@ -285,8 +285,8 @@ fn test_render_coerce_canonicalize() ? { fn test_str() ? { mut h := new_header() h.add(.accept, 'text/html') - h.add_custom('Accept', 'image/jpeg') ? - h.add_custom('X-custom', 'Hello') ? + h.add_custom('Accept', 'image/jpeg')? + h.add_custom('X-custom', 'Hello')? // key order is not guaranteed assert h.str() == 'Accept: text/html\r\nAccept: image/jpeg\r\nX-custom: Hello\r\n' @@ -308,7 +308,7 @@ fn test_custom_header_from_map() ? { h := new_custom_header_from_map({ 'Server': 'VWeb' 'foo': 'bar' - }) ? + })? assert h.contains_custom('server') assert h.contains_custom('foo') assert h.get_custom('server') or { '' } == 'VWeb' @@ -323,7 +323,7 @@ fn test_header_join() ? { h2 := new_custom_header_from_map({ 'Server': 'VWeb' 'foo': 'bar' - }) ? + })? h3 := h1.join(h2) // h1 is unchanged assert h1.contains(.accept) @@ -343,35 +343,35 @@ fn test_header_join() ? { } fn parse_headers_test(s string, expected map[string]string) ? { - assert parse_headers(s) ? == new_custom_header_from_map(expected) ? + assert parse_headers(s)? == new_custom_header_from_map(expected)? } fn test_parse_headers() ? { parse_headers_test('foo: bar', { 'foo': 'bar' - }) ? + })? parse_headers_test('foo: \t bar', { 'foo': 'bar' - }) ? + })? parse_headers_test('foo: bar\r\n\tbaz', { 'foo': 'bar baz' - }) ? + })? parse_headers_test('foo: bar \r\n\tbaz\r\n buzz', { 'foo': 'bar baz buzz' - }) ? + })? parse_headers_test('foo: bar\r\nbar:baz', { 'foo': 'bar' 'bar': 'baz' - }) ? + })? parse_headers_test('foo: bar\r\nbar:baz\r\n', { 'foo': 'bar' 'bar': 'baz' - }) ? + })? parse_headers_test('foo: bar\r\nbar:baz\r\n\r\n', { 'foo': 'bar' 'bar': 'baz' - }) ? - assert parse_headers('foo: bar\r\nfoo:baz') ?.custom_values('foo') == ['bar', 'baz'] + })? + assert parse_headers('foo: bar\r\nfoo:baz')?.custom_values('foo') == ['bar', 'baz'] if x := parse_headers(' oops: oh no') { return error('should have errored, but got $x') diff --git a/vlib/net/http/http.v b/vlib/net/http/http.v index aac5897ec4..0641c794ee 100644 --- a/vlib/net/http/http.v +++ b/vlib/net/http/http.v @@ -154,7 +154,7 @@ pub fn fetch(config FetchConfig) ?Response { in_memory_verification: config.in_memory_verification allow_redirect: config.allow_redirect } - res := req.do() ? + res := req.do()? return res } @@ -183,7 +183,7 @@ fn fetch_with_method(method Method, _config FetchConfig) ?Response { } fn build_url_from_fetch(config FetchConfig) ?string { - mut url := urllib.parse(config.url) ? + mut url := urllib.parse(config.url)? if config.params.len == 0 { return url.str() } diff --git a/vlib/net/http/http_httpbin_test.v b/vlib/net/http/http_httpbin_test.v index a3ddccc2f3..db35b4682d 100644 --- a/vlib/net/http/http_httpbin_test.v +++ b/vlib/net/http/http_httpbin_test.v @@ -23,7 +23,7 @@ fn http_fetch_mock(_methods []string, _config FetchConfig) ?[]Response { for method in methods { lmethod := method.to_lower() config.method = method_from_str(method) - res := fetch(FetchConfig{ ...config, url: url + lmethod }) ? + res := fetch(FetchConfig{ ...config, url: url + lmethod })? // TODO // body := json.decode(HttpbinResponseBody,res.text)? result << res @@ -80,7 +80,7 @@ fn test_http_fetch_with_headers() ? { return } mut header := new_header() - header.add_custom('Test-Header', 'hello world') ? + header.add_custom('Test-Header', 'hello world')? responses := http_fetch_mock([], header: header ) or { panic(err) } diff --git a/vlib/net/http/request.v b/vlib/net/http/request.v index 9572b01203..0a59431b9e 100644 --- a/vlib/net/http/request.v +++ b/vlib/net/http/request.v @@ -62,7 +62,7 @@ pub fn (req &Request) do() ?Response { if no_redirects == max_redirects { return error('http.request.do: maximum number of redirects reached ($max_redirects)') } - qresp := req.method_and_url_to_response(req.method, rurl) ? + qresp := req.method_and_url_to_response(req.method, rurl)? resp = qresp if !req.allow_redirect { break @@ -105,11 +105,11 @@ fn (req &Request) method_and_url_to_response(method Method, url urllib.URL) ?Res // println('fetch $method, $scheme, $host_name, $nport, $path ') if scheme == 'https' { // println('ssl_do( $nport, $method, $host_name, $path )') - res := req.ssl_do(nport, method, host_name, path) ? + res := req.ssl_do(nport, method, host_name, path)? return res } else if scheme == 'http' { // println('http_do( $nport, $method, $host_name, $path )') - res := req.http_do('$host_name:$nport', method, path) ? + res := req.http_do('$host_name:$nport', method, path)? return res } return error('http.request.method_and_url_to_response: unsupported scheme: "$scheme"') @@ -152,18 +152,18 @@ fn (req &Request) build_request_cookies_header() string { } fn (req &Request) http_do(host string, method Method, path string) ?Response { - host_name, _ := net.split_address(host) ? + host_name, _ := net.split_address(host)? s := req.build_request_headers(method, host_name, path) - mut client := net.dial_tcp(host) ? + mut client := net.dial_tcp(host)? client.set_read_timeout(req.read_timeout) client.set_write_timeout(req.write_timeout) // TODO this really needs to be exposed somehow - client.write(s.bytes()) ? + client.write(s.bytes())? $if trace_http_request ? { eprintln('> $s') } - mut bytes := io.read_all(reader: client) ? - client.close() ? + mut bytes := io.read_all(reader: client)? + client.close()? response_text := bytes.bytestr() $if trace_http_response ? { eprintln('< $response_text') @@ -179,7 +179,7 @@ pub fn (req &Request) referer() string { // parse_request parses a raw HTTP request into a Request object. // See also: `parse_request_head`, which parses only the headers. pub fn parse_request(mut reader io.BufferedReader) ?Request { - mut request := parse_request_head(mut reader) ? + mut request := parse_request_head(mut reader)? // body mut body := []u8{} @@ -201,16 +201,16 @@ pub fn parse_request(mut reader io.BufferedReader) ?Request { // parse_request_head parses *only* the header of a raw HTTP request into a Request object pub fn parse_request_head(mut reader io.BufferedReader) ?Request { // request line - mut line := reader.read_line() ? - method, target, version := parse_request_line(line) ? + mut line := reader.read_line()? + method, target, version := parse_request_line(line)? // headers mut header := new_header() - line = reader.read_line() ? + line = reader.read_line()? for line != '' { - key, value := parse_header(line) ? - header.add_custom(key, value) ? - line = reader.read_line() ? + key, value := parse_header(line)? + header.add_custom(key, value)? + line = reader.read_line()? } header.coerce(canonicalize: true) @@ -228,7 +228,7 @@ fn parse_request_line(s string) ?(Method, urllib.URL, Version) { return error('malformed request line') } method := method_from_str(words[0]) - target := urllib.parse(words[1]) ? + target := urllib.parse(words[1])? version := version_from_str(words[2]) if version == .unknown { return error('unsupported version') diff --git a/vlib/net/http/request_test.v b/vlib/net/http/request_test.v index 4c6f6d9e42..1ab43d87de 100644 --- a/vlib/net/http/request_test.v +++ b/vlib/net/http/request_test.v @@ -178,7 +178,7 @@ fn test_parse_large_body() ? { body := 'A'.repeat(101) // greater than max_bytes req := 'GET / HTTP/1.1\r\nContent-Length: $body.len\r\n\r\n$body' mut reader_ := reader(req) - result := parse_request(mut reader_) ? + result := parse_request(mut reader_)? assert result.data.len == body.len assert result.data == body } diff --git a/vlib/net/http/response.v b/vlib/net/http/response.v index 8abd8e7b44..b1c22f7243 100644 --- a/vlib/net/http/response.v +++ b/vlib/net/http/response.v @@ -35,10 +35,10 @@ pub fn (resp Response) bytestr() string { // Parse a raw HTTP response into a Response object pub fn parse_response(resp string) ?Response { - version, status_code, status_msg := parse_status_line(resp.all_before('\n')) ? + version, status_code, status_msg := parse_status_line(resp.all_before('\n'))? // Build resp header map and separate the body - start_idx, end_idx := find_headers_range(resp) ? - header := parse_headers(resp.substr(start_idx, end_idx)) ? + start_idx, end_idx := find_headers_range(resp)? + header := parse_headers(resp.substr(start_idx, end_idx))? mut text := resp.substr(end_idx, resp.len) if header.get(.transfer_encoding) or { '' } == 'chunked' { text = chunked.decode(text) @@ -71,7 +71,7 @@ fn parse_status_line(line string) ?(string, int, string) { for digit in digits { strconv.atoi(digit) or { return error('HTTP version must contain only integers') } } - return version, strconv.atoi(data[1]) ?, data[2] + return version, strconv.atoi(data[1])?, data[2] } // cookies parses the Set-Cookie headers into Cookie objects diff --git a/vlib/net/http/response_test.v b/vlib/net/http/response_test.v index bf2fba3f6a..a8f45afcdd 100644 --- a/vlib/net/http/response_test.v +++ b/vlib/net/http/response_test.v @@ -17,7 +17,7 @@ fn test_response_bytestr() ? { lines := resp.bytestr().split_into_lines() assert lines[0] == 'HTTP/1.1 302 Found' // header order is not guaranteed - check_headers(['Location: /', 'Content-Length: 3'], lines[1..3]) ? + check_headers(['Location: /', 'Content-Length: 3'], lines[1..3])? assert lines[3] == '' assert lines[4] == 'Foo' } diff --git a/vlib/net/http/server.v b/vlib/net/http/server.v index 6b808d58dc..ff3e22f7ff 100644 --- a/vlib/net/http/server.v +++ b/vlib/net/http/server.v @@ -38,7 +38,7 @@ pub fn (mut s Server) listen_and_serve() ? { if s.handler is DebugHandler { eprintln('Server handler not set, using debug handler') } - s.listener = net.listen_tcp(.ip6, ':$s.port') ? + s.listener = net.listen_tcp(.ip6, ':$s.port')? s.listener.set_accept_timeout(s.accept_timeout) eprintln('Listening on :$s.port') s.state = .running diff --git a/vlib/net/http/server_test.v b/vlib/net/http/server_test.v index 790da30b56..0b4e9c85c0 100644 --- a/vlib/net/http/server_test.v +++ b/vlib/net/http/server_test.v @@ -11,7 +11,7 @@ fn test_server_stop() ? { server.stop() assert server.status() == .stopped assert watch.elapsed() < 100 * time.millisecond - t.wait() ? + t.wait()? assert watch.elapsed() < 999 * time.millisecond } @@ -26,7 +26,7 @@ fn test_server_close() ? { server.close() assert server.status() == .closed assert watch.elapsed() < 100 * time.millisecond - t.wait() ? + t.wait()? assert watch.elapsed() < 999 * time.millisecond } @@ -71,19 +71,19 @@ fn test_server_custom_handler() ? { for server.status() != .running { time.sleep(10 * time.millisecond) } - x := http.fetch(url: 'http://localhost:$cport/endpoint?abc=xyz', data: 'my data') ? + x := http.fetch(url: 'http://localhost:$cport/endpoint?abc=xyz', data: 'my data')? assert x.text == 'my data, /endpoint?abc=xyz' assert x.status_code == 200 assert x.http_version == '1.1' - y := http.fetch(url: 'http://localhost:$cport/another/endpoint', data: 'abcde') ? + y := http.fetch(url: 'http://localhost:$cport/another/endpoint', data: 'abcde')? assert y.text == 'abcde, /another/endpoint' assert y.status_code == 200 assert y.status() == .ok assert y.http_version == '1.1' // - http.fetch(url: 'http://localhost:$cport/something/else') ? + http.fetch(url: 'http://localhost:$cport/something/else')? server.stop() - t.wait() ? + t.wait()? assert handler.counter == 3 assert handler.oks == 2 assert handler.not_founds == 1 diff --git a/vlib/net/openssl/ssl_connection.v b/vlib/net/openssl/ssl_connection.v index ca84e2b4d9..ec79c6d261 100644 --- a/vlib/net/openssl/ssl_connection.v +++ b/vlib/net/openssl/ssl_connection.v @@ -40,7 +40,7 @@ pub fn (mut s SSLConn) shutdown() ? { } if err_res == .ssl_error_want_read { for { - ready := @select(s.handle, .read, s.duration) ? + ready := @select(s.handle, .read, s.duration)? if ready { break } @@ -48,7 +48,7 @@ pub fn (mut s SSLConn) shutdown() ? { continue } else if err_res == .ssl_error_want_write { for { - ready := @select(s.handle, .write, s.duration) ? + ready := @select(s.handle, .write, s.duration)? if ready { break } @@ -123,10 +123,10 @@ pub fn (mut s SSLConn) connect(mut tcp_conn net.TcpConn, hostname string) ? { for { res = C.SSL_connect(voidptr(s.ssl)) if res != 1 { - err_res := ssl_error(res, s.ssl) ? + err_res := ssl_error(res, s.ssl)? if err_res == .ssl_error_want_read { for { - ready := @select(s.handle, .read, s.duration) ? + ready := @select(s.handle, .read, s.duration)? if ready { break } @@ -134,7 +134,7 @@ pub fn (mut s SSLConn) connect(mut tcp_conn net.TcpConn, hostname string) ? { continue } else if err_res == .ssl_error_want_write { for { - ready := @select(s.handle, .write, s.duration) ? + ready := @select(s.handle, .write, s.duration)? if ready { break } @@ -152,10 +152,10 @@ pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) ?int { for { res = C.SSL_read(voidptr(s.ssl), buf_ptr, len) if res < 0 { - err_res := ssl_error(res, s.ssl) ? + err_res := ssl_error(res, s.ssl)? if err_res == .ssl_error_want_read { for { - ready := @select(s.handle, .read, s.duration) ? + ready := @select(s.handle, .read, s.duration)? if ready { break } @@ -163,7 +163,7 @@ pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) ?int { continue } else if err_res == .ssl_error_want_write { for { - ready := @select(s.handle, .write, s.duration) ? + ready := @select(s.handle, .write, s.duration)? if ready { break } @@ -180,7 +180,7 @@ pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) ?int { } pub fn (mut s SSLConn) read(mut buffer []u8) ?int { - res := s.socket_read_into_ptr(&u8(buffer.data), buffer.len) ? + res := s.socket_read_into_ptr(&u8(buffer.data), buffer.len)? return res } @@ -194,17 +194,17 @@ pub fn (mut s SSLConn) write(bytes []u8) ?int { remaining := bytes.len - total_sent mut sent := C.SSL_write(voidptr(s.ssl), ptr, remaining) if sent <= 0 { - err_res := ssl_error(sent, s.ssl) ? + err_res := ssl_error(sent, s.ssl)? if err_res == .ssl_error_want_read { for { - ready := @select(s.handle, .read, s.duration) ? + ready := @select(s.handle, .read, s.duration)? if ready { break } } } else if err_res == .ssl_error_want_write { for { - ready := @select(s.handle, .write, s.duration) ? + ready := @select(s.handle, .write, s.duration)? if ready { break } @@ -254,13 +254,13 @@ fn @select(handle int, test Select, timeout time.Duration) ?bool { match test { .read { - net.socket_error(C.@select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout)) ? + net.socket_error(C.@select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout))? } .write { - net.socket_error(C.@select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout)) ? + net.socket_error(C.@select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout))? } .except { - net.socket_error(C.@select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout)) ? + net.socket_error(C.@select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout))? } } diff --git a/vlib/net/smtp/smtp.v b/vlib/net/smtp/smtp.v index 9c1d392496..19936854cf 100644 --- a/vlib/net/smtp/smtp.v +++ b/vlib/net/smtp/smtp.v @@ -67,7 +67,7 @@ pub fn new_client(config Client) ?&Client { mut c := &Client{ ...config } - c.reconnect() ? + c.reconnect()? return c } @@ -81,7 +81,7 @@ pub fn (mut c Client) reconnect() ? { c.conn = conn if c.ssl { - c.connect_ssl() ? + c.connect_ssl()? } else { c.reader = io.new_buffered_reader(reader: c.conn) } @@ -114,12 +114,12 @@ pub fn (mut c Client) send(config Mail) ? { // quit closes the connection to the server pub fn (mut c Client) quit() ? { - c.send_str('QUIT\r\n') ? - c.expect_reply(.close) ? + c.send_str('QUIT\r\n')? + c.expect_reply(.close)? if c.encrypted { - c.ssl_conn.shutdown() ? + c.ssl_conn.shutdown()? } else { - c.conn.close() ? + c.conn.close()? } c.is_open = false c.encrypted = false @@ -139,7 +139,7 @@ fn (mut c Client) connect_ssl() ? { fn (mut c Client) expect_reply(expected ReplyCode) ? { mut str := '' for { - str = c.reader.read_line() ? + str = c.reader.read_line()? if str.len < 4 { return error('Invalid SMTP response: $str') } @@ -175,23 +175,23 @@ fn (mut c Client) send_str(s string) ? { } if c.encrypted { - c.ssl_conn.write(s.bytes()) ? + c.ssl_conn.write(s.bytes())? } else { - c.conn.write(s.bytes()) ? + c.conn.write(s.bytes())? } } [inline] fn (mut c Client) send_ehlo() ? { - c.send_str('EHLO $c.server\r\n') ? - c.expect_reply(.action_ok) ? + c.send_str('EHLO $c.server\r\n')? + c.expect_reply(.action_ok)? } [inline] fn (mut c Client) send_starttls() ? { - c.send_str('STARTTLS\r\n') ? - c.expect_reply(.ready) ? - c.connect_ssl() ? + c.send_str('STARTTLS\r\n')? + c.expect_reply(.ready)? + c.connect_ssl()? } [inline] @@ -206,23 +206,23 @@ fn (mut c Client) send_auth() ? { sb.write_string(c.password) a := sb.str() auth := 'AUTH PLAIN ${base64.encode_str(a)}\r\n' - c.send_str(auth) ? - c.expect_reply(.auth_ok) ? + c.send_str(auth)? + c.expect_reply(.auth_ok)? } fn (mut c Client) send_mailfrom(from string) ? { - c.send_str('MAIL FROM: <$from>\r\n') ? - c.expect_reply(.action_ok) ? + c.send_str('MAIL FROM: <$from>\r\n')? + c.expect_reply(.action_ok)? } fn (mut c Client) send_mailto(to string) ? { - c.send_str('RCPT TO: <$to>\r\n') ? - c.expect_reply(.action_ok) ? + c.send_str('RCPT TO: <$to>\r\n')? + c.expect_reply(.action_ok)? } fn (mut c Client) send_data() ? { - c.send_str('DATA\r\n') ? - c.expect_reply(.mail_start) ? + c.send_str('DATA\r\n')? + c.expect_reply(.mail_start)? } fn (mut c Client) send_body(cfg Mail) ? { @@ -243,6 +243,6 @@ fn (mut c Client) send_body(cfg Mail) ? { sb.write_string('\r\n\r\n') sb.write_string(cfg.body) sb.write_string('\r\n.\r\n') - c.send_str(sb.str()) ? - c.expect_reply(.action_ok) ? + c.send_str(sb.str())? + c.expect_reply(.action_ok)? } diff --git a/vlib/net/tcp.v b/vlib/net/tcp.v index 2350296b17..8cdf6c5a4d 100644 --- a/vlib/net/tcp.v +++ b/vlib/net/tcp.v @@ -49,11 +49,11 @@ pub fn (mut c TcpConn) close() ? { $if trace_tcp ? { eprintln(' TcpConn.close | c.sock.handle: ${c.sock.handle:6}') } - c.sock.close() ? + c.sock.close()? } pub fn (c TcpConn) read_ptr(buf_ptr &u8, len int) ?int { - mut res := wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0)) ? + mut res := wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))? $if trace_tcp ? { eprintln('<<< TcpConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res') } @@ -66,8 +66,8 @@ pub fn (c TcpConn) read_ptr(buf_ptr &u8, len int) ?int { } code := error_code() if code == int(error_ewouldblock) { - c.wait_for_read() ? - res = wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0)) ? + c.wait_for_read()? + res = wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))? $if trace_tcp ? { eprintln('<<< TcpConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res') } @@ -79,7 +79,7 @@ pub fn (c TcpConn) read_ptr(buf_ptr &u8, len int) ?int { } return socket_error(res) } else { - wrap_error(code) ? + wrap_error(code)? } return none } @@ -119,10 +119,10 @@ pub fn (mut c TcpConn) write_ptr(b &u8, len int) ?int { if sent < 0 { code := error_code() if code == int(error_ewouldblock) { - c.wait_for_write() ? + c.wait_for_write()? continue } else { - wrap_error(code) ? + wrap_error(code)? } } total_sent += sent @@ -189,12 +189,12 @@ pub fn (c &TcpConn) peer_addr() ?Addr { } } mut size := sizeof(Addr) - socket_error_message(C.getpeername(c.sock.handle, voidptr(&addr), &size), 'peer_addr failed') ? + socket_error_message(C.getpeername(c.sock.handle, voidptr(&addr), &size), 'peer_addr failed')? return addr } pub fn (c &TcpConn) peer_ip() ?string { - return c.peer_addr() ?.str() + return c.peer_addr()?.str() } pub fn (c &TcpConn) addr() ?Addr { @@ -226,8 +226,8 @@ pub fn listen_tcp(family AddrFamily, saddr string) ?&TcpListener { // cast to the correct type alen := addr.len() - socket_error_message(C.bind(s.handle, voidptr(&addr), alen), 'binding to $saddr failed') ? - socket_error_message(C.listen(s.handle, 128), 'listening on $saddr failed') ? + socket_error_message(C.bind(s.handle, voidptr(&addr), alen), 'binding to $saddr failed')? + socket_error_message(C.listen(s.handle, 128), 'listening on $saddr failed')? return &TcpListener{ sock: s accept_deadline: no_deadline @@ -241,13 +241,13 @@ pub fn (mut l TcpListener) accept() ?&TcpConn { } mut new_handle := C.accept(l.sock.handle, 0, 0) if new_handle <= 0 { - l.wait_for_accept() ? + l.wait_for_accept()? new_handle = C.accept(l.sock.handle, 0, 0) if new_handle == -1 || new_handle == 0 { return error('accept failed') } } - new_sock := tcp_socket_from_handle(new_handle) ? + new_sock := tcp_socket_from_handle(new_handle)? $if trace_tcp ? { eprintln(' TcpListener.accept | << new_sock.handle: ${new_sock.handle:6}') } @@ -282,7 +282,7 @@ pub fn (mut c TcpListener) wait_for_accept() ? { } pub fn (mut c TcpListener) close() ? { - c.sock.close() ? + c.sock.close()? } pub fn (c &TcpListener) addr() ?Addr { @@ -294,7 +294,7 @@ struct TcpSocket { } fn new_tcp_socket(family AddrFamily) ?TcpSocket { - handle := socket_error(C.socket(family, SocketType.tcp, 0)) ? + handle := socket_error(C.socket(family, SocketType.tcp, 0))? mut s := TcpSocket{ handle: handle } @@ -308,14 +308,14 @@ fn new_tcp_socket(family AddrFamily) ?TcpSocket { // TODO(emily): // Move this to its own function on the socket - s.set_option_int(.reuse_addr, 1) ? + s.set_option_int(.reuse_addr, 1)? $if !net_blocking_sockets ? { $if windows { t := u32(1) // true - socket_error(C.ioctlsocket(handle, fionbio, &t)) ? + socket_error(C.ioctlsocket(handle, fionbio, &t))? } $else { - socket_error(C.fcntl(handle, C.F_SETFL, C.fcntl(handle, C.F_GETFL) | C.O_NONBLOCK)) ? + socket_error(C.fcntl(handle, C.F_SETFL, C.fcntl(handle, C.F_GETFL) | C.O_NONBLOCK))? } } return s @@ -329,16 +329,16 @@ fn tcp_socket_from_handle(sockfd int) ?TcpSocket { eprintln(' tcp_socket_from_handle | s.handle: ${s.handle:6}') } // s.set_option_bool(.reuse_addr, true)? - s.set_option_int(.reuse_addr, 1) ? + s.set_option_int(.reuse_addr, 1)? s.set_dualstack(true) or { // Not ipv6, we dont care } $if !net_blocking_sockets ? { $if windows { t := u32(1) // true - socket_error(C.ioctlsocket(sockfd, fionbio, &t)) ? + socket_error(C.ioctlsocket(sockfd, fionbio, &t))? } $else { - socket_error(C.fcntl(sockfd, C.F_SETFL, C.fcntl(sockfd, C.F_GETFL) | C.O_NONBLOCK)) ? + socket_error(C.fcntl(sockfd, C.F_SETFL, C.fcntl(sockfd, C.F_GETFL) | C.O_NONBLOCK))? } } return s @@ -353,17 +353,17 @@ pub fn (mut s TcpSocket) set_option_bool(opt SocketOption, value bool) ? { // return err_option_wrong_type // } x := int(value) - socket_error(C.setsockopt(s.handle, C.SOL_SOCKET, int(opt), &x, sizeof(int))) ? + socket_error(C.setsockopt(s.handle, C.SOL_SOCKET, int(opt), &x, sizeof(int)))? } pub fn (mut s TcpSocket) set_dualstack(on bool) ? { x := int(!on) socket_error(C.setsockopt(s.handle, C.IPPROTO_IPV6, int(SocketOption.ipv6_only), &x, - sizeof(int))) ? + sizeof(int)))? } pub fn (mut s TcpSocket) set_option_int(opt SocketOption, value int) ? { - socket_error(C.setsockopt(s.handle, C.SOL_SOCKET, int(opt), &value, sizeof(int))) ? + socket_error(C.setsockopt(s.handle, C.SOL_SOCKET, int(opt), &value, sizeof(int)))? } fn (mut s TcpSocket) close() ? { @@ -392,11 +392,11 @@ fn (mut s TcpSocket) connect(a Addr) ? { // determine whether connect() completed successfully (SO_ERROR is zero) or // unsuccessfully (SO_ERROR is one of the usual error codes listed here, // ex‐ plaining the reason for the failure). - write_result := s.@select(.write, net.connect_timeout) ? + write_result := s.@select(.write, net.connect_timeout)? if write_result { err := 0 len := sizeof(err) - socket_error(C.getsockopt(s.handle, C.SOL_SOCKET, C.SO_ERROR, &err, &len)) ? + socket_error(C.getsockopt(s.handle, C.SOL_SOCKET, C.SO_ERROR, &err, &len))? if err != 0 { return wrap_error(err) @@ -406,7 +406,7 @@ fn (mut s TcpSocket) connect(a Addr) ? { } // Get the error - socket_error(C.connect(s.handle, voidptr(&a), a.len())) ? + socket_error(C.connect(s.handle, voidptr(&a), a.len()))? // otherwise we timed out return err_connect_timed_out diff --git a/vlib/net/tcp_read_line.v b/vlib/net/tcp_read_line.v index a9c6e2e342..b7a9ed144a 100644 --- a/vlib/net/tcp_read_line.v +++ b/vlib/net/tcp_read_line.v @@ -29,7 +29,7 @@ pub fn (mut con TcpConn) set_blocking(state bool) ? { if !con.is_blocking { t = 1 } - socket_error(C.ioctlsocket(con.sock.handle, fionbio, &t)) ? + socket_error(C.ioctlsocket(con.sock.handle, fionbio, &t))? } $else { mut flags := C.fcntl(con.sock.handle, C.F_GETFL, 0) if state { @@ -37,7 +37,7 @@ pub fn (mut con TcpConn) set_blocking(state bool) ? { } else { flags |= C.O_NONBLOCK } - socket_error(C.fcntl(con.sock.handle, C.F_SETFL, flags)) ? + socket_error(C.fcntl(con.sock.handle, C.F_SETFL, flags))? } } diff --git a/vlib/net/tcp_test.v b/vlib/net/tcp_test.v index 4d0a81a60b..6ff5c86567 100644 --- a/vlib/net/tcp_test.v +++ b/vlib/net/tcp_test.v @@ -31,18 +31,18 @@ fn one_shot_echo_server(mut l net.TcpListener, ch_started chan int) ? { } fn echo(address string) ? { - mut c := net.dial_tcp(address) ? + mut c := net.dial_tcp(address)? defer { c.close() or {} } - println('local: ' + c.addr() ?.str()) - println(' peer: ' + c.peer_addr() ?.str()) + println('local: ' + c.addr()?.str()) + println(' peer: ' + c.peer_addr()?.str()) data := 'Hello from vlib/net!' - c.write_string(data) ? + c.write_string(data)? mut buf := []u8{len: 4096} - read := c.read(mut buf) ? + read := c.read(mut buf)? assert read == data.len for i := 0; i < read; i++ { assert buf[i] == data[i] diff --git a/vlib/net/udp.v b/vlib/net/udp.v index 2821f23bd9..9c2db65159 100644 --- a/vlib/net/udp.v +++ b/vlib/net/udp.v @@ -28,7 +28,7 @@ mut: } pub fn dial_udp(raddr string) ?&UdpConn { - addrs := resolve_addrs_fuzzy(raddr, .udp) ? + addrs := resolve_addrs_fuzzy(raddr, .udp)? for addr in addrs { // create a local socket for this @@ -47,9 +47,9 @@ pub fn dial_udp(raddr string) ?&UdpConn { } // pub fn dial_udp(laddr string, raddr string) ?&UdpConn { -// local := resolve_addr(laddr, .inet, .udp) ? +// local := resolve_addr(laddr, .inet, .udp)? -// sbase := new_udp_socket() ? +// sbase := new_udp_socket()? // sock := UdpSocket{ // handle: sbase.handle @@ -78,10 +78,10 @@ pub fn (mut c UdpConn) write_to_ptr(addr Addr, b &u8, len int) ?int { } code := error_code() if code == int(error_ewouldblock) { - c.wait_for_write() ? - socket_error(C.sendto(c.sock.handle, b, len, 0, voidptr(&addr), addr.len())) ? + c.wait_for_write()? + socket_error(C.sendto(c.sock.handle, b, len, 0, voidptr(&addr), addr.len()))? } else { - wrap_error(code) ? + wrap_error(code)? } return none } @@ -105,20 +105,20 @@ pub fn (mut c UdpConn) read(mut buf []u8) ?(int, Addr) { } len := sizeof(Addr) mut res := wrap_read_result(C.recvfrom(c.sock.handle, voidptr(buf.data), buf.len, - 0, voidptr(&addr), &len)) ? + 0, voidptr(&addr), &len))? if res > 0 { return res, addr } code := error_code() if code == int(error_ewouldblock) { - c.wait_for_read() ? + c.wait_for_read()? // same setup as in tcp res = wrap_read_result(C.recvfrom(c.sock.handle, voidptr(buf.data), buf.len, 0, - voidptr(&addr), &len)) ? - res2 := socket_error(res) ? + voidptr(&addr), &len))? + res2 := socket_error(res)? return res2, addr } else { - wrap_error(code) ? + wrap_error(code)? } return none } @@ -181,13 +181,13 @@ pub fn (mut c UdpConn) close() ? { } pub fn listen_udp(laddr string) ?&UdpConn { - addrs := resolve_addrs_fuzzy(laddr, .udp) ? + addrs := resolve_addrs_fuzzy(laddr, .udp)? // TODO(emily): // here we are binding to the first address // and that is probably not ideal addr := addrs[0] return &UdpConn{ - sock: new_udp_socket(addr) ? + sock: new_udp_socket(addr)? read_timeout: net.udp_default_read_timeout write_timeout: net.udp_default_write_timeout } @@ -196,7 +196,7 @@ pub fn listen_udp(laddr string) ?&UdpConn { fn new_udp_socket(local_addr Addr) ?&UdpSocket { family := local_addr.family() - sockfd := socket_error(C.socket(family, SocketType.udp, 0)) ? + sockfd := socket_error(C.socket(family, SocketType.udp, 0))? mut s := &UdpSocket{ handle: sockfd l: local_addr @@ -207,24 +207,24 @@ fn new_udp_socket(local_addr Addr) ?&UdpSocket { } } - s.set_option_bool(.reuse_addr, true) ? + s.set_option_bool(.reuse_addr, true)? if family == .ip6 { - s.set_dualstack(true) ? + s.set_dualstack(true)? } $if !net_blocking_sockets ? { // NOTE: refer to comments in tcp.v $if windows { t := u32(1) // true - socket_error(C.ioctlsocket(sockfd, fionbio, &t)) ? + socket_error(C.ioctlsocket(sockfd, fionbio, &t))? } $else { - socket_error(C.fcntl(sockfd, C.F_SETFD, C.O_NONBLOCK)) ? + socket_error(C.fcntl(sockfd, C.F_SETFD, C.O_NONBLOCK))? } } // cast to the correct type - socket_error(C.bind(s.handle, voidptr(&local_addr), local_addr.len())) ? + socket_error(C.bind(s.handle, voidptr(&local_addr), local_addr.len()))? return s } @@ -246,13 +246,13 @@ fn new_udp_socket_for_remote(raddr Addr) ?&UdpSocket { addr = new_ip6(0, addr_ip6_any) } .unix { - addr = temp_unix() ? + addr = temp_unix()? } else { panic('Invalid family') } } - mut sock := new_udp_socket(addr) ? + mut sock := new_udp_socket(addr)? sock.has_r = true sock.r = raddr @@ -268,13 +268,13 @@ pub fn (mut s UdpSocket) set_option_bool(opt SocketOption, value bool) ? { // return err_option_wrong_type // } x := int(value) - socket_error(C.setsockopt(s.handle, C.SOL_SOCKET, int(opt), &x, sizeof(int))) ? + socket_error(C.setsockopt(s.handle, C.SOL_SOCKET, int(opt), &x, sizeof(int)))? } pub fn (mut s UdpSocket) set_dualstack(on bool) ? { x := int(!on) socket_error(C.setsockopt(s.handle, C.IPPROTO_IPV6, int(SocketOption.ipv6_only), &x, - sizeof(int))) ? + sizeof(int)))? } fn (mut s UdpSocket) close() ? { diff --git a/vlib/net/udp_test.v b/vlib/net/udp_test.v index 4ca82d5c8a..e4d4adf631 100644 --- a/vlib/net/udp_test.v +++ b/vlib/net/udp_test.v @@ -48,7 +48,7 @@ fn echo() ? { println('Got "$buf.bytestr()"') - c.close() ? + c.close()? } fn test_udp() { diff --git a/vlib/net/unix/common.v b/vlib/net/unix/common.v index 75e591f24c..9891e3030c 100644 --- a/vlib/net/unix/common.v +++ b/vlib/net/unix/common.v @@ -15,10 +15,10 @@ fn C.strncpy(&char, &char, int) fn shutdown(handle int) ? { $if windows { C.shutdown(handle, C.SD_BOTH) - net.socket_error(C.closesocket(handle)) ? + net.socket_error(C.closesocket(handle))? } $else { C.shutdown(handle, C.SHUT_RDWR) - net.socket_error(C.close(handle)) ? + net.socket_error(C.close(handle))? } } @@ -47,13 +47,13 @@ fn @select(handle int, test Select, timeout time.Duration) ?bool { match test { .read { - net.socket_error(C.@select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout)) ? + net.socket_error(C.@select(handle + 1, &set, C.NULL, C.NULL, timeval_timeout))? } .write { - net.socket_error(C.@select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout)) ? + net.socket_error(C.@select(handle + 1, C.NULL, &set, C.NULL, timeval_timeout))? } .except { - net.socket_error(C.@select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout)) ? + net.socket_error(C.@select(handle + 1, C.NULL, C.NULL, &set, timeval_timeout))? } } @@ -67,7 +67,7 @@ fn wait_for_common(handle int, deadline time.Time, timeout time.Duration, test S if timeout < 0 { return net.err_timed_out } - ready := @select(handle, test, timeout) ? + ready := @select(handle, test, timeout)? if ready { return } @@ -82,7 +82,7 @@ fn wait_for_common(handle int, deadline time.Time, timeout time.Duration, test S return net.err_timed_out } - ready := @select(handle, test, d_timeout) ? + ready := @select(handle, test, d_timeout)? if ready { return } diff --git a/vlib/net/unix/stream_nix.v b/vlib/net/unix/stream_nix.v index 7904716048..f5fc4b00d1 100644 --- a/vlib/net/unix/stream_nix.v +++ b/vlib/net/unix/stream_nix.v @@ -41,7 +41,7 @@ fn error_code() int { } fn new_stream_socket() ?StreamSocket { - sockfd := net.socket_error(C.socket(net.AddrFamily.unix, net.SocketType.tcp, 0)) ? + sockfd := net.socket_error(C.socket(net.AddrFamily.unix, net.SocketType.tcp, 0))? mut s := StreamSocket{ handle: sockfd } @@ -73,12 +73,12 @@ fn (mut s StreamSocket) connect(a string) ? { return } _ := error_code() - write_result := s.@select(.write, unix.connect_timeout) ? + write_result := s.@select(.write, unix.connect_timeout)? if write_result { // succeeded return } - except_result := s.@select(.except, unix.connect_timeout) ? + except_result := s.@select(.except, unix.connect_timeout)? if except_result { return net.err_connect_failed } @@ -90,7 +90,7 @@ pub fn listen_stream(sock string) ?&StreamListener { if sock.len >= max_sun_path { return error('Socket path too long! Max length: ${max_sun_path - 1} chars.') } - mut s := new_stream_socket() ? + mut s := new_stream_socket()? s.path = sock mut addr := C.sockaddr_un{} unsafe { C.memset(&addr, 0, sizeof(C.sockaddr_un)) } @@ -98,19 +98,19 @@ pub fn listen_stream(sock string) ?&StreamListener { unsafe { C.strncpy(&addr.sun_path[0], &char(sock.str), max_sun_path) } size := C.SUN_LEN(&addr) if os.exists(sock) { - os.rm(sock) ? + os.rm(sock)? } - net.socket_error(C.bind(s.handle, voidptr(&addr), size)) ? - os.chmod(sock, 0o777) ? - net.socket_error(C.listen(s.handle, 128)) ? + net.socket_error(C.bind(s.handle, voidptr(&addr), size))? + os.chmod(sock, 0o777)? + net.socket_error(C.listen(s.handle, 128))? return &StreamListener{ sock: s } } pub fn connect_stream(path string) ?&StreamConn { - mut s := new_stream_socket() ? - s.connect(path) ? + mut s := new_stream_socket()? + s.connect(path)? return &StreamConn{ sock: s read_timeout: unix.unix_default_read_timeout @@ -121,7 +121,7 @@ pub fn connect_stream(path string) ?&StreamConn { pub fn (mut l StreamListener) accept() ?&StreamConn { mut new_handle := C.accept(l.sock.handle, 0, 0) if new_handle <= 0 { - l.wait_for_accept() ? + l.wait_for_accept()? new_handle = C.accept(l.sock.handle, 0, 0) if new_handle == -1 || new_handle == 0 { return error('accept failed') @@ -161,12 +161,12 @@ pub fn (mut c StreamListener) wait_for_accept() ? { } pub fn (mut c StreamListener) close() ? { - os.rm(c.sock.path) ? - c.sock.close() ? + os.rm(c.sock.path)? + c.sock.close()? } pub fn (mut c StreamConn) close() ? { - c.sock.close() ? + c.sock.close()? } // write_ptr blocks and attempts to write all data @@ -186,10 +186,10 @@ pub fn (mut c StreamConn) write_ptr(b &u8, len int) ?int { if sent < 0 { code := error_code() if code == int(error_ewouldblock) { - c.wait_for_write() ? + c.wait_for_write()? continue } else { - net.wrap_error(code) ? + net.wrap_error(code)? } } total_sent += sent @@ -209,7 +209,7 @@ pub fn (mut c StreamConn) write_string(s string) ?int { } pub fn (mut c StreamConn) read_ptr(buf_ptr &u8, len int) ?int { - mut res := wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0)) ? + mut res := wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))? $if trace_unix ? { eprintln('<<< StreamConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res') } @@ -218,14 +218,14 @@ pub fn (mut c StreamConn) read_ptr(buf_ptr &u8, len int) ?int { } code := error_code() if code == int(error_ewouldblock) { - c.wait_for_read() ? - res = wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0)) ? + c.wait_for_read()? + res = wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))? $if trace_unix ? { eprintln('<<< StreamConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res') } return net.socket_error(res) } else { - net.wrap_error(code) ? + net.wrap_error(code)? } return net.socket_error(code) } diff --git a/vlib/net/unix/unix_test.v b/vlib/net/unix/unix_test.v index 4d1cfd018e..fd4a6db1be 100644 --- a/vlib/net/unix/unix_test.v +++ b/vlib/net/unix/unix_test.v @@ -25,14 +25,14 @@ fn echo_server(mut l unix.StreamListener) ? { } fn echo() ? { - mut c := unix.connect_stream(test_port) ? + mut c := unix.connect_stream(test_port)? defer { c.close() or {} } data := 'Hello from vlib/net!' - c.write_string(data) ? + c.write_string(data)? mut buf := []u8{len: 4096} - read := c.read(mut buf) ? + read := c.read(mut buf)? assert read == data.len for i := 0; i < read; i++ { assert buf[i] == data[i] diff --git a/vlib/net/unix/use_net_and_net_unix_together_test.v b/vlib/net/unix/use_net_and_net_unix_together_test.v index 6f288966a8..d544a12f45 100644 --- a/vlib/net/unix/use_net_and_net_unix_together_test.v +++ b/vlib/net/unix/use_net_and_net_unix_together_test.v @@ -14,15 +14,15 @@ fn test_that_net_and_net_unix_can_be_imported_together_without_conflicts() ? { l.close() or {} } // - mut c := unix.connect_stream(test_port) ? + mut c := unix.connect_stream(test_port)? defer { c.close() or {} } // data := 'Hello from vlib/net!' - c.write_string(data) ? + c.write_string(data)? mut buf := []u8{len: 100} - assert c.read(mut buf) ? == data.len + assert c.read(mut buf)? == data.len eprintln('< client read back buf: |${buf[0..data.len].bytestr()}|') assert buf[0..data.len] == data.bytes() } diff --git a/vlib/net/urllib/urllib.v b/vlib/net/urllib/urllib.v index 0fdc315558..ff19431499 100644 --- a/vlib/net/urllib/urllib.v +++ b/vlib/net/urllib/urllib.v @@ -477,7 +477,7 @@ fn parse_url(rawurl string, via_request bool) ?URL { } // Split off possible leading 'http:', 'mailto:', etc. // Cannot contain escaped characters. - p := split_by_scheme(rawurl) ? + p := split_by_scheme(rawurl)? url.scheme = p[0] mut rest := p[1] url.scheme = url.scheme.to_lower() @@ -516,7 +516,7 @@ fn parse_url(rawurl string, via_request bool) ?URL { if ((url.scheme != '' || !via_request) && !rest.starts_with('///')) && rest.starts_with('//') { authority, r := split(rest[2..], `/`, false) rest = r - a := parse_authority(authority) ? + a := parse_authority(authority)? url.user = a.user url.host = a.host } @@ -524,7 +524,7 @@ fn parse_url(rawurl string, via_request bool) ?URL { // raw_path is a hint of the encoding of path. We don't want to set it if // the default escaping of path is equivalent, to help make sure that people // don't rely on it in general. - url.set_path(rest) ? + url.set_path(rest)? return url } @@ -538,10 +538,10 @@ fn parse_authority(authority string) ?ParseAuthorityRes { mut host := '' mut zuser := user('') if i < 0 { - h := parse_host(authority) ? + h := parse_host(authority)? host = h } else { - h := parse_host(authority[i + 1..]) ? + h := parse_host(authority[i + 1..])? host = h } if i < 0 { @@ -555,14 +555,14 @@ fn parse_authority(authority string) ?ParseAuthorityRes { return error(error_msg('parse_authority: invalid userinfo', '')) } if !userinfo.contains(':') { - u := unescape(userinfo, .encode_user_password) ? + u := unescape(userinfo, .encode_user_password)? userinfo = u zuser = user(userinfo) } else { mut username, mut password := split(userinfo, `:`, true) - u := unescape(username, .encode_user_password) ? + u := unescape(username, .encode_user_password)? username = u - p := unescape(password, .encode_user_password) ? + p := unescape(password, .encode_user_password)? password = p zuser = user_password(username, password) } @@ -621,7 +621,7 @@ fn parse_host(host string) ?string { // set_path will return an error only if the provided path contains an invalid // escaping. pub fn (mut u URL) set_path(p string) ?bool { - u.path = unescape(p, .encode_path) ? + u.path = unescape(p, .encode_path)? u.raw_path = if p == escape(u.path, .encode_path) { '' } else { p } return true } @@ -783,7 +783,7 @@ pub fn (u URL) str() string { // interpreted as a key set to an empty value. pub fn parse_query(query string) ?Values { mut m := new_values() - parse_query_values(mut m, query) ? + parse_query_values(mut m, query)? return m } @@ -915,7 +915,7 @@ pub fn (u &URL) is_abs() bool { // may be relative or absolute. parse returns nil, err on parse // failure, otherwise its return value is the same as resolve_reference. pub fn (u &URL) parse(ref string) ?URL { - refurl := parse(ref) ? + refurl := parse(ref)? return u.resolve_reference(refurl) } @@ -934,7 +934,7 @@ pub fn (u &URL) resolve_reference(ref &URL) ?URL { // The 'absoluteURI' or 'net_path' cases. // We can ignore the error from set_path since we know we provided a // validly-escaped path. - url.set_path(resolve_path(ref.escaped_path(), '')) ? + url.set_path(resolve_path(ref.escaped_path(), ''))? return url } if ref.opaque != '' { @@ -952,7 +952,7 @@ pub fn (u &URL) resolve_reference(ref &URL) ?URL { // The 'abs_path' or 'rel_path' cases. url.host = u.host url.user = u.user - url.set_path(resolve_path(u.escaped_path(), ref.escaped_path())) ? + url.set_path(resolve_path(u.escaped_path(), ref.escaped_path()))? return url } diff --git a/vlib/net/urllib/urllib_test.v b/vlib/net/urllib/urllib_test.v index 605c6ae7c8..50ee67e6aa 100644 --- a/vlib/net/urllib/urllib_test.v +++ b/vlib/net/urllib/urllib_test.v @@ -36,8 +36,8 @@ fn test_escape_unescape() { } fn test_parse_query() ? { - q1 := urllib.parse_query('format=%22%25l%3A+%25c+%25t%22') ? - q2 := urllib.parse_query('format="%l:+%c+%t"') ? + q1 := urllib.parse_query('format=%22%25l%3A+%25c+%25t%22')? + q2 := urllib.parse_query('format="%l:+%c+%t"')? // dump(q1) // dump(q2) assert q1.get('format') == '"%l: %c %t"' @@ -45,21 +45,21 @@ fn test_parse_query() ? { } fn test_parse_query_orders() ? { - query_one := urllib.parse_query('https://someapi.com/endpoint?gamma=zalibaba&tau=1&alpha=alibaba&signature=alibaba123') ? + query_one := urllib.parse_query('https://someapi.com/endpoint?gamma=zalibaba&tau=1&alpha=alibaba&signature=alibaba123')? qvalues := query_one.values() assert qvalues == ['zalibaba', '1', 'alibaba', 'alibaba123'] } fn test_parse_missing_host() ? { // issue #10311 - url := urllib.parse('http:///') ? + url := urllib.parse('http:///')? assert url.str() == 'http://///' } // testing the case where the key as a null value // e.g ?key= fn test_parse_none_value() ? { - query_one := urllib.parse_query('gamma=zalibaba&tau=1&alpha=alibaba&signature=') ? + query_one := urllib.parse_query('gamma=zalibaba&tau=1&alpha=alibaba&signature=')? qvalues := query_one.values() qvalues_map := query_one.to_map() assert qvalues == ['zalibaba', '1', 'alibaba'] @@ -75,7 +75,7 @@ fn test_parse_none_value() ? { // e.g https://www.vlang.dev?alibaba fn test_parse_empty_query_one() ? { query_str := 'alibaba' - query_one := urllib.parse_query(query_str) ? + query_one := urllib.parse_query(query_str)? qvalues := query_one.values() qvalues_map := query_one.to_map() query_encode := query_one.encode() @@ -90,7 +90,7 @@ fn test_parse_empty_query_one() ? { // e.g https://www.vlang.dev? fn test_parse_empty_query_two() ? { query_str := '' - query_one := urllib.parse_query(query_str) ? + query_one := urllib.parse_query(query_str)? qvalues := query_one.values() qvalues_map := query_one.to_map() query_encode := query_one.encode() diff --git a/vlib/net/util.v b/vlib/net/util.v index 33d7cec866..8d0ea2a06f 100644 --- a/vlib/net/util.v +++ b/vlib/net/util.v @@ -22,6 +22,6 @@ pub fn split_address(addr string) ?(string, u16) { // TODO(emily): Maybe do some more checking here // to validate ipv6 address sanity? - p := validate_port(port) ? + p := validate_port(port)? return address, p } diff --git a/vlib/net/websocket/events.v b/vlib/net/websocket/events.v index a442dafc7b..b64c876c53 100644 --- a/vlib/net/websocket/events.v +++ b/vlib/net/websocket/events.v @@ -162,7 +162,7 @@ fn (mut s Server) send_connect_event(mut c ServerClient) ?bool { return true } fun := s.accept_client_callbacks[0] - res := fun(mut c) ? + res := fun(mut c)? return res } diff --git a/vlib/net/websocket/handshake.v b/vlib/net/websocket/handshake.v index 43715cb7d7..a7163d9040 100644 --- a/vlib/net/websocket/handshake.v +++ b/vlib/net/websocket/handshake.v @@ -34,15 +34,15 @@ fn (mut ws Client) handshake() ? { } handshake_bytes := handshake.bytes() ws.debug_log('sending handshake: $handshake') - ws.socket_write(handshake_bytes) ? - ws.read_handshake(seckey) ? + ws.socket_write(handshake_bytes)? + ws.read_handshake(seckey)? unsafe { handshake_bytes.free() } } // handle_server_handshake manages websocket server handshake process fn (mut s Server) handle_server_handshake(mut c Client) ?(string, &ServerClient) { - msg := c.read_handshake_str() ? - handshake_response, client := s.parse_client_handshake(msg, mut c) ? + msg := c.read_handshake_str()? + handshake_response, client := s.parse_client_handshake(msg, mut c)? unsafe { msg.free() } return handshake_response, client } @@ -81,7 +81,7 @@ fn (mut s Server) parse_client_handshake(client_handshake string, mut c Client) 'Sec-WebSocket-Key', 'sec-websocket-key' { key = keys[1].trim_space() s.logger.debug('server-> got key: $key') - seckey = create_key_challenge_response(key) ? + seckey = create_key_challenge_response(key)? s.logger.debug('server-> challenge: $seckey, response: ${keys[1]}') flags << .has_accept } @@ -117,7 +117,7 @@ fn (mut ws Client) read_handshake_str() ?string { mut msg := [1024]u8{} mut buffer := [1]u8{} for total_bytes_read < 1024 { - bytes_read := ws.socket_read_ptr(&buffer[0], 1) ? + bytes_read := ws.socket_read_ptr(&buffer[0], 1)? if bytes_read == 0 { return error_with_code('unexpected no response from handshake', 5) } @@ -135,8 +135,8 @@ fn (mut ws Client) read_handshake_str() ?string { // read_handshake reads the handshake result and check if valid fn (mut ws Client) read_handshake(seckey string) ? { - mut msg := ws.read_handshake_str() ? - ws.check_handshake_response(msg, seckey) ? + mut msg := ws.read_handshake_str()? + ws.check_handshake_response(msg, seckey)? unsafe { msg.free() } } @@ -164,7 +164,7 @@ fn (mut ws Client) check_handshake_response(handshake_response string, seckey st } 'Sec-WebSocket-Accept', 'sec-websocket-accept' { ws.debug_log('seckey: $seckey') - challenge := create_key_challenge_response(seckey) ? + challenge := create_key_challenge_response(seckey)? ws.debug_log('challenge: $challenge, response: ${keys[1]}') if keys[1].trim_space() != challenge { return error_with_code('handshake_handler: Sec-WebSocket-Accept header does not match computed sha1/base64 response.', @@ -179,7 +179,7 @@ fn (mut ws Client) check_handshake_response(handshake_response string, seckey st } unsafe { lines.free() } if ws.flags.len < 3 { - ws.close(1002, 'invalid websocket HTTP headers') ? + ws.close(1002, 'invalid websocket HTTP headers')? return error_with_code('invalid websocket HTTP headers', 8) } } diff --git a/vlib/net/websocket/io.v b/vlib/net/websocket/io.v index 35d6e08a65..2d0db657b2 100644 --- a/vlib/net/websocket/io.v +++ b/vlib/net/websocket/io.v @@ -10,7 +10,7 @@ fn (mut ws Client) socket_read(mut buffer []u8) ?int { return error('socket_read: trying to read a closed socket') } if ws.is_ssl { - r := ws.ssl_conn.read(mut buffer) ? + r := ws.ssl_conn.read(mut buffer)? return r } else { for { @@ -34,7 +34,7 @@ fn (mut ws Client) socket_read_ptr(buf_ptr &u8, len int) ?int { return error('socket_read_ptr: trying to read a closed socket') } if ws.is_ssl { - r := ws.ssl_conn.socket_read_into_ptr(buf_ptr, len) ? + r := ws.ssl_conn.socket_read_into_ptr(buf_ptr, len)? return r } else { for { @@ -79,22 +79,22 @@ fn (mut ws Client) socket_write(bytes []u8) ?int { fn (mut ws Client) shutdown_socket() ? { ws.debug_log('shutting down socket') if ws.is_ssl { - ws.ssl_conn.shutdown() ? + ws.ssl_conn.shutdown()? } else { - ws.conn.close() ? + ws.conn.close()? } } // dial_socket connects tcp socket and initializes default configurations fn (mut ws Client) dial_socket() ?&net.TcpConn { tcp_address := '$ws.uri.hostname:$ws.uri.port' - mut t := net.dial_tcp(tcp_address) ? + mut t := net.dial_tcp(tcp_address)? optval := int(1) - t.sock.set_option_int(.keep_alive, optval) ? + t.sock.set_option_int(.keep_alive, optval)? t.set_read_timeout(30 * time.second) t.set_write_timeout(30 * time.second) if ws.is_ssl { - ws.ssl_conn.connect(mut t, ws.uri.hostname) ? + ws.ssl_conn.connect(mut t, ws.uri.hostname)? } return t } diff --git a/vlib/net/websocket/message.v b/vlib/net/websocket/message.v index 420effe2fe..1fce6d4f89 100644 --- a/vlib/net/websocket/message.v +++ b/vlib/net/websocket/message.v @@ -39,33 +39,33 @@ const ( // validate_client validates client frame rules from RFC6455 pub fn (mut ws Client) validate_frame(frame &Frame) ? { if frame.rsv1 || frame.rsv2 || frame.rsv3 { - ws.close(1002, 'rsv cannot be other than 0, not negotiated') ? + ws.close(1002, 'rsv cannot be other than 0, not negotiated')? return error('rsv cannot be other than 0, not negotiated') } if (int(frame.opcode) >= 3 && int(frame.opcode) <= 7) || (int(frame.opcode) >= 11 && int(frame.opcode) <= 15) { - ws.close(1002, 'use of reserved opcode') ? + ws.close(1002, 'use of reserved opcode')? return error('use of reserved opcode') } if frame.has_mask && !ws.is_server { // server should never send masked frames // to client, close connection - ws.close(1002, 'client got masked frame') ? + ws.close(1002, 'client got masked frame')? return error('client sent masked frame') } if is_control_frame(frame.opcode) { if !frame.fin { - ws.close(1002, 'control message must not be fragmented') ? + ws.close(1002, 'control message must not be fragmented')? return error('unexpected control frame with no fin') } if frame.payload_len > 125 { - ws.close(1002, 'control frames must not exceed 125 bytes') ? + ws.close(1002, 'control frames must not exceed 125 bytes')? return error('unexpected control frame payload length') } } if frame.fin == false && ws.fragments.len == 0 && frame.opcode == .continuation { err_msg := 'unexecpected continuation, there are no frames to continue, $frame' - ws.close(1002, err_msg) ? + ws.close(1002, err_msg)? return error(err_msg) } } @@ -89,7 +89,7 @@ fn (mut ws Client) read_payload(frame &Frame) ?[]u8 { mut read_buf := [1]u8{} mut bytes_read := 0 for bytes_read < frame.payload_len { - len := ws.socket_read_ptr(&read_buf[0], 1) ? + len := ws.socket_read_ptr(&read_buf[0], 1)? if len != 1 { return error('expected read all message, got zero') } @@ -113,7 +113,7 @@ fn (mut ws Client) validate_utf_8(opcode OPCode, payload []u8) ? { if opcode in [.text_frame, .close] && !utf8.validate(payload.data, payload.len) { ws.logger.error('malformed utf8 payload, payload len: ($payload.len)') ws.send_error_event('Recieved malformed utf8.') - ws.close(1007, 'malformed utf8 payload') ? + ws.close(1007, 'malformed utf8 payload')? return error('malformed utf8 payload') } } @@ -121,9 +121,9 @@ fn (mut ws Client) validate_utf_8(opcode OPCode, payload []u8) ? { // read_next_message reads 1 to n frames to compose a message pub fn (mut ws Client) read_next_message() ?Message { for { - frame := ws.parse_frame_header() ? - ws.validate_frame(&frame) ? - frame_payload := ws.read_payload(&frame) ? + frame := ws.parse_frame_header()? + ws.validate_frame(&frame)? + frame_payload := ws.read_payload(&frame)? if is_control_frame(frame.opcode) { // Control frames can interject other frames // and need to be returned immediately @@ -161,12 +161,12 @@ pub fn (mut ws Client) read_next_message() ?Message { ws.fragments = [] } if is_data_frame(frame.opcode) { - ws.close(0, '') ? + ws.close(0, '')? return error('Unexpected frame opcode') } - payload := ws.payload_from_fragments(frame_payload) ? + payload := ws.payload_from_fragments(frame_payload)? opcode := ws.opcode_from_fragments() - ws.validate_utf_8(opcode, payload) ? + ws.validate_utf_8(opcode, payload)? msg := Message{ opcode: opcode payload: payload.clone() @@ -215,7 +215,7 @@ pub fn (mut ws Client) parse_frame_header() ?Frame { mut rbuff := [1]u8{} mut mask_end_byte := 0 for ws.state == .open { - read_bytes := ws.socket_read_ptr(&rbuff[0], 1) ? + read_bytes := ws.socket_read_ptr(&rbuff[0], 1)? if read_bytes == 0 { // this is probably a timeout or close continue diff --git a/vlib/net/websocket/tests/autobahn/autobahn_client.v b/vlib/net/websocket/tests/autobahn/autobahn_client.v index c65fdab7be..d449bbebf0 100644 --- a/vlib/net/websocket/tests/autobahn/autobahn_client.v +++ b/vlib/net/websocket/tests/autobahn/autobahn_client.v @@ -10,17 +10,17 @@ fn main() { } // update the reports uri := 'ws://autobahn_server:9001/updateReports?agent=v-client' - mut ws := websocket.new_client(uri) ? - ws.connect() ? - ws.listen() ? + mut ws := websocket.new_client(uri)? + ws.connect()? + ws.listen()? } fn handle_case(case_nr int) ? { uri := 'ws://autobahn_server:9001/runCase?case=$case_nr&agent=v-client' - mut ws := websocket.new_client(uri) ? + mut ws := websocket.new_client(uri)? ws.on_message(on_message) - ws.connect() ? - ws.listen() ? + ws.connect()? + ws.listen()? } fn on_message(mut ws websocket.Client, msg &websocket.Message) ? { diff --git a/vlib/net/websocket/tests/autobahn/autobahn_client_wss.v b/vlib/net/websocket/tests/autobahn/autobahn_client_wss.v index c7a3c25aee..1cf17820f2 100644 --- a/vlib/net/websocket/tests/autobahn/autobahn_client_wss.v +++ b/vlib/net/websocket/tests/autobahn/autobahn_client_wss.v @@ -11,18 +11,18 @@ fn main() { // update the reports // uri := 'wss://localhost:9002/updateReports?agent=v-client' uri := 'wss://autobahn_server_wss:9002/updateReports?agent=v-client' - mut ws := websocket.new_client(uri) ? - ws.connect() ? - ws.listen() ? + mut ws := websocket.new_client(uri)? + ws.connect()? + ws.listen()? } fn handle_case(case_nr int) ? { uri := 'wss://autobahn_server_wss:9002/runCase?case=$case_nr&agent=v-client' // uri := 'wss://localhost:9002/runCase?case=$case_nr&agent=v-client' - mut ws := websocket.new_client(uri) ? + mut ws := websocket.new_client(uri)? ws.on_message(on_message) - ws.connect() ? - ws.listen() ? + ws.connect()? + ws.listen()? } fn on_message(mut ws websocket.Client, msg &websocket.Message) ? { diff --git a/vlib/net/websocket/tests/autobahn/autobahn_server.v b/vlib/net/websocket/tests/autobahn/autobahn_server.v index 0493ca99e6..3dfded7d89 100644 --- a/vlib/net/websocket/tests/autobahn/autobahn_server.v +++ b/vlib/net/websocket/tests/autobahn/autobahn_server.v @@ -11,10 +11,10 @@ fn main() { fn handle_case(case_nr int) ? { uri := 'ws://localhost:9002/runCase?case=$case_nr&agent=v-client' - mut ws := websocket.new_client(uri) ? + mut ws := websocket.new_client(uri)? ws.on_message(on_message) - ws.connect() ? - ws.listen() ? + ws.connect()? + ws.listen()? } fn on_message(mut ws websocket.Client, msg &websocket.Message) ? { diff --git a/vlib/net/websocket/tests/autobahn/local_run/autobahn_client.v b/vlib/net/websocket/tests/autobahn/local_run/autobahn_client.v index ef5b281ab2..4f7645d027 100644 --- a/vlib/net/websocket/tests/autobahn/local_run/autobahn_client.v +++ b/vlib/net/websocket/tests/autobahn/local_run/autobahn_client.v @@ -10,17 +10,17 @@ fn main() { } // update the reports uri := 'ws://localhost:9001/updateReports?agent=v-client' - mut ws := websocket.new_client(uri) ? - ws.connect() ? - ws.listen() ? + mut ws := websocket.new_client(uri)? + ws.connect()? + ws.listen()? } fn handle_case(case_nr int) ? { uri := 'ws://localhost:9001/runCase?case=$case_nr&agent=v-client' - mut ws := websocket.new_client(uri) ? + mut ws := websocket.new_client(uri)? ws.on_message(on_message) - ws.connect() ? - ws.listen() ? + ws.connect()? + ws.listen()? } fn on_message(mut ws websocket.Client, msg &websocket.Message) ? { diff --git a/vlib/net/websocket/tests/autobahn/local_run/autobahn_client_wss.v b/vlib/net/websocket/tests/autobahn/local_run/autobahn_client_wss.v index c7a3c25aee..1cf17820f2 100644 --- a/vlib/net/websocket/tests/autobahn/local_run/autobahn_client_wss.v +++ b/vlib/net/websocket/tests/autobahn/local_run/autobahn_client_wss.v @@ -11,18 +11,18 @@ fn main() { // update the reports // uri := 'wss://localhost:9002/updateReports?agent=v-client' uri := 'wss://autobahn_server_wss:9002/updateReports?agent=v-client' - mut ws := websocket.new_client(uri) ? - ws.connect() ? - ws.listen() ? + mut ws := websocket.new_client(uri)? + ws.connect()? + ws.listen()? } fn handle_case(case_nr int) ? { uri := 'wss://autobahn_server_wss:9002/runCase?case=$case_nr&agent=v-client' // uri := 'wss://localhost:9002/runCase?case=$case_nr&agent=v-client' - mut ws := websocket.new_client(uri) ? + mut ws := websocket.new_client(uri)? ws.on_message(on_message) - ws.connect() ? - ws.listen() ? + ws.connect()? + ws.listen()? } fn on_message(mut ws websocket.Client, msg &websocket.Message) ? { diff --git a/vlib/net/websocket/websocket_client.v b/vlib/net/websocket/websocket_client.v index be216b0f1f..95aa4a2ce5 100644 --- a/vlib/net/websocket/websocket_client.v +++ b/vlib/net/websocket/websocket_client.v @@ -75,7 +75,7 @@ pub enum OPCode { // new_client instance a new websocket client pub fn new_client(address string) ?&Client { - uri := parse_uri(address) ? + uri := parse_uri(address)? return &Client{ conn: 0 is_server: false @@ -93,14 +93,14 @@ pub fn new_client(address string) ?&Client { // connect connects to remote websocket server pub fn (mut ws Client) connect() ? { - ws.assert_not_connected() ? + ws.assert_not_connected()? ws.set_state(.connecting) ws.logger.info('connecting to host $ws.uri') - ws.conn = ws.dial_socket() ? + ws.conn = ws.dial_socket()? // Todo: make setting configurable ws.conn.set_read_timeout(time.second * 30) ws.conn.set_write_timeout(time.second * 30) - ws.handshake() ? + ws.handshake()? ws.set_state(.open) ws.logger.info('successfully connected to host $ws.uri') ws.send_open_event() @@ -174,30 +174,30 @@ pub fn (mut ws Client) listen() ? { } if msg.payload.len > 0 { if msg.payload.len == 1 { - ws.close(1002, 'close payload cannot be 1 byte') ? + ws.close(1002, 'close payload cannot be 1 byte')? return error('close payload cannot be 1 byte') } code := u16(msg.payload[0]) << 8 | u16(msg.payload[1]) if code in invalid_close_codes { - ws.close(1002, 'invalid close code: $code') ? + ws.close(1002, 'invalid close code: $code')? return error('invalid close code: $code') } reason := if msg.payload.len > 2 { msg.payload[2..] } else { []u8{} } if reason.len > 0 { - ws.validate_utf_8(.close, reason) ? + ws.validate_utf_8(.close, reason)? } if ws.state !in [.closing, .closed] { // sending close back according to spec ws.debug_log('close with reason, code: $code, reason: $reason') r := reason.bytestr() - ws.close(code, r) ? + ws.close(code, r)? } unsafe { msg.free() } } else { if ws.state !in [.closing, .closed] { ws.debug_log('close with reason, no code') // sending close back according to spec - ws.close(1000, 'normal') ? + ws.close(1000, 'normal')? } unsafe { msg.free() } } @@ -206,7 +206,7 @@ pub fn (mut ws Client) listen() ? { .continuation { ws.logger.error('unexpected opcode continuation, nothing to continue') ws.send_error_event('unexpected opcode continuation, nothing to continue') - ws.close(1002, 'nothing to continue') ? + ws.close(1002, 'nothing to continue')? return error('unexpected opcode continuation, nothing to continue') } } @@ -220,12 +220,12 @@ fn (mut ws Client) manage_clean_close() { // ping sends ping message to server pub fn (mut ws Client) ping() ? { - ws.send_control_frame(.ping, 'PING', []) ? + ws.send_control_frame(.ping, 'PING', [])? } // pong sends pong message to server, pub fn (mut ws Client) pong() ? { - ws.send_control_frame(.pong, 'PONG', []) ? + ws.send_control_frame(.pong, 'PONG', [])? } // write_ptr writes len bytes provided a byteptr with a websocket messagetype @@ -279,7 +279,7 @@ pub fn (mut ws Client) write_ptr(bytes &u8, payload_len int, code OPCode) ?int { header[12] = masking_key[2] header[13] = masking_key[3] } else { - ws.close(1009, 'frame too large') ? + ws.close(1009, 'frame too large')? return error('frame too large') } } @@ -296,7 +296,7 @@ pub fn (mut ws Client) write_ptr(bytes &u8, payload_len int, code OPCode) ?int { frame_buf[header_len + i] ^= masking_key[i % 4] & 0xff } } - written_len := ws.socket_write(frame_buf) ? + written_len := ws.socket_write(frame_buf)? unsafe { frame_buf.free() masking_key.free() @@ -339,10 +339,10 @@ pub fn (mut ws Client) close(code int, message string) ? { for i in 0 .. message.len { close_frame[i + 2] = message[i] } - ws.send_control_frame(.close, 'CLOSE', close_frame) ? + ws.send_control_frame(.close, 'CLOSE', close_frame)? unsafe { close_frame.free() } } else { - ws.send_control_frame(.close, 'CLOSE', []) ? + ws.send_control_frame(.close, 'CLOSE', [])? } ws.fragments = [] } @@ -409,7 +409,7 @@ fn (mut ws Client) send_control_frame(code OPCode, frame_typ string, payload []u // parse_uri parses the url to a Uri fn parse_uri(url string) ?&Uri { - u := urllib.parse(url) ? + u := urllib.parse(url)? request_uri := u.request_uri() v := request_uri.split('?') mut port := u.port() diff --git a/vlib/net/websocket/websocket_server.v b/vlib/net/websocket/websocket_server.v index f241e4575f..baa34cb641 100644 --- a/vlib/net/websocket/websocket_server.v +++ b/vlib/net/websocket/websocket_server.v @@ -55,7 +55,7 @@ pub fn (mut s Server) set_ping_interval(seconds int) { // listen start listen and process to incoming connections from websocket clients pub fn (mut s Server) listen() ? { s.logger.info('websocket server: start listen on port $s.port') - s.ls = net.listen_tcp(s.family, ':$s.port') ? + s.ls = net.listen_tcp(s.family, ':$s.port')? s.set_state(.open) go s.handle_ping() for { @@ -108,15 +108,15 @@ fn (mut s Server) serve_client(mut c Client) ? { defer { c.logger.debug('server-> End serve client ($c.id)') } - mut handshake_response, mut server_client := s.handle_server_handshake(mut c) ? - accept := s.send_connect_event(mut server_client) ? + mut handshake_response, mut server_client := s.handle_server_handshake(mut c)? + accept := s.send_connect_event(mut server_client)? if !accept { s.logger.debug('server-> client not accepted') - c.shutdown_socket() ? + c.shutdown_socket()? return } // the client is accepted - c.socket_write(handshake_response.bytes()) ? + c.socket_write(handshake_response.bytes())? lock { s.clients[server_client.client.id] = server_client } @@ -158,7 +158,7 @@ fn (mut s Server) setup_callbacks(mut sc ServerClient) { // accept_new_client creates a new client instance for client that connects to the socket fn (mut s Server) accept_new_client() ?&Client { - mut new_conn := s.ls.accept() ? + mut new_conn := s.ls.accept()? c := &Client{ is_server: true conn: new_conn diff --git a/vlib/net/websocket/websocket_test.v b/vlib/net/websocket/websocket_test.v index 88401a8f0a..a082d8bc9e 100644 --- a/vlib/net/websocket/websocket_test.v +++ b/vlib/net/websocket/websocket_test.v @@ -51,7 +51,7 @@ fn start_server(family net.AddrFamily, listen_port int) ? { return false } return true - }) ? + })? s.on_message(fn (mut ws websocket.Client, msg &websocket.Message) ? { match msg.opcode { .pong { ws.write_string('pong') or { panic(err) } } @@ -70,9 +70,9 @@ fn ws_test(family net.AddrFamily, uri string) ? { eprintln('connecting to $uri ...') mut test_results := WebsocketTestResults{} - mut ws := websocket.new_client(uri) ? + mut ws := websocket.new_client(uri)? ws.on_open(fn (mut ws websocket.Client) ? { - ws.pong() ? + ws.pong()? assert true }) ws.on_error(fn (mut ws websocket.Client, err string) ? { diff --git a/vlib/orm/orm.v b/vlib/orm/orm.v index 77823e823d..baad8adb54 100644 --- a/vlib/orm/orm.v +++ b/vlib/orm/orm.v @@ -363,7 +363,7 @@ pub fn orm_table_gen(table string, para string, defaults bool, def_unique_len in mut stmt := '' mut ctyp := sql_from_v(sql_field_type(field)) or { field_name = '${field_name}_id' - sql_from_v(7) ? + sql_from_v(7)? } if ctyp == '' { return error('Unknown type ($field.typ) for field $field.name in struct $table') diff --git a/vlib/os/file.c.v b/vlib/os/file.c.v index b27a4bd0c1..8779751c2a 100644 --- a/vlib/os/file.c.v +++ b/vlib/os/file.c.v @@ -90,7 +90,7 @@ pub fn open(path string) ?File { } } */ - cfile := vfopen(path, 'rb') ? + cfile := vfopen(path, 'rb')? fd := fileno(cfile) return File{ cfile: cfile @@ -124,7 +124,7 @@ pub fn create(path string) ?File { } } */ - cfile := vfopen(path, 'wb') ? + cfile := vfopen(path, 'wb')? fd := fileno(cfile) return File{ cfile: cfile @@ -165,7 +165,7 @@ pub fn (f &File) read(mut buf []u8) ?int { if buf.len == 0 { return 0 } - nbytes := fread(buf.data, 1, buf.len, f.cfile) ? + nbytes := fread(buf.data, 1, buf.len, f.cfile)? return nbytes } @@ -221,7 +221,7 @@ pub fn (mut f File) writeln(s string) ?int { // write_string writes the string `s` into the file // It returns how many bytes were actually written. pub fn (mut f File) write_string(s string) ?int { - unsafe { f.write_full_buffer(s.str, usize(s.len)) ? } + unsafe { f.write_full_buffer(s.str, usize(s.len))? } return s.len } @@ -415,14 +415,14 @@ pub fn (f &File) read_bytes_into(pos u64, mut buf []u8) ?int { $if windows { // Note: fseek errors if pos == os.file_size, which we accept C._fseeki64(f.cfile, pos, C.SEEK_SET) - nbytes := fread(buf.data, 1, buf.len, f.cfile) ? + nbytes := fread(buf.data, 1, buf.len, f.cfile)? $if debug { C._fseeki64(f.cfile, 0, C.SEEK_SET) } return nbytes } $else { C.fseeko(f.cfile, pos, C.SEEK_SET) - nbytes := fread(buf.data, 1, buf.len, f.cfile) ? + nbytes := fread(buf.data, 1, buf.len, f.cfile)? $if debug { C.fseeko(f.cfile, 0, C.SEEK_SET) } @@ -431,7 +431,7 @@ pub fn (f &File) read_bytes_into(pos u64, mut buf []u8) ?int { } $if x32 { C.fseek(f.cfile, pos, C.SEEK_SET) - nbytes := fread(buf.data, 1, buf.len, f.cfile) ? + nbytes := fread(buf.data, 1, buf.len, f.cfile)? $if debug { C.fseek(f.cfile, 0, C.SEEK_SET) } @@ -452,12 +452,12 @@ pub fn (f &File) read_from(pos u64, mut buf []u8) ?int { C.fseeko(f.cfile, pos, C.SEEK_SET) } - nbytes := fread(buf.data, 1, buf.len, f.cfile) ? + nbytes := fread(buf.data, 1, buf.len, f.cfile)? return nbytes } $if x32 { C.fseek(f.cfile, pos, C.SEEK_SET) - nbytes := fread(buf.data, 1, buf.len, f.cfile) ? + nbytes := fread(buf.data, 1, buf.len, f.cfile)? return nbytes } return error('Could not read file') @@ -511,7 +511,7 @@ pub fn (mut f File) read_struct(mut t T) ? { if tsize == 0 { return error_size_of_type_0() } - nbytes := fread(t, 1, tsize, f.cfile) ? + nbytes := fread(t, 1, tsize, f.cfile)? if nbytes != tsize { return error_with_code('incomplete struct read', nbytes) } @@ -530,17 +530,17 @@ pub fn (mut f File) read_struct_at(mut t T, pos u64) ? { $if x64 { $if windows { C._fseeki64(f.cfile, pos, C.SEEK_SET) - nbytes = fread(t, 1, tsize, f.cfile) ? + nbytes = fread(t, 1, tsize, f.cfile)? C._fseeki64(f.cfile, 0, C.SEEK_END) } $else { C.fseeko(f.cfile, pos, C.SEEK_SET) - nbytes = fread(t, 1, tsize, f.cfile) ? + nbytes = fread(t, 1, tsize, f.cfile)? C.fseeko(f.cfile, 0, C.SEEK_END) } } $if x32 { C.fseek(f.cfile, pos, C.SEEK_SET) - nbytes = fread(t, 1, tsize, f.cfile) ? + nbytes = fread(t, 1, tsize, f.cfile)? C.fseek(f.cfile, 0, C.SEEK_END) } if nbytes != tsize { @@ -558,7 +558,7 @@ pub fn (mut f File) read_raw() ?T { return error_size_of_type_0() } mut t := T{} - nbytes := fread(&t, 1, tsize, f.cfile) ? + nbytes := fread(&t, 1, tsize, f.cfile)? if nbytes != tsize { return error_with_code('incomplete struct read', nbytes) } @@ -581,7 +581,7 @@ pub fn (mut f File) read_raw_at(pos u64) ?T { if C._fseeki64(f.cfile, pos, C.SEEK_SET) != 0 { return error(posix_get_error_msg(C.errno)) } - nbytes = fread(&t, 1, tsize, f.cfile) ? + nbytes = fread(&t, 1, tsize, f.cfile)? if C._fseeki64(f.cfile, 0, C.SEEK_END) != 0 { return error(posix_get_error_msg(C.errno)) } @@ -589,7 +589,7 @@ pub fn (mut f File) read_raw_at(pos u64) ?T { if C.fseeko(f.cfile, pos, C.SEEK_SET) != 0 { return error(posix_get_error_msg(C.errno)) } - nbytes = fread(&t, 1, tsize, f.cfile) ? + nbytes = fread(&t, 1, tsize, f.cfile)? if C.fseeko(f.cfile, 0, C.SEEK_END) != 0 { return error(posix_get_error_msg(C.errno)) } @@ -599,7 +599,7 @@ pub fn (mut f File) read_raw_at(pos u64) ?T { if C.fseek(f.cfile, pos, C.SEEK_SET) != 0 { return error(posix_get_error_msg(C.errno)) } - nbytes = fread(&t, 1, tsize, f.cfile) ? + nbytes = fread(&t, 1, tsize, f.cfile)? if C.fseek(f.cfile, 0, C.SEEK_END) != 0 { return error(posix_get_error_msg(C.errno)) } diff --git a/vlib/os/file.js.v b/vlib/os/file.js.v index be9433c678..72affb737a 100644 --- a/vlib/os/file.js.v +++ b/vlib/os/file.js.v @@ -48,12 +48,12 @@ pub fn open_file(path string, mode string, options ...int) ?File { // open tries to open a file for reading and returns back a read-only `File` object. pub fn open(path string) ?File { - f := open_file(path, 'r') ? + f := open_file(path, 'r')? return f } pub fn create(path string) ?File { - f := open_file(path, 'w') ? + f := open_file(path, 'w')? return f } @@ -108,8 +108,8 @@ pub fn (mut f File) write(buf []u8) ?int { // writeln writes the string `s` into the file, and appends a \n character. // It returns how many bytes were written, including the \n character. pub fn (mut f File) writeln(s string) ?int { - mut nbytes := f.write(s.bytes()) ? - nbytes += f.write('\n'.bytes()) ? + mut nbytes := f.write(s.bytes())? + nbytes += f.write('\n'.bytes())? return nbytes } @@ -128,7 +128,7 @@ pub fn (mut f File) write_to(pos u64, buf []u8) ?int { // write_string writes the string `s` into the file // It returns how many bytes were actually written. pub fn (mut f File) write_string(s string) ?int { - nbytes := f.write(s.bytes()) ? + nbytes := f.write(s.bytes())? return nbytes } diff --git a/vlib/os/file_test.v b/vlib/os/file_test.v index b9ddac395d..ddfb9ace65 100644 --- a/vlib/os/file_test.v +++ b/vlib/os/file_test.v @@ -48,14 +48,14 @@ const ( fn testsuite_begin() ? { os.rmdir_all(tfolder) or {} assert !os.is_dir(tfolder) - os.mkdir_all(tfolder) ? - os.chdir(tfolder) ? + os.mkdir_all(tfolder)? + os.chdir(tfolder)? assert os.is_dir(tfolder) } fn testsuite_end() ? { - os.chdir(os.wd_at_startup) ? - os.rmdir_all(tfolder) ? + os.chdir(os.wd_at_startup)? + os.rmdir_all(tfolder)? assert !os.is_dir(tfolder) } @@ -64,23 +64,23 @@ fn testsuite_end() ? { // returning on each newline, even before the buffer is full, and reaching EOF before // the buffer is completely filled. fn test_read_bytes_into_newline_text() ? { - mut f := os.open_file(tfile, 'w') ? - f.write_string('Hello World!\nGood\r morning.') ? + mut f := os.open_file(tfile, 'w')? + f.write_string('Hello World!\nGood\r morning.')? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut buf := []u8{len: 8} - n0 := f.read_bytes_into_newline(mut buf) ? + n0 := f.read_bytes_into_newline(mut buf)? assert n0 == 8 - n1 := f.read_bytes_into_newline(mut buf) ? + n1 := f.read_bytes_into_newline(mut buf)? assert n1 == 5 - n2 := f.read_bytes_into_newline(mut buf) ? + n2 := f.read_bytes_into_newline(mut buf)? assert n2 == 8 - n3 := f.read_bytes_into_newline(mut buf) ? + n3 := f.read_bytes_into_newline(mut buf)? assert n3 == 6 f.close() @@ -99,22 +99,22 @@ fn test_read_bytes_into_newline_binary() ? { n1_bytes := bw[10..13] n2_bytes := bw[13..] - mut f := os.open_file(tfile, 'w') ? - f.write(bw) ? + mut f := os.open_file(tfile, 'w')? + f.write(bw)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut buf := []u8{len: 10} - n0 := f.read_bytes_into_newline(mut buf) ? + n0 := f.read_bytes_into_newline(mut buf)? assert n0 == 10 assert buf[..n0] == n0_bytes - n1 := f.read_bytes_into_newline(mut buf) ? + n1 := f.read_bytes_into_newline(mut buf)? assert n1 == 3 assert buf[..n1] == n1_bytes - n2 := f.read_bytes_into_newline(mut buf) ? + n2 := f.read_bytes_into_newline(mut buf)? assert n2 == 2 assert buf[..n2] == n2_bytes f.close() @@ -125,19 +125,19 @@ fn test_read_bytes_into_newline_binary() ? { // test simulates file reading where the end-of-file is reached inside an fread // containing data. fn test_read_eof_last_read_partial_buffer_fill() ? { - mut f := os.open_file(tfile, 'w') ? + mut f := os.open_file(tfile, 'w')? bw := []u8{len: 199, init: 5} - f.write(bw) ? + f.write(bw)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut br := []u8{len: 100} // Read first 100 bytes of 199 byte file, should fill buffer with no error. - n0 := f.read(mut br) ? + n0 := f.read(mut br)? assert n0 == 100 // Read remaining 99 bytes of 199 byte file, should fill buffer with no // error, even though end-of-file was reached. - n1 := f.read(mut br) ? + n1 := f.read(mut br)? assert n1 == 99 // Read again, end-of-file was previously reached so should return none // error. @@ -157,19 +157,19 @@ fn test_read_eof_last_read_partial_buffer_fill() ? { // simulates file reading where the end-of-file is reached at the beinning of an // fread that returns no data. fn test_read_eof_last_read_full_buffer_fill() ? { - mut f := os.open_file(tfile, 'w') ? + mut f := os.open_file(tfile, 'w')? bw := []u8{len: 200, init: 5} - f.write(bw) ? + f.write(bw)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut br := []u8{len: 100} // Read first 100 bytes of 200 byte file, should fill buffer with no error. - n0 := f.read(mut br) ? + n0 := f.read(mut br)? assert n0 == 100 // Read remaining 100 bytes of 200 byte file, should fill buffer with no // error. The end-of-file isn't reached yet, but there is no more data. - n1 := f.read(mut br) ? + n1 := f.read(mut br)? assert n1 == 100 // Read again, end-of-file was previously reached so should return none // error. @@ -187,10 +187,10 @@ fn test_read_eof_last_read_full_buffer_fill() ? { fn test_write_struct() ? { os.rm(tfile) or {} // FIXME This is a workaround for macos, because the file isn't truncated when open with 'w' size_of_point := int(sizeof(Point)) - mut f := os.open_file(tfile, 'w') ? - f.write_struct(another_point) ? + mut f := os.open_file(tfile, 'w')? + f.write_struct(another_point)? f.close() - x := os.read_file(tfile) ? + x := os.read_file(tfile)? pcopy := unsafe { &u8(memdup(&another_point, size_of_point)) } y := unsafe { pcopy.vstring_with_len(size_of_point) } assert x == y @@ -201,39 +201,39 @@ fn test_write_struct() ? { } fn test_write_struct_at() ? { - mut f := os.open_file(tfile, 'w') ? - f.write_struct(extended_point) ? - f.write_struct_at(another_point, 3) ? + mut f := os.open_file(tfile, 'w')? + f.write_struct(extended_point)? + f.write_struct_at(another_point, 3)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut p := Point{} - f.read_struct_at(mut p, 3) ? + f.read_struct_at(mut p, 3)? f.close() assert p == another_point } fn test_read_struct() ? { - mut f := os.open_file(tfile, 'w') ? - f.write_struct(another_point) ? + mut f := os.open_file(tfile, 'w')? + f.write_struct(another_point)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut p := Point{} - f.read_struct(mut p) ? + f.read_struct(mut p)? f.close() assert p == another_point } fn test_read_struct_at() ? { - mut f := os.open_file(tfile, 'w') ? - f.write([u8(1), 2, 3]) ? - f.write_struct(another_point) ? + mut f := os.open_file(tfile, 'w')? + f.write([u8(1), 2, 3])? + f.write_struct(another_point)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut p := Point{} - f.read_struct_at(mut p, 3) ? + f.read_struct_at(mut p, 3)? f.close() assert p == another_point @@ -242,10 +242,10 @@ fn test_read_struct_at() ? { fn test_write_raw() ? { os.rm(tfile) or {} // FIXME This is a workaround for macos, because the file isn't truncated when open with 'w' size_of_point := int(sizeof(Point)) - mut f := os.open_file(tfile, 'w') ? - f.write_raw(another_point) ? + mut f := os.open_file(tfile, 'w')? + f.write_raw(another_point)? f.close() - x := os.read_file(tfile) ? + x := os.read_file(tfile)? pcopy := unsafe { &u8(memdup(&another_point, size_of_point)) } y := unsafe { pcopy.vstring_with_len(size_of_point) } assert x == y @@ -256,20 +256,20 @@ fn test_write_raw() ? { } fn test_write_raw_at() ? { - mut f := os.open_file(tfile, 'w') ? - f.write_raw(extended_point) ? - f.write_raw_at(another_point, 3) ? + mut f := os.open_file(tfile, 'w')? + f.write_raw(extended_point)? + f.write_raw_at(another_point, 3)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut p := Point{} - f.read_struct_at(mut p, 3) ? + f.read_struct_at(mut p, 3)? f.close() assert p == another_point } fn test_write_raw_at_negative_pos() ? { - mut f := os.open_file(tfile, 'w') ? + mut f := os.open_file(tfile, 'w')? if _ := f.write_raw_at(another_point, -1) { assert false } @@ -278,17 +278,17 @@ fn test_write_raw_at_negative_pos() ? { } fn test_read_raw() ? { - mut f := os.open_file(tfile, 'w') ? - f.write_raw(another_point) ? - f.write_raw(another_byte) ? - f.write_raw(another_color) ? - f.write_raw(another_permission) ? + mut f := os.open_file(tfile, 'w')? + f.write_raw(another_point)? + f.write_raw(another_byte)? + f.write_raw(another_color)? + f.write_raw(another_permission)? f.close() - f = os.open_file(tfile, 'r') ? - p := f.read_raw() ? - b := f.read_raw() ? - c := f.read_raw() ? - x := f.read_raw() ? + f = os.open_file(tfile, 'r')? + p := f.read_raw()? + b := f.read_raw()? + c := f.read_raw()? + x := f.read_raw()? f.close() assert p == another_point @@ -298,22 +298,22 @@ fn test_read_raw() ? { } fn test_read_raw_at() ? { - mut f := os.open_file(tfile, 'w') ? - f.write([u8(1), 2, 3]) ? - f.write_raw(another_point) ? - f.write_raw(another_byte) ? - f.write_raw(another_color) ? - f.write_raw(another_permission) ? + mut f := os.open_file(tfile, 'w')? + f.write([u8(1), 2, 3])? + f.write_raw(another_point)? + f.write_raw(another_byte)? + f.write_raw(another_color)? + f.write_raw(another_permission)? f.close() - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? mut at := u64(3) - p := f.read_raw_at(at) ? + p := f.read_raw_at(at)? at += sizeof(Point) - b := f.read_raw_at(at) ? + b := f.read_raw_at(at)? at += sizeof(u8) - c := f.read_raw_at(at) ? + c := f.read_raw_at(at)? at += sizeof(Color) - x := f.read_raw_at(at) ? + x := f.read_raw_at(at)? at += sizeof(Permissions) f.close() @@ -324,7 +324,7 @@ fn test_read_raw_at() ? { } fn test_read_raw_at_negative_pos() ? { - mut f := os.open_file(tfile, 'r') ? + mut f := os.open_file(tfile, 'r')? if _ := f.read_raw_at(-1) { assert false } @@ -333,23 +333,23 @@ fn test_read_raw_at_negative_pos() ? { } fn test_seek() ? { - mut f := os.open_file(tfile, 'w') ? - f.write_raw(another_point) ? - f.write_raw(another_byte) ? - f.write_raw(another_color) ? - f.write_raw(another_permission) ? + mut f := os.open_file(tfile, 'w')? + f.write_raw(another_point)? + f.write_raw(another_byte)? + f.write_raw(another_color)? + f.write_raw(another_permission)? f.close() // println('> ${sizeof(Point)} ${sizeof(byte)} ${sizeof(Color)} ${sizeof(Permissions)}') - f = os.open_file(tfile, 'r') ? + f = os.open_file(tfile, 'r')? // - f.seek(i64(sizeof(Point)), .start) ? - assert f.tell() ? == sizeof(Point) - b := f.read_raw() ? + f.seek(i64(sizeof(Point)), .start)? + assert f.tell()? == sizeof(Point) + b := f.read_raw()? assert b == another_byte - f.seek(i64(sizeof(Color)), .current) ? - x := f.read_raw() ? + f.seek(i64(sizeof(Color)), .current)? + x := f.read_raw()? assert x == another_permission // f.close() @@ -358,13 +358,13 @@ fn test_seek() ? { fn test_tell() ? { for size in 10 .. 30 { s := 'x'.repeat(size) - os.write_file(tfile, s) ? + os.write_file(tfile, s)? fs := os.file_size(tfile) assert int(fs) == size // - mut f := os.open_file(tfile, 'r') ? - f.seek(-5, .end) ? - pos := f.tell() ? + mut f := os.open_file(tfile, 'r')? + f.seek(-5, .end)? + pos := f.tell()? f.close() // dump(pos) assert pos == size - 5 diff --git a/vlib/os/glob_test.v b/vlib/os/glob_test.v index 889900c63c..e5c813e2c0 100644 --- a/vlib/os/glob_test.v +++ b/vlib/os/glob_test.v @@ -1,7 +1,7 @@ import os fn deep_glob() ? { - os.chdir(@VMODROOT) ? + os.chdir(@VMODROOT)? matches := os.glob('vlib/v/*/*.v') or { panic(err) } assert matches.len > 10 assert 'vlib/v/ast/ast.v' in matches @@ -16,7 +16,7 @@ fn deep_glob() ? { } fn redeep_glob() ? { - os.chdir(@VMODROOT) ? + os.chdir(@VMODROOT)? matches := os.glob('vlib/v/**/*.v') or { panic(err) } assert matches.len > 10 assert 'vlib/v/ast/ast.v' in matches @@ -32,15 +32,15 @@ fn redeep_glob() ? { fn test_glob_can_find_v_files_3_levels_deep() ? { $if !windows { - deep_glob() ? - redeep_glob() ? + deep_glob()? + redeep_glob()? } assert true } fn test_glob_can_find_files_in_current_folder() ? { - os.chdir(@VMODROOT) ? - matches := os.glob('*') ? + os.chdir(@VMODROOT)? + matches := os.glob('*')? assert '.gitignore' in matches assert 'make.bat' in matches assert 'Makefile' in matches @@ -53,8 +53,8 @@ fn test_glob_can_find_files_in_current_folder() ? { } fn test_glob_can_be_used_with_multiple_patterns() ? { - os.chdir(@VMODROOT) ? - matches := os.glob('*', 'cmd/tools/*') ? + os.chdir(@VMODROOT)? + matches := os.glob('*', 'cmd/tools/*')? assert 'README.md' in matches assert 'Makefile' in matches $if !windows { @@ -66,8 +66,8 @@ fn test_glob_can_be_used_with_multiple_patterns() ? { } fn test_glob_star() ? { - os.chdir(@VMODROOT) ? - matches := os.glob('*ake*') ? + os.chdir(@VMODROOT)? + matches := os.glob('*ake*')? assert 'Makefile' in matches assert 'make.bat' in matches } diff --git a/vlib/os/notify/backend_linux.c.v b/vlib/os/notify/backend_linux.c.v index 1913913881..6b07aebdbf 100644 --- a/vlib/os/notify/backend_linux.c.v +++ b/vlib/os/notify/backend_linux.c.v @@ -84,18 +84,18 @@ fn (mut en EpollNotifier) ctl(fd int, op int, mask u32) ? { // add adds a file descriptor to the watch list fn (mut en EpollNotifier) add(fd int, events FdEventType, conf ...FdConfigFlags) ? { mask := flags_to_mask(events, ...conf) - en.ctl(fd, C.EPOLL_CTL_ADD, mask) ? + en.ctl(fd, C.EPOLL_CTL_ADD, mask)? } // modify sets an existing entry in the watch list to the provided events and configuration fn (mut en EpollNotifier) modify(fd int, events FdEventType, conf ...FdConfigFlags) ? { mask := flags_to_mask(events, ...conf) - en.ctl(fd, C.EPOLL_CTL_MOD, mask) ? + en.ctl(fd, C.EPOLL_CTL_MOD, mask)? } // remove removes a file descriptor from the watch list fn (mut en EpollNotifier) remove(fd int) ? { - en.ctl(fd, C.EPOLL_CTL_DEL, 0) ? + en.ctl(fd, C.EPOLL_CTL_DEL, 0)? } // wait waits to be notified of events on the watch list, diff --git a/vlib/os/notify/notify.v b/vlib/os/notify/notify.v index 613e2b4547..8bf3536caf 100644 --- a/vlib/os/notify/notify.v +++ b/vlib/os/notify/notify.v @@ -2,7 +2,7 @@ module notify import time -// Backends should provide a `new() ?FdNotifier` function +// Backends should provide a `new()?FdNotifier` function pub interface FdNotifier { mut: add(fd int, events FdEventType, conf ...FdConfigFlags) ? diff --git a/vlib/os/notify/notify_test.v b/vlib/os/notify/notify_test.v index 3003ff8de7..fb32006d2e 100644 --- a/vlib/os/notify/notify_test.v +++ b/vlib/os/notify/notify_test.v @@ -18,14 +18,14 @@ fn make_pipe() ?(int, int) { fn test_level_trigger() ? { // currently only linux is supported $if linux { - mut notifier := notify.new() ? - reader, writer := make_pipe() ? + mut notifier := notify.new()? + reader, writer := make_pipe()? defer { os.fd_close(reader) os.fd_close(writer) notifier.close() or {} } - notifier.add(reader, .read) ? + notifier.add(reader, .read)? os.fd_write(writer, 'foobar') mut n := ¬ifier @@ -39,14 +39,14 @@ fn test_level_trigger() ? { fn test_edge_trigger() ? { // currently only linux is supported $if linux { - mut notifier := notify.new() ? - reader, writer := make_pipe() ? + mut notifier := notify.new()? + reader, writer := make_pipe()? defer { os.fd_close(reader) os.fd_close(writer) notifier.close() or {} } - notifier.add(reader, .read, .edge_trigger) ? + notifier.add(reader, .read, .edge_trigger)? mut n := ¬ifier @@ -66,14 +66,14 @@ fn test_edge_trigger() ? { fn test_one_shot() ? { $if linux { - mut notifier := notify.new() ? - reader, writer := make_pipe() ? + mut notifier := notify.new()? + reader, writer := make_pipe()? defer { os.fd_close(reader) os.fd_close(writer) notifier.close() or {} } - notifier.add(reader, .read, .one_shot) ? + notifier.add(reader, .read, .one_shot)? mut n := ¬ifier @@ -84,20 +84,20 @@ fn test_one_shot() ? { assert notifier.wait(0).len == 0 // rearm - notifier.modify(reader, .read) ? + notifier.modify(reader, .read)? check_read_event(mut n, reader, 'barbaz') } } fn test_hangup() ? { $if linux { - mut notifier := notify.new() ? - reader, writer := make_pipe() ? + mut notifier := notify.new()? + reader, writer := make_pipe()? defer { os.fd_close(reader) notifier.close() or {} } - notifier.add(reader, .hangup) ? + notifier.add(reader, .hangup)? assert notifier.wait(0).len == 0 @@ -113,18 +113,18 @@ fn test_hangup() ? { fn test_write() ? { $if linux { - mut notifier := notify.new() ? - reader, writer := make_pipe() ? + mut notifier := notify.new()? + reader, writer := make_pipe()? defer { os.fd_close(reader) os.fd_close(writer) notifier.close() or {} } - notifier.add(reader, .write) ? + notifier.add(reader, .write)? assert notifier.wait(0).len == 0 - notifier.add(writer, .write) ? + notifier.add(writer, .write)? events := notifier.wait(0) assert events.len == 1 assert events[0].fd == writer @@ -134,8 +134,8 @@ fn test_write() ? { fn test_remove() ? { $if linux { - mut notifier := notify.new() ? - reader, writer := make_pipe() ? + mut notifier := notify.new()? + reader, writer := make_pipe()? defer { os.fd_close(reader) os.fd_close(writer) @@ -144,12 +144,12 @@ fn test_remove() ? { // level triggered - will keep getting events while // there is data to read - notifier.add(reader, .read) ? + notifier.add(reader, .read)? os.fd_write(writer, 'foobar') assert notifier.wait(0).len == 1 assert notifier.wait(0).len == 1 - notifier.remove(reader) ? + notifier.remove(reader)? assert notifier.wait(0).len == 0 } } diff --git a/vlib/os/open_uri_windows.c.v b/vlib/os/open_uri_windows.c.v index 296c83df1b..ea3e4ebcae 100644 --- a/vlib/os/open_uri_windows.c.v +++ b/vlib/os/open_uri_windows.c.v @@ -13,9 +13,9 @@ pub fn open_uri(uri string) ? { } return } - handle := dl.open_opt('shell32', dl.rtld_now) ? + handle := dl.open_opt('shell32', dl.rtld_now)? // https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutew - func := ShellExecuteWin(dl.sym_opt(handle, 'ShellExecuteW') ?) + func := ShellExecuteWin(dl.sym_opt(handle, 'ShellExecuteW')?) func(C.NULL, 'open'.to_wide(), uri.to_wide(), C.NULL, C.NULL, C.SW_SHOWNORMAL) dl.close(handle) } diff --git a/vlib/os/os.c.v b/vlib/os/os.c.v index 74b86e9ef7..87de130b07 100644 --- a/vlib/os/os.c.v +++ b/vlib/os/os.c.v @@ -40,7 +40,7 @@ fn C._chsize_s(voidptr, u64) int // read_bytes returns all bytes read from file in `path`. [manualfree] pub fn read_bytes(path string) ?[]u8 { - mut fp := vfopen(path, 'rb') ? + mut fp := vfopen(path, 'rb')? defer { C.fclose(fp) } @@ -71,7 +71,7 @@ pub fn read_bytes(path string) ?[]u8 { // read_file reads the file in `path` and returns the contents. pub fn read_file(path string) ?string { mode := 'rb' - mut fp := vfopen(path, mode) ? + mut fp := vfopen(path, mode)? defer { C.fclose(fp) } @@ -1013,15 +1013,15 @@ pub fn is_atty(fd int) int { // write_file_array writes the data in `buffer` to a file in `path`. pub fn write_file_array(path string, buffer array) ? { - mut f := create(path) ? - unsafe { f.write_full_buffer(buffer.data, usize(buffer.len * buffer.element_size)) ? } + mut f := create(path)? + unsafe { f.write_full_buffer(buffer.data, usize(buffer.len * buffer.element_size))? } f.close() } pub fn glob(patterns ...string) ?[]string { mut matches := []string{} for pattern in patterns { - native_glob_pattern(pattern, mut matches) ? + native_glob_pattern(pattern, mut matches)? } matches.sort() return matches diff --git a/vlib/os/os.js.v b/vlib/os/os.js.v index 0ff0faea42..66552b9ab8 100644 --- a/vlib/os/os.js.v +++ b/vlib/os/os.js.v @@ -160,8 +160,8 @@ pub fn glob(patterns ...string) ?[]string { } pub fn write_file_array(path string, buffer array) ? { - mut f := create(path) ? - f.write_array(buffer) ? + mut f := create(path)? + f.write_array(buffer)? f.close() } diff --git a/vlib/os/os.v b/vlib/os/os.v index 3faaaf3c55..c55b34b283 100644 --- a/vlib/os/os.v +++ b/vlib/os/os.v @@ -58,27 +58,27 @@ pub fn cp_all(src string, dst string, overwrite bool) ? { } if exists(adjusted_path) { if overwrite { - rm(adjusted_path) ? + rm(adjusted_path)? } else { return error('Destination file path already exist') } } - cp(source_path, adjusted_path) ? + cp(source_path, adjusted_path)? return } if !exists(dest_path) { - mkdir(dest_path) ? + mkdir(dest_path)? } if !is_dir(dest_path) { return error('Destination path is not a valid directory') } - files := ls(source_path) ? + files := ls(source_path)? for file in files { sp := join_path_single(source_path, file) dp := join_path_single(dest_path, file) if is_dir(sp) { if !exists(dp) { - mkdir(dp) ? + mkdir(dp)? } } cp_all(sp, dp, overwrite) or { @@ -91,14 +91,14 @@ pub fn cp_all(src string, dst string, overwrite bool) ? { // mv_by_cp first copies the source file, and if it is copied successfully, deletes the source file. // may be used when you are not sure that the source and target are on the same mount/partition. pub fn mv_by_cp(source string, target string) ? { - cp(source, target) ? - rm(source) ? + cp(source, target)? + rm(source)? } // read_lines reads the file in `path` into an array of lines. [manualfree] pub fn read_lines(path string) ?[]string { - buf := read_file(path) ? + buf := read_file(path)? res := buf.split_into_lines() unsafe { buf.free() } return res @@ -146,7 +146,7 @@ pub fn sigint_to_signal_name(si int) string { // rmdir_all recursively removes the specified directory. pub fn rmdir_all(path string) ? { mut ret_err := '' - items := ls(path) ? + items := ls(path)? for item in items { fullpath := join_path_single(path, item) if is_dir(fullpath) && !is_link(fullpath) { @@ -371,8 +371,8 @@ pub fn expand_tilde_to_home(path string) string { // write_file writes `text` data to the file in `path`. // If `path` exists, the contents of `path` will be overwritten with the contents of `text`. pub fn write_file(path string, text string) ? { - mut f := create(path) ? - unsafe { f.write_full_buffer(text.str, usize(text.len)) ? } + mut f := create(path)? + unsafe { f.write_full_buffer(text.str, usize(text.len))? } f.close() } diff --git a/vlib/os/os_nix.c.v b/vlib/os/os_nix.c.v index 2db368baec..8e371f4648 100644 --- a/vlib/os/os_nix.c.v +++ b/vlib/os/os_nix.c.v @@ -493,7 +493,7 @@ pub fn is_writable_folder(folder string) ?bool { } C.close(x) } - rm(tmp_perm_check) ? + rm(tmp_perm_check)? return true } diff --git a/vlib/os/os_test.v b/vlib/os/os_test.v index 3b523dd4f3..dd6f4e3bc4 100644 --- a/vlib/os/os_test.v +++ b/vlib/os/os_test.v @@ -86,20 +86,20 @@ fn test_open_file_binary() { // } fn create_file(fpath string) ? { - mut f := os.create(fpath) ? + mut f := os.create(fpath)? f.close() } fn create_and_write_to_file(fpath string, content string) ? { - mut f := os.create(fpath) ? - f.write_string(content) ? + mut f := os.create(fpath)? + f.write_string(content)? f.close() } fn test_create_file() ? { filename := './test1.txt' hello := 'hello world!' - create_and_write_to_file(filename, hello) ? + create_and_write_to_file(filename, hello)? assert u64(hello.len) == os.file_size(filename) os.rm(filename) or { panic(err) } } @@ -199,21 +199,21 @@ fn test_ls() { } fn create_tree() ? { - os.mkdir_all('myfolder/f1/f2/f3') ? - os.mkdir_all('myfolder/a1/a2/a3') ? + os.mkdir_all('myfolder/f1/f2/f3')? + os.mkdir_all('myfolder/a1/a2/a3')? f3 := os.real_path('myfolder/f1/f2/f3') assert os.is_dir(f3) - create_file('myfolder/f1/f2/f3/a.txt') ? - create_file('myfolder/f1/f2/f3/b.txt') ? - create_file('myfolder/f1/f2/f3/c.txt') ? - create_file('myfolder/f1/f2/f3/d.md') ? - create_file('myfolder/f1/0.txt') ? - create_file('myfolder/another.md') ? - create_file('myfolder/a1/a2/a3/x.txt') ? - create_file('myfolder/a1/a2/a3/y.txt') ? - create_file('myfolder/a1/a2/a3/z.txt') ? - create_file('myfolder/a1/1.txt') ? - create_file('myfolder/xyz.ini') ? + create_file('myfolder/f1/f2/f3/a.txt')? + create_file('myfolder/f1/f2/f3/b.txt')? + create_file('myfolder/f1/f2/f3/c.txt')? + create_file('myfolder/f1/f2/f3/d.md')? + create_file('myfolder/f1/0.txt')? + create_file('myfolder/another.md')? + create_file('myfolder/a1/a2/a3/x.txt')? + create_file('myfolder/a1/a2/a3/y.txt')? + create_file('myfolder/a1/a2/a3/z.txt')? + create_file('myfolder/a1/1.txt')? + create_file('myfolder/xyz.ini')? } fn remove_tree() { @@ -227,7 +227,7 @@ fn normalise_paths(paths []string) []string { } fn test_walk_ext() ? { - create_tree() ? + create_tree()? defer { remove_tree() } @@ -255,7 +255,7 @@ fn test_walk_ext() ? { } fn test_walk_with_context() ? { - create_tree() ? + create_tree()? defer { remove_tree() } @@ -445,8 +445,8 @@ fn test_realpath_does_not_absolutize_non_existing_relative_paths() { fn test_realpath_absolutepath_symlink() ? { file_name := 'tolink_file.txt' symlink_name := 'symlink.txt' - create_file(file_name) ? - assert os.symlink(file_name, symlink_name) ? + create_file(file_name)? + assert os.symlink(file_name, symlink_name)? rpath := os.real_path(symlink_name) println(rpath) assert os.is_abs_path(rpath) @@ -509,7 +509,7 @@ fn test_make_symlink_check_is_link_and_remove_symlink_with_file() ? { symlink := 'tsymlink' os.rm(symlink) or {} os.rm(file) or {} - create_file(file) ? + create_file(file)? os.symlink(file, symlink) or { panic(err) } assert os.is_link(symlink) os.rm(symlink) or { panic(err) } @@ -523,7 +523,7 @@ fn test_make_hardlink_check_is_link_and_remove_hardlink_with_file() ? { symlink := 'tsymlink' os.rm(symlink) or {} os.rm(file) or {} - create_file(file) ? + create_file(file)? os.link(file, symlink) or { panic(err) } assert os.exists(symlink) os.rm(symlink) or { panic(err) } @@ -568,7 +568,7 @@ fn test_symlink() { fn test_is_executable_writable_readable() ? { file_name := 'rwxfile.exe' - create_file(file_name) ? + create_file(file_name)? $if !windows { os.chmod(file_name, 0o600) or {} // mark as readable && writable, but NOT executable assert os.is_writable(file_name) @@ -731,7 +731,7 @@ fn test_posix_set_bit() ? { assert true } $else { fpath := 'permtest' - create_file(fpath) ? + create_file(fpath)? os.chmod(fpath, 0o0777) or { panic(err) } c_fpath := &char(fpath.str) mut s := C.stat{} @@ -789,8 +789,8 @@ fn test_exists_in_system_path() { fn test_truncate() ? { filename := './test_trunc.txt' hello := 'hello world!' - mut f := os.create(filename) ? - f.write_string(hello) ? + mut f := os.create(filename)? + f.write_string(hello)? f.close() assert u64(hello.len) == os.file_size(filename) newlen := u64(40000) @@ -807,10 +807,10 @@ fn test_glob() ? { os.mkdir('test_dir') or { panic(err) } for i in 0 .. 4 { if i == 3 { - create_file('test_dir/test0_another') ? - create_file('test_dir/test') ? + create_file('test_dir/test0_another')? + create_file('test_dir/test')? } else { - create_file('test_dir/test' + i.str()) ? + create_file('test_dir/test' + i.str())? } } files := os.glob('test_dir/t*') or { panic(err) } @@ -853,7 +853,7 @@ fn test_execute() ? { // The output of the next command contains a 0 byte in the middle. // Nevertheless, the execute function *should* return a string that // contains it. - os.write_file(print0script, 'C.printf(c"start%cMIDDLE%cfinish\nxx", 0, 0)\n') ? + os.write_file(print0script, 'C.printf(c"start%cMIDDLE%cfinish\nxx", 0, 0)\n')? defer { os.rm(print0script) or {} } diff --git a/vlib/os/os_windows.c.v b/vlib/os/os_windows.c.v index fa13ad2b6c..d4dadbb546 100644 --- a/vlib/os/os_windows.c.v +++ b/vlib/os/os_windows.c.v @@ -516,7 +516,7 @@ pub fn is_writable_folder(folder string) ?bool { tmp_folder_name := 'tmp_perm_check_pid_' + getpid().str() tmp_perm_check := join_path_single(folder, tmp_folder_name) write_file(tmp_perm_check, 'test') or { return error('cannot write to folder "$folder": $err') } - rm(tmp_perm_check) ? + rm(tmp_perm_check)? return true } diff --git a/vlib/os/process_test.v b/vlib/os/process_test.v index a219ee8b3e..1a1d1c4885 100644 --- a/vlib/os/process_test.v +++ b/vlib/os/process_test.v @@ -17,7 +17,7 @@ fn testsuite_begin() ? { // prebuilding the executable with: // v -os windows -o x.exe cmd/tools/test_os_process.v // WINE_TEST_OS_PROCESS_EXE=x.exe ./v -os windows vlib/os/process_test.v - os.cp(os.getenv('WINE_TEST_OS_PROCESS_EXE'), test_os_process) ? + os.cp(os.getenv('WINE_TEST_OS_PROCESS_EXE'), test_os_process)? } else { os.system('${os.quoted_path(vexe)} -o ${os.quoted_path(test_os_process)} ${os.quoted_path(test_os_process_source)}') } diff --git a/vlib/pg/orm.v b/vlib/pg/orm.v index 31f9617847..aeed948b7a 100644 --- a/vlib/pg/orm.v +++ b/vlib/pg/orm.v @@ -10,12 +10,12 @@ pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.Qu query := orm.orm_select_gen(config, '"', true, '$', 1, where) mut ret := [][]orm.Primitive{} - res := pg_stmt_worker(db, query, orm.QueryData{}, where) ? + res := pg_stmt_worker(db, query, orm.QueryData{}, where)? for row in res { mut row_data := []orm.Primitive{} for i, val in row.vals { - field := str_to_primitive(val, config.types[i]) ? + field := str_to_primitive(val, config.types[i])? row_data << field } ret << row_data @@ -28,17 +28,17 @@ pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.Qu pub fn (db DB) insert(table string, data orm.QueryData) ? { query := orm.orm_stmt_gen(table, '"', .insert, true, '$', 1, data, orm.QueryData{}) - pg_stmt_worker(db, query, data, orm.QueryData{}) ? + pg_stmt_worker(db, query, data, orm.QueryData{})? } pub fn (db DB) update(table string, data orm.QueryData, where orm.QueryData) ? { query := orm.orm_stmt_gen(table, '"', .update, true, '$', 1, data, where) - pg_stmt_worker(db, query, data, where) ? + pg_stmt_worker(db, query, data, where)? } pub fn (db DB) delete(table string, where orm.QueryData) ? { query := orm.orm_stmt_gen(table, '"', .delete, true, '$', 1, orm.QueryData{}, where) - pg_stmt_worker(db, query, orm.QueryData{}, where) ? + pg_stmt_worker(db, query, orm.QueryData{}, where)? } pub fn (db DB) last_id() orm.Primitive { @@ -51,12 +51,12 @@ pub fn (db DB) last_id() orm.Primitive { pub fn (db DB) create(table string, fields []orm.TableField) ? { query := orm.orm_table_gen(table, '"', true, 0, fields, pg_type_from_v, false) or { return err } - pg_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{}) ? + pg_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})? } pub fn (db DB) drop(table string) ? { query := 'DROP TABLE "$table";' - pg_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{}) ? + pg_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})? } // utils @@ -267,7 +267,7 @@ fn str_to_primitive(str string, typ int) ?orm.Primitive { } orm.time { if str.contains_any(' /:-') { - date_time_str := time.parse(str) ? + date_time_str := time.parse(str)? return orm.Primitive(date_time_str) } diff --git a/vlib/pg/pg.v b/vlib/pg/pg.v index 6b210d43d5..a5d77b0a00 100644 --- a/vlib/pg/pg.v +++ b/vlib/pg/pg.v @@ -126,7 +126,7 @@ pub fn (db DB) close() { // converted to an int. If no row is found or on // command failure, an error is returned pub fn (db DB) q_int(query string) ?int { - rows := db.exec(query) ? + rows := db.exec(query)? if rows.len == 0 { return error('q_int "$query" not found') } @@ -143,7 +143,7 @@ pub fn (db DB) q_int(query string) ?int { // as a string. If no row is found or on // command failure, an error is returned pub fn (db DB) q_string(query string) ?string { - rows := db.exec(query) ? + rows := db.exec(query)? if rows.len == 0 { return error('q_string "$query" not found') } @@ -182,7 +182,7 @@ pub fn (db DB) exec_one(query string) ?Row { if e != '' { return error('pg exec error: "$e"') } - row := rows_first_or_empty(res_to_rows(res)) ? + row := rows_first_or_empty(res_to_rows(res))? return row } diff --git a/vlib/rand/README.md b/vlib/rand/README.md index a98d966d3e..9badb43600 100644 --- a/vlib/rand/README.md +++ b/vlib/rand/README.md @@ -16,7 +16,7 @@ rand.seed([u32(3110), 50714]) ... // Use the top-level functions -rand.u32n(100) ? +rand.u32n(100)? rand.int() // among others ... ``` @@ -41,7 +41,7 @@ rng.seed(seed.time_seed_array(pcg32.seed_len)) ... // Use functions of your choice -rng.u32n(100) ? +rng.u32n(100)? rng.int() // among others ... ``` diff --git a/vlib/rand/rand.v b/vlib/rand/rand.v index c030b481d5..3544d71189 100644 --- a/vlib/rand/rand.v +++ b/vlib/rand/rand.v @@ -106,7 +106,7 @@ pub fn (mut rng PRNG) u32_in_range(min u32, max u32) ?u32 { if max <= min { return error('max must be greater than min') } - return min + rng.u32n(max - min) ? + return min + rng.u32n(max - min)? } // u64_in_range returns a uniformly distributed pseudorandom 64-bit unsigned `u64` in range `[min, max)`. @@ -115,7 +115,7 @@ pub fn (mut rng PRNG) u64_in_range(min u64, max u64) ?u64 { if max <= min { return error('max must be greater than min') } - return min + rng.u64n(max - min) ? + return min + rng.u64n(max - min)? } // i8 returns a (possibly negative) pseudorandom 8-bit `i8`. @@ -160,7 +160,7 @@ pub fn (mut rng PRNG) intn(max int) ?int { if max <= 0 { return error('max has to be positive.') } - return int(rng.u32n(u32(max)) ?) + return int(rng.u32n(u32(max))?) } // i64n returns a pseudorandom int that lies in `[0, max)`. @@ -169,7 +169,7 @@ pub fn (mut rng PRNG) i64n(max i64) ?i64 { if max <= 0 { return error('max has to be positive.') } - return i64(rng.u64n(u64(max)) ?) + return i64(rng.u64n(u64(max))?) } // int_in_range returns a pseudorandom `int` in range `[min, max)`. @@ -179,7 +179,7 @@ pub fn (mut rng PRNG) int_in_range(min int, max int) ?int { return error('max must be greater than min') } // This supports negative ranges like [-10, -5) because the difference is positive - return min + rng.intn(max - min) ? + return min + rng.intn(max - min)? } // i64_in_range returns a pseudorandom `i64` in range `[min, max)`. @@ -188,7 +188,7 @@ pub fn (mut rng PRNG) i64_in_range(min i64, max i64) ?i64 { if max <= min { return error('max must be greater than min') } - return min + rng.i64n(max - min) ? + return min + rng.i64n(max - min)? } // f32 returns a pseudorandom `f32` value in range `[0, 1)`. @@ -227,7 +227,7 @@ pub fn (mut rng PRNG) f32_in_range(min f32, max f32) ?f32 { if max < min { return error('max must be greater than or equal to min') } - return min + rng.f32n(max - min) ? + return min + rng.f32n(max - min)? } // i64_in_range returns a pseudorandom `i64` in range `[min, max]`. @@ -236,7 +236,7 @@ pub fn (mut rng PRNG) f64_in_range(min f64, max f64) ?f64 { if max < min { return error('max must be greater than or equal to min') } - return min + rng.f64n(max - min) ? + return min + rng.f64n(max - min)? } // ulid generates an Unique Lexicographically sortable IDentifier. @@ -298,7 +298,7 @@ fn (config ShuffleConfigStruct) validate_for(a []T) ? { // shuffle all elements until the end. [direct_array_access] pub fn (mut rng PRNG) shuffle(mut a []T, config ShuffleConfigStruct) ? { - config.validate_for(a) ? + config.validate_for(a)? new_end := if config.end == 0 { a.len } else { config.end } for i in config.start .. new_end { x := rng.int_in_range(i, new_end) or { config.start } @@ -313,7 +313,7 @@ pub fn (mut rng PRNG) shuffle(mut a []T, config ShuffleConfigStruct) ? { // The permutation is done on a fresh clone of `a`, so `a` remains unchanged. pub fn (mut rng PRNG) shuffle_clone(a []T, config ShuffleConfigStruct) ?[]T { mut res := a.clone() - rng.shuffle(mut res, config) ? + rng.shuffle(mut res, config)? return res } @@ -327,7 +327,7 @@ pub fn (mut rng PRNG) choose(array []T, k int) ?[]T { } mut results := []T{len: k} mut indices := []int{len: n, init: it} - rng.shuffle(mut indices) ? + rng.shuffle(mut indices)? for i in 0 .. k { results[i] = array[indices[i]] } @@ -542,7 +542,7 @@ pub fn ascii(len int) string { // optional and the entire array is shuffled by default. Leave the end as 0 to // shuffle all elements until the end. pub fn shuffle(mut a []T, config ShuffleConfigStruct) ? { - default_rng.shuffle(mut a, config) ? + default_rng.shuffle(mut a, config)? } // shuffle_clone returns a random permutation of the elements in `a`. diff --git a/vlib/rand/random_bytes_test.v b/vlib/rand/random_bytes_test.v index 80e7f52dfb..d31c5d3e7f 100644 --- a/vlib/rand/random_bytes_test.v +++ b/vlib/rand/random_bytes_test.v @@ -3,7 +3,7 @@ import rand fn test_rand_bytes() ? { mut randoms := []string{} for i in 0 .. 100 { - x := rand.bytes(i) ?.hex() + x := rand.bytes(i)?.hex() if x.len > 0 { randoms << x } @@ -25,7 +25,7 @@ fn test_prng_rand_bytes() ? { mut randoms := []string{} mut rng := rand.get_current_rng() for i in 0 .. 100 { - x := rng.bytes(i) ?.hex() + x := rng.bytes(i)?.hex() if x.len > 0 { randoms << x } diff --git a/vlib/rand/random_numbers_test.v b/vlib/rand/random_numbers_test.v index b823c47f33..79df3f82f9 100644 --- a/vlib/rand/random_numbers_test.v +++ b/vlib/rand/random_numbers_test.v @@ -358,11 +358,11 @@ fn test_shuffle_partial() ? { mut a := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] mut b := a.clone() - rand.shuffle(mut a, start: 4) ? + rand.shuffle(mut a, start: 4)? assert a[..4] == b[..4] a = b.clone() - rand.shuffle(mut a, start: 3, end: 7) ? + rand.shuffle(mut a, start: 3, end: 7)? assert a[..3] == b[..3] assert a[7..] == b[7..] } @@ -386,7 +386,7 @@ fn test_choose() ? { lengths := [1, 3, 4, 5, 6, 7] a := ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] for length in lengths { - b := rand.choose(a, length) ? + b := rand.choose(a, length)? assert b.len == length for element in b { assert element in a diff --git a/vlib/readline/README.md b/vlib/readline/README.md index c4bc9193a2..8f57153d58 100644 --- a/vlib/readline/README.md +++ b/vlib/readline/README.md @@ -6,21 +6,21 @@ from a terminal in an easy and structured manner. The module provides an easy way to prompt the user for questions or even make a REPL or an embedded console. - # Usage: ```v import readline mut r := readline.Readline{} -answer := r.read_line('hello: ') ? +answer := r.read_line('hello: ')? println(answer) ``` or just: + ```v import readline { read_line } -input := read_line('What is your name: ') ? +input := read_line('What is your name: ')? println('Your name is: $input') ``` diff --git a/vlib/readline/readline_default.c.v b/vlib/readline/readline_default.c.v index 9c2f03e199..688b0a4da4 100644 --- a/vlib/readline/readline_default.c.v +++ b/vlib/readline/readline_default.c.v @@ -50,7 +50,7 @@ pub fn (mut r Readline) read_line_utf8(prompt string) ?[]rune { // read_line does the same as `read_line_utf8` but returns user input as a `string`. // (As opposed to `[]rune` returned by `read_line_utf8`). pub fn (mut r Readline) read_line(prompt string) ?string { - s := r.read_line_utf8(prompt) ? + s := r.read_line_utf8(prompt)? return s.string() } @@ -65,7 +65,7 @@ pub fn (mut r Readline) read_line(prompt string) ?string { // persistent functionalities (e.g. history). pub fn read_line_utf8(prompt string) ?[]rune { mut r := Readline{} - s := r.read_line_utf8(prompt) ? + s := r.read_line_utf8(prompt)? return s } @@ -75,6 +75,6 @@ pub fn read_line_utf8(prompt string) ?[]rune { // persistent functionalities (e.g. history). pub fn read_line(prompt string) ?string { mut r := Readline{} - s := r.read_line(prompt) ? + s := r.read_line(prompt)? return s } diff --git a/vlib/readline/readline_js.js.v b/vlib/readline/readline_js.js.v index 22a3350c65..7d6f4e1bd9 100644 --- a/vlib/readline/readline_js.js.v +++ b/vlib/readline/readline_js.js.v @@ -27,6 +27,6 @@ pub fn (mut r Readline) read_line(prompt string) ?string { pub fn read_line(prompt string) ?string { mut r := Readline{} - s := r.read_line(prompt) ? + s := r.read_line(prompt)? return s } diff --git a/vlib/readline/readline_linux.c.v b/vlib/readline/readline_linux.c.v index a5c22c9e19..cd15a0737e 100644 --- a/vlib/readline/readline_linux.c.v +++ b/vlib/readline/readline_linux.c.v @@ -169,7 +169,7 @@ pub fn (mut r Readline) read_line_utf8(prompt string) ?[]rune { // read_line does the same as `read_line_utf8` but returns user input as a `string`. // (As opposed to `[]rune` returned by `read_line_utf8`). pub fn (mut r Readline) read_line(prompt string) ?string { - s := r.read_line_utf8(prompt) ? + s := r.read_line_utf8(prompt)? return s.string() } @@ -184,7 +184,7 @@ pub fn (mut r Readline) read_line(prompt string) ?string { // persistent functionalities (e.g. history). pub fn read_line_utf8(prompt string) ?[]rune { mut r := Readline{} - s := r.read_line_utf8(prompt) ? + s := r.read_line_utf8(prompt)? return s } @@ -194,7 +194,7 @@ pub fn read_line_utf8(prompt string) ?[]rune { // persistent functionalities (e.g. history). pub fn read_line(prompt string) ?string { mut r := Readline{} - s := r.read_line(prompt) ? + s := r.read_line(prompt)? return s } diff --git a/vlib/readline/readline_windows.c.v b/vlib/readline/readline_windows.c.v index 511c26c3a0..4408502c70 100644 --- a/vlib/readline/readline_windows.c.v +++ b/vlib/readline/readline_windows.c.v @@ -48,7 +48,7 @@ pub fn (mut r Readline) read_line_utf8(prompt string) ?[]rune { // read_line does the same as `read_line_utf8` but returns user input as a `string`. // (As opposed to `[]rune` returned by `read_line_utf8`). pub fn (mut r Readline) read_line(prompt string) ?string { - s := r.read_line_utf8(prompt) ? + s := r.read_line_utf8(prompt)? return s.string() } @@ -63,7 +63,7 @@ pub fn (mut r Readline) read_line(prompt string) ?string { // persistent functionalities (e.g. history). pub fn read_line_utf8(prompt string) ?[]rune { mut r := Readline{} - s := r.read_line_utf8(prompt) ? + s := r.read_line_utf8(prompt)? return s } @@ -73,6 +73,6 @@ pub fn read_line_utf8(prompt string) ?[]rune { // persistent functionalities (e.g. history). pub fn read_line(prompt string) ?string { mut r := Readline{} - s := r.read_line(prompt) ? + s := r.read_line(prompt)? return s } diff --git a/vlib/regex/README.md b/vlib/regex/README.md index 0b481ad957..34df63a0d9 100644 --- a/vlib/regex/README.md +++ b/vlib/regex/README.md @@ -540,7 +540,7 @@ After an initializer is used, the regex expression must be compiled with: ```v ignore // compile compiles the REgex returning an error if the compilation fails -pub fn (re mut RE) compile_opt(in_txt string) ? +pub fn (re mut RE) compile_opt(in_txt string)? ``` ### Matching Functions diff --git a/vlib/regex/regex_opt.v b/vlib/regex/regex_opt.v index 9269069789..e02f563dca 100644 --- a/vlib/regex/regex_opt.v +++ b/vlib/regex/regex_opt.v @@ -47,7 +47,7 @@ pub fn regex_opt(pattern string) ?RE { re.group_data = []int{len: re.group_max, init: -1} // compile the pattern - re.compile_opt(pattern) ? + re.compile_opt(pattern)? return re } diff --git a/vlib/regex/regex_test.v b/vlib/regex/regex_test.v index bc38ffad67..fdc5cf2d50 100644 --- a/vlib/regex/regex_test.v +++ b/vlib/regex/regex_test.v @@ -254,7 +254,7 @@ cgroups_test_suite = [ "http://www.ciao.mondo/hello/pippo12_/pera.html", r"(?Phttps?)|(?Pftps?)://(?P[\w_]+.)+",0,46, [8, 0, 0, 4, 1, 7, 11, 1, 11, 16, 1, 16, 22, 1, 22, 28, 1, 28, 37, 1, 37, 42, 1, 42, 46] - //[8, 0, 0, 4, 1, 7, 10, 1, 11, 15, 1, 16, 21, 1, 22, 27, 1, 28, 36, 1, 37, 41, 1, 42, 46], + //[8, 0, 0, 4, 1, 7, 10, 1, 11, 15, 1, 16, 21, 1, 22, 27, 1, 28, 36, 1, 37, 41, 1, 42, 46], {'format':int(0),'token':1} }, TestItemCGroup{ diff --git a/vlib/sokol/sapp/sapp_v.c.v b/vlib/sokol/sapp/sapp_v.c.v index bca061a2f6..346fa23351 100644 --- a/vlib/sokol/sapp/sapp_v.c.v +++ b/vlib/sokol/sapp/sapp_v.c.v @@ -30,7 +30,7 @@ pub fn screenshot(path string) ? { [manualfree] pub fn screenshot_ppm(path string) ? { ss := screenshot_window() - write_rgba_to_ppm(path, ss.width, ss.height, 4, ss.pixels) ? + write_rgba_to_ppm(path, ss.width, ss.height, 4, ss.pixels)? unsafe { ss.destroy() } } @@ -40,19 +40,19 @@ pub fn screenshot_ppm(path string) ? { pub fn screenshot_png(path string) ? { ss := screenshot_window() stbi.set_flip_vertically_on_write(true) - stbi.stbi_write_png(path, ss.width, ss.height, 4, ss.pixels, ss.width * 4) ? + stbi.stbi_write_png(path, ss.width, ss.height, 4, ss.pixels, ss.width * 4)? unsafe { ss.destroy() } } // write_rgba_to_ppm writes `pixels` data in RGBA format to PPM3 format. fn write_rgba_to_ppm(path string, w int, h int, components int, pixels &u8) ? { - mut f_out := os.create(path) ? + mut f_out := os.create(path)? defer { f_out.close() } - f_out.writeln('P3') ? - f_out.writeln('$w $h') ? - f_out.writeln('255') ? + f_out.writeln('P3')? + f_out.writeln('$w $h')? + f_out.writeln('255')? for i := h - 1; i >= 0; i-- { for j := 0; j < w; j++ { idx := i * w * components + j * components @@ -60,7 +60,7 @@ fn write_rgba_to_ppm(path string, w int, h int, components int, pixels &u8) ? { r := int(pixels[idx]) g := int(pixels[idx + 1]) b := int(pixels[idx + 2]) - f_out.write_string('$r $g $b ') ? + f_out.write_string('$r $g $b ')? } } } diff --git a/vlib/sqlite/orm.v b/vlib/sqlite/orm.v index c56b52f84d..8aa6720c66 100644 --- a/vlib/sqlite/orm.v +++ b/vlib/sqlite/orm.v @@ -7,10 +7,10 @@ import time pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.QueryData) ?[][]orm.Primitive { query := orm.orm_select_gen(config, '`', true, '?', 1, where) - stmt := db.new_init_stmt(query) ? + stmt := db.new_init_stmt(query)? mut c := 1 - sqlite_stmt_binder(stmt, where, query, mut c) ? - sqlite_stmt_binder(stmt, data, query, mut c) ? + sqlite_stmt_binder(stmt, where, query, mut c)? + sqlite_stmt_binder(stmt, data, query, mut c)? defer { stmt.finalize() @@ -23,7 +23,7 @@ pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.Qu if step !in [sqlite_row, sqlite_ok, sqlite_done] { return db.error_message(step, query) } - count := stmt.sqlite_select_column(0, 8) ? + count := stmt.sqlite_select_column(0, 8)? ret << [count] return ret } @@ -37,7 +37,7 @@ pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.Qu } mut row := []orm.Primitive{} for i, typ in config.types { - primitive := stmt.sqlite_select_column(i, typ) ? + primitive := stmt.sqlite_select_column(i, typ)? row << primitive } ret << row @@ -49,17 +49,17 @@ pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.Qu pub fn (db DB) insert(table string, data orm.QueryData) ? { query := orm.orm_stmt_gen(table, '`', .insert, true, '?', 1, data, orm.QueryData{}) - sqlite_stmt_worker(db, query, data, orm.QueryData{}) ? + sqlite_stmt_worker(db, query, data, orm.QueryData{})? } pub fn (db DB) update(table string, data orm.QueryData, where orm.QueryData) ? { query := orm.orm_stmt_gen(table, '`', .update, true, '?', 1, data, where) - sqlite_stmt_worker(db, query, data, where) ? + sqlite_stmt_worker(db, query, data, where)? } pub fn (db DB) delete(table string, where orm.QueryData) ? { query := orm.orm_stmt_gen(table, '`', .delete, true, '?', 1, orm.QueryData{}, where) - sqlite_stmt_worker(db, query, orm.QueryData{}, where) ? + sqlite_stmt_worker(db, query, orm.QueryData{}, where)? } pub fn (db DB) last_id() orm.Primitive { @@ -73,22 +73,22 @@ pub fn (db DB) create(table string, fields []orm.TableField) ? { query := orm.orm_table_gen(table, '`', true, 0, fields, sqlite_type_from_v, false) or { return err } - sqlite_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{}) ? + sqlite_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})? } pub fn (db DB) drop(table string) ? { query := 'DROP TABLE `$table`;' - sqlite_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{}) ? + sqlite_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})? } // helper fn sqlite_stmt_worker(db DB, query string, data orm.QueryData, where orm.QueryData) ? { - stmt := db.new_init_stmt(query) ? + stmt := db.new_init_stmt(query)? mut c := 1 - sqlite_stmt_binder(stmt, data, query, mut c) ? - sqlite_stmt_binder(stmt, where, query, mut c) ? - stmt.orm_step(query) ? + sqlite_stmt_binder(stmt, data, query, mut c)? + sqlite_stmt_binder(stmt, where, query, mut c)? + stmt.orm_step(query)? stmt.finalize() } diff --git a/vlib/strconv/atoi.v b/vlib/strconv/atoi.v index 8dd4c0002d..2babb2c1a2 100644 --- a/vlib/strconv/atoi.v +++ b/vlib/strconv/atoi.v @@ -144,7 +144,7 @@ pub fn common_parse_int(_s string, base int, _bit_size int, error_on_non_digit b // un := parse_uint(s, base, bit_size) or { // return i64(0) // } - un := common_parse_uint(s, base, bit_size, error_on_non_digit, error_on_high_digit) ? + un := common_parse_uint(s, base, bit_size, error_on_non_digit, error_on_high_digit)? if un == 0 { return i64(0) } @@ -208,7 +208,7 @@ pub fn atoi(s string) ?int { return if s[0] == `-` { -n } else { n } } // Slow path for invalid, big, or underscored integers. - int64 := parse_int(s, 10, 0) ? + int64 := parse_int(s, 10, 0)? return int(int64) } diff --git a/vlib/strconv/atoi_test.v b/vlib/strconv/atoi_test.v index b356db6a7d..a4b1405ad8 100644 --- a/vlib/strconv/atoi_test.v +++ b/vlib/strconv/atoi_test.v @@ -1,9 +1,9 @@ import strconv fn test_atoi() ? { - assert strconv.atoi('16') ? == 16 - assert strconv.atoi('+16') ? == 16 - assert strconv.atoi('-16') ? == -16 + assert strconv.atoi('16')? == 16 + assert strconv.atoi('+16')? == 16 + assert strconv.atoi('-16')? == -16 // invalid strings if x := strconv.atoi('str') { @@ -28,19 +28,19 @@ fn test_atoi() ? { fn test_parse_int() ? { // Different bases - assert strconv.parse_int('16', 16, 0) ? == 0x16 - assert strconv.parse_int('16', 8, 0) ? == 0o16 - assert strconv.parse_int('11', 2, 0) ? == 3 + assert strconv.parse_int('16', 16, 0)? == 0x16 + assert strconv.parse_int('16', 8, 0)? == 0o16 + assert strconv.parse_int('11', 2, 0)? == 3 // Different bit sizes - assert strconv.parse_int('127', 10, 8) ? == 127 - assert strconv.parse_int('128', 10, 8) ? == 127 - assert strconv.parse_int('32767', 10, 16) ? == 32767 - assert strconv.parse_int('32768', 10, 16) ? == 32767 - assert strconv.parse_int('2147483647', 10, 32) ? == 2147483647 - assert strconv.parse_int('2147483648', 10, 32) ? == 2147483647 - assert strconv.parse_int('9223372036854775807', 10, 64) ? == 9223372036854775807 - assert strconv.parse_int('9223372036854775808', 10, 64) ? == 9223372036854775807 - assert strconv.parse_int('baobab', 36, 64) ? == 683058467 + assert strconv.parse_int('127', 10, 8)? == 127 + assert strconv.parse_int('128', 10, 8)? == 127 + assert strconv.parse_int('32767', 10, 16)? == 32767 + assert strconv.parse_int('32768', 10, 16)? == 32767 + assert strconv.parse_int('2147483647', 10, 32)? == 2147483647 + assert strconv.parse_int('2147483648', 10, 32)? == 2147483647 + assert strconv.parse_int('9223372036854775807', 10, 64)? == 9223372036854775807 + assert strconv.parse_int('9223372036854775808', 10, 64)? == 9223372036854775807 + assert strconv.parse_int('baobab', 36, 64)? == 683058467 // Invalid bit sizes if x := strconv.parse_int('123', 10, -1) { println(x) diff --git a/vlib/sync/channel_opt_propagate_test.v b/vlib/sync/channel_opt_propagate_test.v index 20cb19627b..0bab011ef8 100644 --- a/vlib/sync/channel_opt_propagate_test.v +++ b/vlib/sync/channel_opt_propagate_test.v @@ -5,7 +5,7 @@ const ( ) fn get_val_from_chan(ch chan i64) ?i64 { - r := <-ch ? + r := <-ch? return r } diff --git a/vlib/sync/channel_push_or_2_test.v b/vlib/sync/channel_push_or_2_test.v index 451d9e7b08..040e814139 100644 --- a/vlib/sync/channel_push_or_2_test.v +++ b/vlib/sync/channel_push_or_2_test.v @@ -10,7 +10,7 @@ fn f(ch chan f64) { } fn do_send(ch chan f64, val f64) ?f64 { - ch <- val ? + ch <- val? return val + 1.0 } diff --git a/vlib/szip/szip.v b/vlib/szip/szip.v index b65e45289c..720820936a 100644 --- a/vlib/szip/szip.v +++ b/vlib/szip/szip.v @@ -273,7 +273,7 @@ pub fn zip_folder(folder string, zip_file string, opt ZipFolderOptions) ? { }) // open or create new zip - mut zip := open(zip_file, .no_compression, .write) ? + mut zip := open(zip_file, .no_compression, .write)? // close zip defer { zip.close() @@ -296,10 +296,10 @@ pub fn zip_folder(folder string, zip_file string, opt ZipFolderOptions) ? { zip_file_entry += '/' // Tells the implementation that the entry is a directory } // add file or directory (ends with "/") to zip - zip.open_entry(zip_file_entry) ? + zip.open_entry(zip_file_entry)? if !is_dir { - file_as_byte := os.read_bytes(file) ? - zip.write_entry(file_as_byte) ? + file_as_byte := os.read_bytes(file)? + zip.write_entry(file_as_byte)? } zip.close_entry() } diff --git a/vlib/szip/szip_test.v b/vlib/szip/szip_test.v index 138ad16bb9..412eb89d23 100644 --- a/vlib/szip/szip_test.v +++ b/vlib/szip/szip_test.v @@ -41,35 +41,35 @@ fn testsuite_end() ? { } fn test_szip_create_temp_files() ? { - os.mkdir(test_path) ? - os.mkdir(test_path2) ? - os.write_file(fpath1, 'file one') ? - os.write_file(fpath2, 'file two') ? - os.write_file(fpath3, 'file three') ? + os.mkdir(test_path)? + os.mkdir(test_path2)? + os.write_file(fpath1, 'file one')? + os.write_file(fpath2, 'file two')? + os.write_file(fpath3, 'file three')? assert os.exists(fpath1) assert os.exists(fpath2) assert os.exists(fpath3) } fn test_zipping_files() ? { - mut files := (os.ls(test_path) ?).map(os.join_path(test_path, it)) - files << (os.ls(test_path2) ?).map(os.join_path(test_path2, it)) - szip.zip_files(files, test_out_zip) ? + mut files := (os.ls(test_path)?).map(os.join_path(test_path, it)) + files << (os.ls(test_path2)?).map(os.join_path(test_path2, it)) + szip.zip_files(files, test_out_zip)? assert os.exists(test_out_zip) - os.rm(fpath1) ? - os.rm(fpath2) ? - os.rm(fpath3) ? + os.rm(fpath1)? + os.rm(fpath2)? + os.rm(fpath3)? } fn test_extract_zipped_files() ? { - szip.extract_zip_to_dir(test_out_zip, test_path) ? - szip.extract_zip_to_dir(test_out_zip, test_path2) ? + szip.extract_zip_to_dir(test_out_zip, test_path)? + szip.extract_zip_to_dir(test_out_zip, test_path2)? assert os.exists(fpath1) assert os.exists(fpath2) assert os.exists(fpath3) - assert (os.read_file(fpath1) ?) == 'file one' - assert (os.read_file(fpath2) ?) == 'file two' - assert (os.read_file(fpath3) ?) == 'file three' + assert (os.read_file(fpath1)?) == 'file one' + assert (os.read_file(fpath2)?) == 'file two' + assert (os.read_file(fpath3)?) == 'file three' cleanup() } @@ -81,21 +81,21 @@ fn test_reading_zipping_files() ? { } cleanup() - os.mkdir(test_path) ? - os.mkdir(test_path2) ? - os.write_file(fpath3, 'file three') ? + os.mkdir(test_path)? + os.mkdir(test_path2)? + os.write_file(fpath3, 'file three')? for c, f_name in file_name_list { tmp_path := os.join_path(test_path, f_name) - os.write_file(tmp_path, 'file ${c:02}') ? + os.write_file(tmp_path, 'file ${c:02}')? assert os.exists(tmp_path) } - files := (os.ls(test_path) ?).map(os.join_path(test_path, it)) + files := (os.ls(test_path)?).map(os.join_path(test_path, it)) - szip.zip_files(files, test_out_zip) ? + szip.zip_files(files, test_out_zip)? assert os.exists(test_out_zip) - mut zp := szip.open(test_out_zip, szip.CompressionLevel.no_compression, szip.OpenMode.read_only) ? - n_entries := zp.total() ? + mut zp := szip.open(test_out_zip, szip.CompressionLevel.no_compression, szip.OpenMode.read_only)? + n_entries := zp.total()? assert n_entries == n_files unsafe { @@ -104,11 +104,11 @@ fn test_reading_zipping_files() ? { buf := malloc(data_len * 2) for _ in 0 .. n_files { - zp.open_entry_by_index(0) ? + zp.open_entry_by_index(0)? name := zp.name() assert name in file_name_list - zp.read_entry_buf(buf, buf_size) ? + zp.read_entry_buf(buf, buf_size)? buf[data_len] = 0 tmp_str := tos(buf, data_len) @@ -125,50 +125,50 @@ fn test_reading_zipping_files() ? { fn test_zip_folder() ? { cleanup() - os.mkdir_all(test_path3_1) ? - os.mkdir_all(test_path3_2) ? - os.mkdir_all(test_path3_3) ? - os.mkdir_all(test_path3_4) ? - os.write_file(fpath4, '4') ? - os.write_file(fpath5, '5') ? - os.write_file(fpath6, '6') ? + os.mkdir_all(test_path3_1)? + os.mkdir_all(test_path3_2)? + os.mkdir_all(test_path3_3)? + os.mkdir_all(test_path3_4)? + os.write_file(fpath4, '4')? + os.write_file(fpath5, '5')? + os.write_file(fpath6, '6')? - szip.zip_folder(test_path3, test_dir_zip) ? + szip.zip_folder(test_path3, test_dir_zip)? assert os.exists(test_dir_zip) - os.rmdir_all(test_path3) ? - os.mkdir_all(test_path3) ? - szip.extract_zip_to_dir(test_dir_zip, test_path3) ? + os.rmdir_all(test_path3)? + os.mkdir_all(test_path3)? + szip.extract_zip_to_dir(test_dir_zip, test_path3)? assert os.exists(test_path3_1) assert os.exists(test_path3_2) assert os.exists(test_path3_3) // This is the empty dir assert os.exists(test_path3_4) - assert (os.read_file(fpath4) ?) == '4' - assert (os.read_file(fpath5) ?) == '5' - assert (os.read_file(fpath6) ?) == '6' + assert (os.read_file(fpath4)?) == '4' + assert (os.read_file(fpath5)?) == '5' + assert (os.read_file(fpath6)?) == '6' } fn test_zip_folder_omit_empty_directories() ? { cleanup() - os.mkdir_all(test_path3_1) ? - os.mkdir_all(test_path3_2) ? - os.mkdir_all(test_path3_3) ? - os.mkdir_all(test_path3_4) ? - os.write_file(fpath4, '4') ? - os.write_file(fpath5, '5') ? - os.write_file(fpath6, '6') ? + os.mkdir_all(test_path3_1)? + os.mkdir_all(test_path3_2)? + os.mkdir_all(test_path3_3)? + os.mkdir_all(test_path3_4)? + os.write_file(fpath4, '4')? + os.write_file(fpath5, '5')? + os.write_file(fpath6, '6')? - szip.zip_folder(test_path3, test_dir_zip, omit_empty_folders: true) ? + szip.zip_folder(test_path3, test_dir_zip, omit_empty_folders: true)? assert os.exists(test_dir_zip) - os.rmdir_all(test_path3) ? - os.mkdir_all(test_path3) ? - szip.extract_zip_to_dir(test_dir_zip, test_path3) ? + os.rmdir_all(test_path3)? + os.mkdir_all(test_path3)? + szip.extract_zip_to_dir(test_dir_zip, test_path3)? assert os.exists(test_path3_1) assert os.exists(test_path3_2) assert !os.exists(test_path3_3) // This is the empty dir, should be omitted with `omit_empty_folders` assert os.exists(test_path3_4) - assert (os.read_file(fpath4) ?) == '4' - assert (os.read_file(fpath5) ?) == '5' - assert (os.read_file(fpath6) ?) == '6' + assert (os.read_file(fpath4)?) == '4' + assert (os.read_file(fpath5)?) == '5' + assert (os.read_file(fpath6)?) == '6' } diff --git a/vlib/term/term_test.v b/vlib/term/term_test.v index 114b302cf7..3df6af712f 100644 --- a/vlib/term/term_test.v +++ b/vlib/term/term_test.v @@ -58,8 +58,8 @@ fn test_header() { } fn test_get_cursor_position() ? { - original_position := term.get_cursor_position() ? - cursor_position_1 := term.get_cursor_position() ? + original_position := term.get_cursor_position()? + cursor_position_1 := term.get_cursor_position()? assert original_position.x == cursor_position_1.x assert original_position.y == cursor_position_1.y // @@ -67,13 +67,13 @@ fn test_get_cursor_position() ? { x: 10 y: 11 ) - cursor_position_2 := term.get_cursor_position() ? + cursor_position_2 := term.get_cursor_position()? // term.set_cursor_position( x: 5 y: 6 ) - cursor_position_3 := term.get_cursor_position() ? + cursor_position_3 := term.get_cursor_position()? // term.set_cursor_position(original_position) eprintln('original_position: $original_position') diff --git a/vlib/term/ui/README.md b/vlib/term/ui/README.md index 82e349665f..31a2b50ee3 100644 --- a/vlib/term/ui/README.md +++ b/vlib/term/ui/README.md @@ -40,7 +40,7 @@ fn main() { frame_fn: frame hide_cursor: true ) - app.tui.run() ? + app.tui.run()? } ``` diff --git a/vlib/term/ui/input_nix.c.v b/vlib/term/ui/input_nix.c.v index 1ce0460f29..f2f50724d8 100644 --- a/vlib/term/ui/input_nix.c.v +++ b/vlib/term/ui/input_nix.c.v @@ -45,7 +45,7 @@ pub fn (mut ctx Context) run() ? { ctx.fail('error: x11 backend not implemented yet') exit(1) } else { - ctx.termios_setup() ? + ctx.termios_setup()? ctx.termios_loop() } } diff --git a/vlib/time/parse.c.v b/vlib/time/parse.c.v index 3b7c369023..56f32948ae 100644 --- a/vlib/time/parse.c.v +++ b/vlib/time/parse.c.v @@ -23,7 +23,7 @@ pub fn parse_rfc3339(s string) ?Time { // Check if sn is date only if !parts[0].contains_any(' Z') && parts[0].contains('-') { - year, month, day := parse_iso8601_date(sn) ? + year, month, day := parse_iso8601_date(sn)? t = new_time(Time{ year: year month: month @@ -34,7 +34,7 @@ pub fn parse_rfc3339(s string) ?Time { // Check if sn is time only if !parts[0].contains('-') && parts[0].contains(':') { mut hour_, mut minute_, mut second_, mut microsecond_, mut unix_offset, mut is_local_time := 0, 0, 0, 0, i64(0), true - hour_, minute_, second_, microsecond_, unix_offset, is_local_time = parse_iso8601_time(parts[0]) ? + hour_, minute_, second_, microsecond_, unix_offset, is_local_time = parse_iso8601_time(parts[0])? t = new_time(Time{ hour: hour_ minute: minute_ @@ -124,10 +124,10 @@ pub fn parse_iso8601(s string) ?Time { if !(parts.len == 1 || parts.len == 2) { return error_invalid_time(12) } - year, month, day := parse_iso8601_date(parts[0]) ? + year, month, day := parse_iso8601_date(parts[0])? mut hour_, mut minute_, mut second_, mut microsecond_, mut unix_offset, mut is_local_time := 0, 0, 0, 0, i64(0), true if parts.len == 2 { - hour_, minute_, second_, microsecond_, unix_offset, is_local_time = parse_iso8601_time(parts[1]) ? + hour_, minute_, second_, microsecond_, unix_offset, is_local_time = parse_iso8601_time(parts[1])? } mut t := new_time( year: year diff --git a/vlib/time/time_addition_test.v b/vlib/time/time_addition_test.v index 8fde8744c1..d21d5aed0e 100644 --- a/vlib/time/time_addition_test.v +++ b/vlib/time/time_addition_test.v @@ -1,7 +1,7 @@ import time fn test_add_to_day_in_the_previous_century() ? { - a := time.parse_iso8601('1900-01-01') ? + a := time.parse_iso8601('1900-01-01')? aa := a.add_days(180) dump(a.debug()) dump(aa.debug()) @@ -9,25 +9,25 @@ fn test_add_to_day_in_the_previous_century() ? { } fn test_add_to_day_in_the_past() ? { - a := time.parse_iso8601('1990-03-01') ? + a := time.parse_iso8601('1990-03-01')? aa := a.add_days(180) assert aa.ymmdd() == '1990-08-27' } fn test_add_to_day_in_the_recent_past() ? { - a := time.parse_iso8601('2021-03-01') ? + a := time.parse_iso8601('2021-03-01')? aa := a.add_days(180) assert aa.ymmdd() == '2021-08-28' } fn test_add_to_day_in_the_future_1() ? { - a := time.parse_iso8601('3000-11-01') ? + a := time.parse_iso8601('3000-11-01')? aa := a.add_days(180) assert aa.ymmdd() == '3001-04-30' } fn test_add_to_day_in_the_future_2() ? { - a := time.parse_iso8601('3000-12-30') ? + a := time.parse_iso8601('3000-12-30')? aa := a.add_days(180) assert aa.ymmdd() == '3001-06-28' } diff --git a/vlib/toml/ast/walker/walker.v b/vlib/toml/ast/walker/walker.v index a51e714ce1..3264dacffe 100644 --- a/vlib/toml/ast/walker/walker.v +++ b/vlib/toml/ast/walker/walker.v @@ -26,7 +26,7 @@ pub fn (i &Inspector) visit(value &ast.Value) ? { // inspect traverses and checks the AST Value node on a depth-first order and based on the data given pub fn inspect(value &ast.Value, data voidptr, inspector_callback InspectorFn) ? { - walk(Inspector{inspector_callback, data}, value) ? + walk(Inspector{inspector_callback, data}, value)? } // walk traverses the AST using the given visitor @@ -34,16 +34,16 @@ pub fn walk(visitor Visitor, value &ast.Value) ? { if value is map[string]ast.Value { value_map := value as map[string]ast.Value for _, val in value_map { - walk(visitor, &val) ? + walk(visitor, &val)? } } if value is []ast.Value { value_array := value as []ast.Value for val in value_array { - walk(visitor, &val) ? + walk(visitor, &val)? } } else { - visitor.visit(value) ? + visitor.visit(value)? } } @@ -53,15 +53,15 @@ pub fn walk_and_modify(modifier Modifier, mut value ast.Value) ? { if value is map[string]ast.Value { mut value_map := value as map[string]ast.Value for _, mut val in value_map { - walk_and_modify(modifier, mut &val) ? + walk_and_modify(modifier, mut &val)? } } if value is []ast.Value { mut value_array := value as []ast.Value for mut val in value_array { - walk_and_modify(modifier, mut &val) ? + walk_and_modify(modifier, mut &val)? } } else { - modifier.modify(mut value) ? + modifier.modify(mut value)? } } diff --git a/vlib/toml/checker/checker.v b/vlib/toml/checker/checker.v index 25636e55d4..5175d43dc6 100644 --- a/vlib/toml/checker/checker.v +++ b/vlib/toml/checker/checker.v @@ -25,28 +25,28 @@ pub struct Checker { // check checks the `ast.Value` and all it's children // for common errors. pub fn (c Checker) check(n &ast.Value) ? { - walker.walk(c, n) ? + walker.walk(c, n)? } fn (c Checker) visit(value &ast.Value) ? { match value { ast.Bool { - c.check_boolean(value) ? + c.check_boolean(value)? } ast.Number { - c.check_number(value) ? + c.check_number(value)? } ast.Quoted { - c.check_quoted(value) ? + c.check_quoted(value)? } ast.DateTime { - c.check_date_time(value) ? + c.check_date_time(value)? } ast.Date { - c.check_date(value) ? + c.check_date(value)? } ast.Time { - c.check_time(value) ? + c.check_time(value)? } else {} } @@ -307,7 +307,7 @@ fn (c Checker) check_date_time(dt ast.DateTime) ? { pos: dt.pos.pos col: dt.pos.col } - }) ? + })? c.check_time(ast.Time{ text: split[1] pos: token.Pos{ @@ -316,7 +316,7 @@ fn (c Checker) check_date_time(dt ast.DateTime) ? { pos: dt.pos.pos + split[0].len col: dt.pos.col + split[0].len } - }) ? + })? // Use V's builtin functionality to validate the string time.parse_rfc3339(lit) or { return error(@MOD + '.' + @STRUCT + '.' + @FN + @@ -395,8 +395,8 @@ pub fn (c Checker) check_quoted(q ast.Quoted) ? { return error(@MOD + '.' + @STRUCT + '.' + @FN + ' string values like "$lit" has unbalanced quote literals `q.quote` in ...${c.excerpt(q.pos)}...') } - c.check_quoted_escapes(q) ? - c.check_utf8_validity(q) ? + c.check_quoted_escapes(q)? + c.check_utf8_validity(q)? } // check_quoted_escapes returns an error for any disallowed escape sequences. @@ -415,7 +415,7 @@ pub fn (c Checker) check_quoted(q ast.Quoted) ? { // \UXXXXXXXX - Unicode (U+XXXXXXXX) fn (c Checker) check_quoted_escapes(q ast.Quoted) ? { // Setup a scanner in stack memory for easier navigation. - mut s := scanner.new_simple_text(q.text) ? + mut s := scanner.new_simple_text(q.text)? // See https://toml.io/en/v1.0.0#string for more info on string types. is_basic := q.quote == `\"` @@ -539,7 +539,7 @@ fn (c Checker) check_unicode_escape(esc_unicode string) ? { // if !sequence.is_upper() { // return error('Unicode escape sequence `$esc_unicode` is not in all uppercase.') //} - validate_utf8_codepoint_string(sequence.to_upper()) ? + validate_utf8_codepoint_string(sequence.to_upper())? if is_long_esc_type { // Long escape type checks } else { @@ -552,7 +552,7 @@ fn (c Checker) check_unicode_escape(esc_unicode string) ? { pub fn (c Checker) check_comment(comment ast.Comment) ? { lit := comment.text // Setup a scanner in stack memory for easier navigation. - mut s := scanner.new_simple_text(lit) ? + mut s := scanner.new_simple_text(lit)? for { ch := s.next() if ch == scanner.end_of_text { diff --git a/vlib/toml/decoder/decoder.v b/vlib/toml/decoder/decoder.v index 7006aa01a8..0c7ae684dc 100644 --- a/vlib/toml/decoder/decoder.v +++ b/vlib/toml/decoder/decoder.v @@ -21,22 +21,22 @@ pub struct Decoder { // decode decodes certain `ast.Value`'s and all it's children. pub fn (d Decoder) decode(mut n ast.Value) ? { - walker.walk_and_modify(d, mut n) ? + walker.walk_and_modify(d, mut n)? } fn (d Decoder) modify(mut value ast.Value) ? { match value { ast.Quoted { mut v := &(value as ast.Quoted) - d.decode_quoted(mut v) ? + d.decode_quoted(mut v)? } ast.Number { mut v := &(value as ast.Number) - d.decode_number(mut v) ? + d.decode_number(mut v)? } ast.DateTime { mut v := &(value as ast.DateTime) - d.decode_date_time(mut v) ? + d.decode_date_time(mut v)? } else {} } @@ -49,7 +49,7 @@ fn (d Decoder) excerpt(tp token.Pos) string { // decode_quoted returns an error if `q` is not a valid quoted TOML string. fn (d Decoder) decode_quoted(mut q ast.Quoted) ? { - decode_quoted_escapes(mut q) ? + decode_quoted_escapes(mut q)? } // decode_number decodes the `n ast.Number` into valid TOML. @@ -84,7 +84,7 @@ pub fn decode_quoted_escapes(mut q ast.Quoted) ? { return } - mut s := scanner.new_simple_text(q.text) ? + mut s := scanner.new_simple_text(q.text)? q.text = q.text.replace('\\"', '"') for { @@ -226,7 +226,7 @@ fn decode_unicode_escape(esc_unicode string) ?(string, int, int) { if unicode_point.len < 8 { unicode_point = '0'.repeat(8 - unicode_point.len) + unicode_point } - i64_val := strconv.parse_int(unicode_point, 16, 0) ? + i64_val := strconv.parse_int(unicode_point, 16, 0)? rn := rune(i64_val) return '$rn', int(i64_val), sequence_len } diff --git a/vlib/toml/input/input.v b/vlib/toml/input/input.v index cdce8227c1..8f783ca6c0 100644 --- a/vlib/toml/input/input.v +++ b/vlib/toml/input/input.v @@ -30,7 +30,7 @@ pub fn auto_config(toml string) ?Config { text: toml } } - config.validate() ? + config.validate()? return config } @@ -49,7 +49,7 @@ fn (c Config) validate() ? { // read_input returns either Config.text or the read file contents of Config.file_path // depending on which one is not empty. pub fn (c Config) read_input() ?string { - c.validate() ? + c.validate()? mut text := c.text if text == '' && os.is_file(c.file_path) { text = os.read_file(c.file_path) or { diff --git a/vlib/toml/parser/parser.v b/vlib/toml/parser/parser.v index ccfabab2f7..38c95f9b3d 100644 --- a/vlib/toml/parser/parser.v +++ b/vlib/toml/parser/parser.v @@ -91,8 +91,8 @@ pub fn new_parser(config Config) Parser { // init initializes the parser. pub fn (mut p Parser) init() ? { p.root_map = map[string]ast.Value{} - p.tokens << p.scanner.scan() ? - p.next() ? + p.tokens << p.scanner.scan()? + p.next()? } // run_checker validates the parsed `ast.Value` nodes in the @@ -102,9 +102,9 @@ fn (mut p Parser) run_checker() ? { chckr := checker.Checker{ scanner: p.scanner } - chckr.check(p.root_map) ? + chckr.check(p.root_map)? for comment in p.ast_root.comments { - chckr.check_comment(comment) ? + chckr.check_comment(comment)? } } } @@ -116,17 +116,17 @@ fn (mut p Parser) run_decoder() ? { dcoder := decoder.Decoder{ scanner: p.scanner } - dcoder.decode(mut p.root_map) ? + dcoder.decode(mut p.root_map)? } } // parse starts parsing the input and returns the root // of the generated AST. pub fn (mut p Parser) parse() ?&ast.Root { - p.init() ? - p.root_table() ? - p.run_checker() ? - p.run_decoder() ? + p.init()? + p.root_table()? + p.run_checker()? + p.run_decoder()? p.ast_root.table = p.root_map return p.ast_root } @@ -138,9 +138,9 @@ fn (mut p Parser) next() ? { if p.tokens.len > 0 { p.peek_tok = p.tokens.first() p.tokens.delete(0) - p.peek(1) ? + p.peek(1)? } else { - p.peek(1) ? + p.peek(1)? p.peek_tok = p.tokens.first() p.tokens.delete(0) } @@ -163,7 +163,7 @@ fn (mut p Parser) peek(n int) ?token.Token { mut count := n - p.tokens.len util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'buffering $count tokens...') for token.kind != .eof && count != 0 { - token = p.scanner.scan() ? + token = p.scanner.scan()? p.tokens << token count-- } @@ -176,7 +176,7 @@ fn (mut p Parser) peek(n int) ?token.Token { // token's `Kind` is equal that of `check_token`. fn (mut p Parser) check(check_token token.Kind) ? { if p.tok.kind == check_token { - p.next() ? + p.next()? } else { return error(@MOD + '.' + @STRUCT + '.' + @FN + ' expected token "$check_token" but found "$p.tok.kind" in this (excerpt): "...${p.excerpt()}..."') @@ -187,9 +187,9 @@ fn (mut p Parser) check(check_token token.Kind) ? { // and return an error if the next token is not one of [.cr, .nl, .hash, .eof]. fn (mut p Parser) peek_for_correct_line_ending_or_fail() ? { // Disallow anything else than [.cr, .nl, .hash, .eof] after any space formatting. - peek_tok, _ := p.peek_over(1, parser.space_formatting) ? + peek_tok, _ := p.peek_over(1, parser.space_formatting)? if peek_tok.kind !in [.cr, .nl, .hash, .eof] { - p.next() ? // Forward to the peek_tok + p.next()? // Forward to the peek_tok return error(@MOD + '.' + @STRUCT + '.' + @FN + ' unexpected EOL "$p.tok.kind" "$p.tok.lit" expected one of [.cr, .nl, .hash, .eof] at this (excerpt): "...${p.excerpt()}..."') } @@ -199,7 +199,7 @@ fn (mut p Parser) peek_for_correct_line_ending_or_fail() ? { // token's `Kind` can be found in `tokens`. Otherwise it returns an error. fn (mut p Parser) check_one_of(tokens []token.Kind) ? { if p.tok.kind in tokens { - p.next() ? + p.next()? } else { return error(@MOD + '.' + @STRUCT + '.' + @FN + ' expected one of $tokens but found "$p.tok.kind" in this (excerpt): "...${p.excerpt()}..."') @@ -239,7 +239,7 @@ fn (mut p Parser) peek_over(i int, tokens []token.Kind) ?(token.Token, int) { // token is found in `tokens`. mut peek_i := i for peek_tok.kind in tokens { - peek_tok = p.peek(peek_i) ? + peek_tok = p.peek(peek_i)? peek_i++ } return peek_tok, peek_i @@ -324,7 +324,7 @@ pub fn (mut p Parser) allocate_table(key DottedKey) ? { if key.len == 0 { return } - p.allocate_in_table(mut t, key) ? + p.allocate_in_table(mut t, key)? } // sub_table_key returns the logic parts of a dotted key (`a.b.c`) for @@ -439,18 +439,18 @@ pub fn (mut p Parser) allocate_in_table(mut table map[string]ast.Value, key Dott pub fn (mut p Parser) dotted_key() ?DottedKey { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing dotted key...') mut dotted_key := DottedKey([]string{}) - key := p.key() ? + key := p.key()? p.ignore_while_peek(parser.space_formatting) dotted_key << key.str() for p.peek_tok.kind == .period { - p.next() ? // . - p.check(.period) ? + p.next()? // . + p.check(.period)? p.ignore_while(parser.space_formatting) - next_key := p.key() ? + next_key := p.key()? dotted_key << next_key.text p.ignore_while_peek(parser.space_formatting) } - p.next() ? + p.next()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsed dotted key `$dotted_key` now at "$p.tok.kind" "$p.tok.lit"') return dotted_key } @@ -462,7 +462,7 @@ pub fn (mut p Parser) root_table() ? { for p.tok.kind != .eof { if !p.skip_next { - p.next() ? + p.next()? } else { p.skip_next = false } @@ -480,10 +480,10 @@ pub fn (mut p Parser) root_table() ? { } .bare, .quoted, .number, .minus, .underscore { // Peek forward as far as we can skipping over space formatting tokens. - peek_tok, _ := p.peek_over(1, parser.keys_and_space_formatting) ? + peek_tok, _ := p.peek_over(1, parser.keys_and_space_formatting)? if peek_tok.kind == .period { - dotted_key, val := p.dotted_key_value() ? + dotted_key, val := p.dotted_key_value()? sub_table, key := p.sub_table_key(dotted_key) @@ -518,16 +518,16 @@ pub fn (mut p Parser) root_table() ? { p.implicit_declared << abs_dotted_key } - t := p.find_sub_table(sub_table) ? + t := p.find_sub_table(sub_table)? unsafe { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'setting "$key" = $val in table ${ptr_str(t)}') t[key.str()] = val } } else { p.ignore_while(parser.space_formatting) - key, val := p.key_value() ? + key, val := p.key_value()? - t := p.find_table() ? + t := p.find_table()? unsafe { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'setting "$key.str()" = $val in table ${ptr_str(t)}') key_str := key.str() @@ -538,15 +538,15 @@ pub fn (mut p Parser) root_table() ? { t[key_str] = val } } - p.peek_for_correct_line_ending_or_fail() ? + p.peek_for_correct_line_ending_or_fail()? } .lsbr { - p.check(.lsbr) ? // '[' bracket + p.check(.lsbr)? // '[' bracket mut peek_tok := p.peek_tok // Disallow `[ [table]]` if p.tok.kind in parser.space_formatting { - peek_tok, _ = p.peek_over(1, parser.space_formatting) ? + peek_tok, _ = p.peek_over(1, parser.space_formatting)? if peek_tok.kind == .lsbr { return error(@MOD + '.' + @STRUCT + '.' + @FN + ' unexpected "$p.tok.kind" "$p.tok.lit" at this (excerpt): "...${p.excerpt()}..."') @@ -557,16 +557,16 @@ pub fn (mut p Parser) root_table() ? { p.ignore_while(parser.space_formatting) // Peek forward as far as we can skipping over space formatting tokens. - peek_tok, _ = p.peek_over(1, parser.keys_and_space_formatting) ? + peek_tok, _ = p.peek_over(1, parser.keys_and_space_formatting)? if p.tok.kind == .lsbr { // Parse `[[table]]` - p.array_of_tables(mut &p.root_map) ? + p.array_of_tables(mut &p.root_map)? p.skip_next = true // skip calling p.next() in coming iteration util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'leaving double bracket at "$p.tok.kind" "$p.tok.lit". NEXT is "$p.peek_tok.kind "$p.peek_tok.lit"') } else if peek_tok.kind == .period { // Parse `[d.e.f]` - dotted_key := p.dotted_key() ? + dotted_key := p.dotted_key()? // So apparently TOML is a *very* key context sensitive language... // [[table]] <- parsed previously @@ -579,14 +579,14 @@ pub fn (mut p Parser) root_table() ? { if p.last_aot.len == 1 && dotted_key.len > 1 && dotted_key[0] == p.last_aot.str() { // Disallow re-declaring the key - p.check_explicitly_declared_array_of_tables(dotted_key) ? - p.check(.rsbr) ? + p.check_explicitly_declared_array_of_tables(dotted_key)? + p.check(.rsbr)? p.ignore_while(parser.space_formatting) - arr := p.find_array_of_tables() ? + arr := p.find_array_of_tables()? if val := arr[p.last_aot_index] { if val is map[string]ast.Value { mut m := map[string]ast.Value{} - p.table_contents(mut m) ? + p.table_contents(mut m)? unsafe { mut mut_val := &val if dotted_key.len == 2 { @@ -598,7 +598,7 @@ pub fn (mut p Parser) root_table() ? { dotted_key_copy.delete(0) new_key := todo_msvc_astring2dkey(dotted_key_copy) sub_table, key := p.sub_table_key(new_key) - t := p.find_in_table(mut mut_val, sub_table) ? + t := p.find_in_table(mut mut_val, sub_table)? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'setting "$key" = $val in table ${ptr_str(t)}') t[new_key.last().str()] = m @@ -613,25 +613,25 @@ pub fn (mut p Parser) root_table() ? { } // Disallow re-declaring the key - p.check_explicitly_declared(dotted_key) ? + p.check_explicitly_declared(dotted_key)? p.explicit_declared << dotted_key // ... also check implicitly declared keys - p.check_implicitly_declared(dotted_key) ? + p.check_implicitly_declared(dotted_key)? p.ignore_while(parser.space_formatting) util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'setting root map key to `$dotted_key` at "$p.tok.kind" "$p.tok.lit"') p.root_map_key = dotted_key - p.allocate_table(p.root_map_key) ? - p.expect(.rsbr) ? - p.peek_for_correct_line_ending_or_fail() ? + p.allocate_table(p.root_map_key)? + p.expect(.rsbr)? + p.peek_for_correct_line_ending_or_fail()? } else { // Parse `[key]` - key := p.key() ? + key := p.key()? dotted_key := DottedKey([key.str()]) // Disallow re-declaring the key - p.check_explicitly_declared(dotted_key) ? + p.check_explicitly_declared(dotted_key)? p.explicit_declared << dotted_key // Check for footgun redeclaration in this odd way: @@ -647,10 +647,10 @@ pub fn (mut p Parser) root_table() ? { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'setting root map key to `$dotted_key` at "$p.tok.kind" "$p.tok.lit"') p.root_map_key = dotted_key - p.allocate_table(p.root_map_key) ? - p.next() ? - p.expect(.rsbr) ? - p.peek_for_correct_line_ending_or_fail() ? + p.allocate_table(p.root_map_key)? + p.next()? + p.expect(.rsbr)? + p.peek_for_correct_line_ending_or_fail()? } } .eof { @@ -679,7 +679,7 @@ pub fn (mut p Parser) table_contents(mut tbl map[string]ast.Value) ? { return } if !p.skip_next { - p.next() ? + p.next()? } else { p.skip_next = false } @@ -697,21 +697,21 @@ pub fn (mut p Parser) table_contents(mut tbl map[string]ast.Value) ? { } .bare, .quoted, .number, .minus, .underscore { // Peek forward as far as we can skipping over space formatting tokens. - peek_tok, _ := p.peek_over(1, parser.keys_and_space_formatting) ? + peek_tok, _ := p.peek_over(1, parser.keys_and_space_formatting)? if peek_tok.kind == .period { - dotted_key, val := p.dotted_key_value() ? + dotted_key, val := p.dotted_key_value()? sub_table, key := p.sub_table_key(dotted_key) - t := p.find_in_table(mut tbl, sub_table) ? + t := p.find_in_table(mut tbl, sub_table)? unsafe { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'setting "$key" = $val in table ${ptr_str(t)}') t[key.str()] = val } } else { p.ignore_while(parser.space_formatting) - key, val := p.key_value() ? + key, val := p.key_value()? unsafe { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'setting "$key.str()" = $val in table ${ptr_str(tbl)}') @@ -723,7 +723,7 @@ pub fn (mut p Parser) table_contents(mut tbl map[string]ast.Value) ? { tbl[key_str] = val } } - p.peek_for_correct_line_ending_or_fail() ? + p.peek_for_correct_line_ending_or_fail()? } .eof { break @@ -743,13 +743,13 @@ pub fn (mut p Parser) inline_table(mut tbl map[string]ast.Value) ? { mut previous_token_was_value := false for p.tok.kind != .eof { - p.next() ? + p.next()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing token "$p.tok.kind"') if previous_token_was_value { p.ignore_while(parser.space_formatting) if p.tok.kind != .rcbr { - p.expect(.comma) ? + p.expect(.comma)? } previous_token_was_value = false } @@ -767,7 +767,7 @@ pub fn (mut p Parser) inline_table(mut tbl map[string]ast.Value) ? { .comma { p.ignore_while_peek(parser.space_formatting) if p.peek_tok.kind in [.comma, .rcbr] { - p.next() ? // Forward to the peek_tok + p.next()? // Forward to the peek_tok return error(@MOD + '.' + @STRUCT + '.' + @FN + ' unexpected "$p.tok.kind" "$p.tok.lit" at this (excerpt): "...${p.excerpt()}..."') } @@ -780,21 +780,21 @@ pub fn (mut p Parser) inline_table(mut tbl map[string]ast.Value) ? { } .bare, .quoted, .number, .minus, .underscore { // Peek forward as far as we can skipping over space formatting tokens. - peek_tok, _ := p.peek_over(1, parser.space_formatting) ? + peek_tok, _ := p.peek_over(1, parser.space_formatting)? if peek_tok.kind == .period { - dotted_key, val := p.dotted_key_value() ? + dotted_key, val := p.dotted_key_value()? sub_table, key := p.sub_table_key(dotted_key) - mut t := p.find_in_table(mut tbl, sub_table) ? + mut t := p.find_in_table(mut tbl, sub_table)? unsafe { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'inserting @6 "$key" = $val into ${ptr_str(t)}') t[key.str()] = val } } else { p.ignore_while(parser.space_formatting) - key, val := p.key_value() ? + key, val := p.key_value()? key_str := key.str() if _ := tbl[key_str] { return error(@MOD + '.' + @STRUCT + '.' + @FN + @@ -820,28 +820,28 @@ pub fn (mut p Parser) inline_table(mut tbl map[string]ast.Value) ? { pub fn (mut p Parser) array_of_tables(mut table map[string]ast.Value) ? { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing array of tables "$p.tok.kind" "$p.tok.lit"') // NOTE this is starting to get ugly. TOML isn't simple at this point - p.check(.lsbr) ? // '[' bracket + p.check(.lsbr)? // '[' bracket // Allow [[ key]] p.ignore_while(parser.space_formatting) - peek_tok, _ := p.peek_over(1, parser.space_formatting) ? + peek_tok, _ := p.peek_over(1, parser.space_formatting)? p.ignore_while(parser.space_formatting) // [[key.key]] horror if peek_tok.kind == .period { - p.double_array_of_tables(mut table) ? + p.double_array_of_tables(mut table)? return } - key := p.key() ? - p.next() ? + key := p.key()? + p.next()? // Allow [[key ]] p.ignore_while(parser.space_formatting) - p.check(.rsbr) ? - p.peek_for_correct_line_ending_or_fail() ? - p.expect(.rsbr) ? + p.check(.rsbr)? + p.peek_for_correct_line_ending_or_fail()? + p.expect(.rsbr)? p.ignore_while(parser.all_formatting) @@ -849,20 +849,20 @@ pub fn (mut p Parser) array_of_tables(mut table map[string]ast.Value) ? { dotted_key_str := dotted_key.str() // Disallow re-declaring the key - p.check_explicitly_declared(dotted_key) ? + p.check_explicitly_declared(dotted_key)? unsafe { if val := table[dotted_key_str] { if val is []ast.Value { arr := &(table[dotted_key_str] as []ast.Value) - arr << p.array_of_tables_contents() ? + arr << p.array_of_tables_contents()? table[dotted_key_str] = arr } else { return error(@MOD + '.' + @STRUCT + '.' + @FN + ' table[$dotted_key_str] is not an array. (excerpt): "...${p.excerpt()}..."') } } else { - table[dotted_key_str] = p.array_of_tables_contents() ? + table[dotted_key_str] = p.array_of_tables_contents()? } } p.last_aot = dotted_key @@ -878,7 +878,7 @@ pub fn (mut p Parser) array_of_tables_contents() ?[]ast.Value { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing contents from "$p.tok.kind" "$p.tok.lit"') mut tbl := map[string]ast.Value{} - p.table_contents(mut tbl) ? + p.table_contents(mut tbl)? mut arr := []ast.Value{} arr << tbl @@ -890,11 +890,11 @@ pub fn (mut p Parser) array_of_tables_contents() ?[]ast.Value { pub fn (mut p Parser) double_array_of_tables(mut table map[string]ast.Value) ? { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing nested array of tables "$p.tok.kind" "$p.tok.lit"') - dotted_key := p.dotted_key() ? + dotted_key := p.dotted_key()? p.ignore_while(parser.space_formatting) - p.check(.rsbr) ? - p.expect(.rsbr) ? + p.check(.rsbr)? + p.expect(.rsbr)? p.ignore_while(parser.all_formatting) @@ -903,7 +903,7 @@ pub fn (mut p Parser) double_array_of_tables(mut table map[string]ast.Value) ? { ' nested array of tables does not support more than 2 levels. (excerpt): "...${p.excerpt()}..."') } - p.check_explicitly_declared(dotted_key) ? + p.check_explicitly_declared(dotted_key)? if !p.explicit_declared_array_of_tables.has(dotted_key) { p.explicit_declared_array_of_tables << dotted_key @@ -939,7 +939,7 @@ pub fn (mut p Parser) double_array_of_tables(mut table map[string]ast.Value) ? { table[first.str()] = ast.Value(nm) t_arr = &(nm[last.str()] as []ast.Value) - t_arr << p.array_of_tables_contents() ? + t_arr << p.array_of_tables_contents()? return } else { return error(@MOD + '.' + @STRUCT + '.' + @FN + @@ -958,14 +958,14 @@ pub fn (mut p Parser) double_array_of_tables(mut table map[string]ast.Value) ? { if val := t[last.str()] { if val is []ast.Value { arr := &(val as []ast.Value) - arr << p.double_array_of_tables_contents(dotted_key) ? + arr << p.double_array_of_tables_contents(dotted_key)? t[last.str()] = arr } else { return error(@MOD + '.' + @STRUCT + '.' + @FN + ' t[$last.str()] is not an array. (excerpt): "...${p.excerpt()}..."') } } else { - t[last.str()] = p.double_array_of_tables_contents(dotted_key) ? + t[last.str()] = p.double_array_of_tables_contents(dotted_key)? } if t_arr.len == 0 { t_arr << t @@ -984,15 +984,15 @@ pub fn (mut p Parser) double_array_of_tables_contents(target_key DottedKey) ?[]a mut peek_tok := p.peek_tok for p.tok.kind != .eof { - p.next() ? + p.next()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing token "$p.tok.kind"') p.ignore_while(parser.all_formatting) // Peek forward as far as we can skipping over space formatting tokens. - peek_tok, peeked_over = p.peek_over(1, parser.space_formatting) ? + peek_tok, peeked_over = p.peek_over(1, parser.space_formatting)? // Peek for occurrence of `[[` if peek_tok.kind == .lsbr { - peek_tok, peeked_over = p.peek_over(peeked_over + 1, parser.space_formatting) ? + peek_tok, peeked_over = p.peek_over(peeked_over + 1, parser.space_formatting)? if peek_tok.kind == .lsbr { mut arr := []ast.Value{} arr << tbl @@ -1003,27 +1003,27 @@ pub fn (mut p Parser) double_array_of_tables_contents(target_key DottedKey) ?[]a match p.tok.kind { .bare, .quoted, .number, .minus, .underscore { // Peek forward as far as we can skipping over space formatting tokens. - peek_tok, _ = p.peek_over(1, parser.space_formatting) ? + peek_tok, _ = p.peek_over(1, parser.space_formatting)? if peek_tok.kind == .period { - mut dotted_key, val := p.dotted_key_value() ? + mut dotted_key, val := p.dotted_key_value()? if implicit_allocation_key.len > 0 { dotted_key.insert(0, implicit_allocation_key) } sub_table, key := p.sub_table_key(dotted_key) - mut t := p.find_in_table(mut tbl, sub_table) ? + mut t := p.find_in_table(mut tbl, sub_table)? unsafe { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'inserting @6 "$key" = $val into ${ptr_str(t)}') t[key.str()] = val } } else { - key, val := p.key_value() ? + key, val := p.key_value()? mut t := unsafe { &tbl } if implicit_allocation_key.len > 0 { - t = p.find_in_table(mut tbl, implicit_allocation_key) ? + t = p.find_in_table(mut tbl, implicit_allocation_key)? } unsafe { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'inserting @7 "$key" = $val into ${ptr_str(t)}') @@ -1032,27 +1032,27 @@ pub fn (mut p Parser) double_array_of_tables_contents(target_key DottedKey) ?[]a } } .lsbr { - p.check(.lsbr) ? // '[' bracket + p.check(.lsbr)? // '[' bracket peek_tok = p.peek_tok // Allow `[ d.e.f]` p.ignore_while(parser.space_formatting) // Peek forward as far as we can skipping over space formatting tokens. - peek_tok, _ = p.peek_over(1, parser.space_formatting) ? + peek_tok, _ = p.peek_over(1, parser.space_formatting)? if peek_tok.kind == .period { // Parse `[d.e.f]` p.ignore_while(parser.space_formatting) - dotted_key := p.dotted_key() ? + dotted_key := p.dotted_key()? implicit_allocation_key = dotted_key if dotted_key.len > 2 { implicit_allocation_key = dotted_key[2..] } p.ignore_while(parser.space_formatting) util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'keys are: dotted `$dotted_key`, target `$target_key`, implicit `$implicit_allocation_key` at "$p.tok.kind" "$p.tok.lit"') - p.expect(.rsbr) ? - p.peek_for_correct_line_ending_or_fail() ? + p.expect(.rsbr)? + p.peek_for_correct_line_ending_or_fail()? p.explicit_declared << dotted_key continue } else { @@ -1075,23 +1075,23 @@ pub fn (mut p Parser) double_array_of_tables_contents(target_key DottedKey) ?[]a pub fn (mut p Parser) array() ?[]ast.Value { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing array...') mut arr := []ast.Value{} - p.expect(.lsbr) ? // '[' bracket + p.expect(.lsbr)? // '[' bracket mut previous_token_was_value := false for p.tok.kind != .eof { - p.next() ? + p.next()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing token "$p.tok.kind" "$p.tok.lit"') if previous_token_was_value { p.ignore_while(parser.all_formatting) if p.tok.kind != .rsbr && p.tok.kind != .hash { - p.expect(.comma) ? + p.expect(.comma)? } previous_token_was_value = false } match p.tok.kind { .boolean { - arr << ast.Value(p.boolean() ?) + arr << ast.Value(p.boolean()?) previous_token_was_value = true } .comma { @@ -1101,7 +1101,7 @@ pub fn (mut p Parser) array() ?[]ast.Value { // Check for known errors: if p.peek_tok.kind in [.comma, .bare] { - p.next() ? // Forward to the peek_tok + p.next()? // Forward to the peek_tok return error(@MOD + '.' + @STRUCT + '.' + @FN + ' unexpected "$p.tok.kind" "$p.tok.lit" at this (excerpt): "...${p.excerpt()}..."') } @@ -1120,12 +1120,12 @@ pub fn (mut p Parser) array() ?[]ast.Value { .lcbr { p.ignore_while(parser.space_formatting) mut t := map[string]ast.Value{} - p.inline_table(mut t) ? + p.inline_table(mut t)? arr << ast.Value(t) previous_token_was_value = true } .number { - val := p.number_or_date() ? + val := p.number_or_date()? arr << val previous_token_was_value = true } @@ -1135,7 +1135,7 @@ pub fn (mut p Parser) array() ?[]ast.Value { } .lsbr { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing array in array "$p.tok.kind" "$p.tok.lit"') - arr << ast.Value(p.array() ?) + arr << ast.Value(p.array()?) previous_token_was_value = true } .rsbr { @@ -1147,7 +1147,7 @@ pub fn (mut p Parser) array() ?[]ast.Value { } } } - p.expect(.rsbr) ? // ']' bracket + p.expect(.rsbr)? // ']' bracket $if debug { flat := arr.str().replace('\n', r'\n') util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsed array: $flat . Currently @ token "$p.tok.kind"') @@ -1175,7 +1175,7 @@ pub fn (mut p Parser) key() ?ast.Key { mut lits := p.tok.lit pos := p.tok.pos() for p.peek_tok.kind != .assign && p.peek_tok.kind != .period && p.peek_tok.kind != .rsbr { - p.next() ? + p.next()? if p.tok.kind !in parser.space_formatting { lits += p.tok.lit } @@ -1189,10 +1189,10 @@ pub fn (mut p Parser) key() ?ast.Key { } else { key = match p.tok.kind { .bare, .underscore, .minus { - ast.Key(p.bare() ?) + ast.Key(p.bare()?) } .boolean { - ast.Key(p.boolean() ?) + ast.Key(p.boolean()?) } .quoted { ast.Key(p.quoted()) @@ -1226,11 +1226,11 @@ pub fn (mut p Parser) key() ?ast.Key { chckr := checker.Checker{ scanner: p.scanner } - chckr.check_quoted(quoted) ? + chckr.check_quoted(quoted)? } if p.config.decode_values { mut quoted := key as ast.Quoted - decoder.decode_quoted_escapes(mut quoted) ? + decoder.decode_quoted_escapes(mut quoted)? key = ast.Key(quoted) } } @@ -1242,12 +1242,12 @@ pub fn (mut p Parser) key() ?ast.Key { // see also `key()` and `value()` pub fn (mut p Parser) key_value() ?(ast.Key, ast.Value) { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing key value pair...') - key := p.key() ? - p.next() ? + key := p.key()? + p.next()? p.ignore_while(parser.space_formatting) - p.check(.assign) ? // Assignment operator + p.check(.assign)? // Assignment operator p.ignore_while(parser.space_formatting) - value := p.value() ? + value := p.value()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsed key value pair. `$key = $value`') p.explicit_declared << p.build_abs_dotted_key(DottedKey([ @@ -1262,11 +1262,11 @@ pub fn (mut p Parser) key_value() ?(ast.Key, ast.Value) { pub fn (mut p Parser) dotted_key_value() ?(DottedKey, ast.Value) { util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsing dotted key value pair...') p.ignore_while(parser.space_formatting) - dotted_key := p.dotted_key() ? + dotted_key := p.dotted_key()? p.ignore_while(parser.space_formatting) - p.check(.assign) ? + p.check(.assign)? p.ignore_while(parser.space_formatting) - value := p.value() ? + value := p.value()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsed dotted key value pair `$dotted_key = $value`...') p.explicit_declared << p.build_abs_dotted_key(dotted_key) @@ -1281,7 +1281,7 @@ pub fn (mut p Parser) value() ?ast.Value { mut value := ast.Value(ast.Null{}) if p.tok.kind == .number { - number_or_date := p.number_or_date() ? + number_or_date := p.number_or_date()? value = number_or_date } else { value = match p.tok.kind { @@ -1289,15 +1289,15 @@ pub fn (mut p Parser) value() ?ast.Value { ast.Value(p.quoted()) } .boolean { - ast.Value(p.boolean() ?) + ast.Value(p.boolean()?) } .lsbr { - ast.Value(p.array() ?) + ast.Value(p.array()?) } .lcbr { p.ignore_while(parser.space_formatting) mut t := map[string]ast.Value{} - p.inline_table(mut t) ? + p.inline_table(mut t)? ast.Value(t) } else { @@ -1318,7 +1318,7 @@ pub fn (mut p Parser) value() ?ast.Value { pub fn (mut p Parser) number_or_date() ?ast.Value { // Handle Date/Time if p.peek_tok.kind == .minus || p.peek_tok.kind == .colon { - date_time_type := p.date_time() ? + date_time_type := p.date_time()? match date_time_type { ast.Date { return ast.Value(date_time_type as ast.Date) @@ -1340,7 +1340,7 @@ pub fn (mut p Parser) bare() ?ast.Bare { pos := p.tok.pos() for p.peek_tok.kind != .assign && p.peek_tok.kind != .period && p.peek_tok.kind != .rsbr && p.peek_tok.kind !in parser.space_formatting { - p.next() ? + p.next()? if p.tok.kind == .bare || p.tok.kind == .minus || p.tok.kind == .underscore { lits += p.tok.lit continue @@ -1409,19 +1409,19 @@ pub fn (mut p Parser) date_time() ?ast.DateTimeType { mut time := ast.Time{} if p.peek_tok.kind == .minus { - date = p.date() ? + date = p.date()? lit += date.text // Look for any THH:MM:SS or HH:MM:SS if (p.peek_tok.kind == .bare && (p.peek_tok.lit.starts_with('T') || p.peek_tok.lit.starts_with('t'))) || p.peek_tok.kind == .whitespace { - p.next() ? // Advance to token with Txx or whitespace special case + p.next()? // Advance to token with Txx or whitespace special case if p.tok.lit.starts_with('T') || p.tok.lit.starts_with('t') { lit += p.tok.lit[0].ascii_str() //'T' or 't' } else { lit += p.tok.lit - p.next() ? + p.next()? } - time = p.time() ? + time = p.time()? lit += time.text util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsed date-time: "$lit"') @@ -1433,7 +1433,7 @@ pub fn (mut p Parser) date_time() ?ast.DateTimeType { } } } else if p.peek_tok.kind == .colon { - time = p.time() ? + time = p.time()? return time } @@ -1449,15 +1449,15 @@ pub fn (mut p Parser) date() ?ast.Date { mut lit := p.tok.lit pos := p.tok.pos() - p.check(.number) ? + p.check(.number)? lit += p.tok.lit - p.check(.minus) ? + p.check(.minus)? lit += p.tok.lit - p.check(.number) ? + p.check(.number)? lit += p.tok.lit - p.check(.minus) ? + p.check(.minus)? lit += p.tok.lit - p.expect(.number) ? + p.expect(.number)? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsed date: "$lit"') return ast.Date{ @@ -1478,46 +1478,46 @@ pub fn (mut p Parser) time() ?ast.Time { } else if p.tok.lit.starts_with('t') { lit = lit.all_after('t') } - p.next() ? + p.next()? } else { - p.check(.number) ? + p.check(.number)? } lit += p.tok.lit - p.check(.colon) ? + p.check(.colon)? lit += p.tok.lit - p.check(.number) ? + p.check(.number)? lit += p.tok.lit // TODO does TOML even have optional seconds? // if p.peek_tok.kind == .colon { - p.check(.colon) ? + p.check(.colon)? lit += p.tok.lit - p.expect(.number) ? + p.expect(.number)? //} // Optional milliseconds if p.peek_tok.kind == .period { - p.next() ? + p.next()? lit += p.tok.lit // lit += '.' - p.check(.period) ? + p.check(.period)? lit += p.tok.lit - p.expect(.number) ? + p.expect(.number)? } // Parse offset if p.peek_tok.kind == .minus || p.peek_tok.kind == .plus { - p.next() ? + p.next()? lit += p.tok.lit // lit += '-' - p.check_one_of([.minus, .plus]) ? + p.check_one_of([.minus, .plus])? lit += p.tok.lit - p.check(.number) ? + p.check(.number)? lit += p.tok.lit - p.check(.colon) ? + p.check(.colon)? lit += p.tok.lit - p.expect(.number) ? + p.expect(.number)? } else if p.peek_tok.kind == .bare && (p.peek_tok.lit == 'Z' || p.peek_tok.lit == 'z') { - p.next() ? + p.next()? lit += p.tok.lit - p.expect(.bare) ? + p.expect(.bare)? } util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'parsed time: "$lit"') diff --git a/vlib/toml/scanner/scanner.v b/vlib/toml/scanner/scanner.v index 394a64058a..91c05884a9 100644 --- a/vlib/toml/scanner/scanner.v +++ b/vlib/toml/scanner/scanner.v @@ -50,7 +50,7 @@ pub: pub fn new_scanner(config Config) ?&Scanner { mut s := &Scanner{ config: config - text: config.input.read_input() ? + text: config.input.read_input()? } return s } @@ -59,7 +59,7 @@ pub fn new_scanner(config Config) ?&Scanner { pub fn new_simple(config Config) ?Scanner { return Scanner{ config: config - text: config.input.read_input() ? + text: config.input.read_input()? } } @@ -74,7 +74,7 @@ pub fn new_simple_text(text string) ?Scanner { } return Scanner{ config: config - text: config.input.read_input() ? + text: config.input.read_input()? } } @@ -89,14 +89,14 @@ pub fn new_simple_file(path string) ?Scanner { } return Scanner{ config: config - text: config.input.read_input() ? + text: config.input.read_input()? } } // scan returns the next token from the input. [direct_array_access] pub fn (mut s Scanner) scan() ?token.Token { - s.validate_and_skip_headers() ? + s.validate_and_skip_headers()? for { c := s.next() @@ -127,7 +127,7 @@ pub fn (mut s Scanner) scan() ?token.Token { is_signed_inf := !is_signed_nan && is_sign && s.at() == `i` && peek_1 == `n` && peek_2 == `f` if !s.is_left_of_assign && (is_nan || is_inf || is_signed_nan || is_signed_inf) { - num := s.extract_nan_or_inf_number() ? + num := s.extract_nan_or_inf_number()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'identified a special number "$num" ($num.len)') return s.new_token(.number, num, num.len) } @@ -135,7 +135,7 @@ pub fn (mut s Scanner) scan() ?token.Token { is_signed_number := is_sign && u8(s.at()).is_digit() && !u8(s.peek(-1)).is_digit() is_digit := byte_c.is_digit() if is_digit || is_signed_number { - num := s.extract_number() ? + num := s.extract_number()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'identified a number "$num" ($num.len)') return s.new_token(.number, num, num.len) } @@ -197,12 +197,12 @@ pub fn (mut s Scanner) scan() ?token.Token { return s.new_token(.assign, ascii, ascii.len) } `"`, `'` { // ... some string "/' - ident_string := s.extract_string() ? + ident_string := s.extract_string()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'identified quoted string `$ident_string`') return s.new_token(.quoted, ident_string, ident_string.len) } `#` { - hash := s.ignore_line() ? + hash := s.ignore_line()? util.printdbg(@MOD + '.' + @STRUCT + '.' + @FN, 'identified comment hash "$hash" ($hash.len)') return s.new_token(.hash, hash, hash.len + 1) } @@ -410,7 +410,7 @@ fn (mut s Scanner) extract_string() ?string { is_multiline := s.text[s.pos + 1] == quote && s.text[s.pos + 2] == quote // Check for escaped multiline quote if is_multiline { - mls := s.extract_multiline_string() ? + mls := s.extract_multiline_string()? return mls } @@ -658,7 +658,7 @@ pub fn (s Scanner) state() State { fn (mut s Scanner) validate_and_skip_headers() ? { // UTF-16 / UTF-32 headers (BE/LE) - s.check_utf16_or_32_bom() ? + s.check_utf16_or_32_bom()? // NICE-TO-HAVE-TODO Check other types of (UTF-?) headers and yield an error. TOML is UTF-8 only. @@ -670,7 +670,7 @@ fn (mut s Scanner) validate_and_skip_headers() ? { } // Check after we've skipped UTF-8 BOM - s.check_utf16_or_32_bom() ? + s.check_utf16_or_32_bom()? } fn (mut s Scanner) check_utf16_or_32_bom() ? { diff --git a/vlib/toml/tests/alexcrichton.toml-rs-tests_test.v b/vlib/toml/tests/alexcrichton.toml-rs-tests_test.v index f43d790733..7c91b61d16 100644 --- a/vlib/toml/tests/alexcrichton.toml-rs-tests_test.v +++ b/vlib/toml/tests/alexcrichton.toml-rs-tests_test.v @@ -87,7 +87,7 @@ fn test_alexcrichton_toml_rs() ? { if !hide_oks { println('OK [${i + 1}/$valid_test_files.len] "$valid_test_file"...') } - toml_doc := toml.parse_file(valid_test_file) ? + toml_doc := toml.parse_file(valid_test_file)? valid++ } println('$valid/$valid_test_files.len TOML files were parsed correctly') @@ -100,12 +100,12 @@ fn test_alexcrichton_toml_rs() ? { println('Testing value output of $valid_test_files.len valid TOML files using "$jq"...') if os.exists(compare_work_dir_root) { - os.rmdir_all(compare_work_dir_root) ? + os.rmdir_all(compare_work_dir_root)? } - os.mkdir_all(compare_work_dir_root) ? + os.mkdir_all(compare_work_dir_root)? jq_normalize_path := os.join_path(compare_work_dir_root, 'normalize.jq') - os.write_file(jq_normalize_path, jq_normalize) ? + os.write_file(jq_normalize_path, jq_normalize)? valid = 0 e = 0 @@ -135,7 +135,7 @@ fn test_alexcrichton_toml_rs() ? { if !hide_oks { println('OK [${i + 1}/$valid_test_files.len] "$valid_test_file"...') } - toml_doc := toml.parse_file(valid_test_file) ? + toml_doc := toml.parse_file(valid_test_file)? v_toml_json_path := os.join_path(compare_work_dir_root, os.file_name(valid_test_file).all_before_last('.') + '.v.json') @@ -147,19 +147,19 @@ fn test_alexcrichton_toml_rs() ? { array_type = 2 } - os.write_file(v_toml_json_path, to_alexcrichton(toml_doc.ast.table, array_type)) ? + os.write_file(v_toml_json_path, to_alexcrichton(toml_doc.ast.table, array_type))? - alexcrichton_json := os.read_file(valid_test_file.all_before_last('.') + '.json') ? + alexcrichton_json := os.read_file(valid_test_file.all_before_last('.') + '.json')? - os.write_file(alexcrichton_toml_json_path, alexcrichton_json) ? + os.write_file(alexcrichton_toml_json_path, alexcrichton_json)? v_normalized_json := run([jq, '-S', '-f "$jq_normalize_path"', v_toml_json_path]) or { - contents := os.read_file(v_toml_json_path) ? + contents := os.read_file(v_toml_json_path)? panic(err.msg() + '\n$contents') } alexcrichton_normalized_json := run([jq, '-S', '-f "$jq_normalize_path"', alexcrichton_toml_json_path]) or { - contents := os.read_file(v_toml_json_path) ? + contents := os.read_file(v_toml_json_path)? panic(err.msg() + '\n$contents') } @@ -194,7 +194,7 @@ fn test_alexcrichton_toml_rs() ? { println('OK [${i + 1}/$invalid_test_files.len] "$invalid_test_file"...') } if toml_doc := toml.parse_file(invalid_test_file) { - content_that_should_have_failed := os.read_file(invalid_test_file) ? + content_that_should_have_failed := os.read_file(invalid_test_file)? println(' This TOML should have failed:\n${'-'.repeat(40)}\n$content_that_should_have_failed\n${'-'.repeat(40)}') assert false } else { diff --git a/vlib/toml/tests/array_of_tables_2_level_test.v b/vlib/toml/tests/array_of_tables_2_level_test.v index 4ad2e94837..9ce0e7bf57 100644 --- a/vlib/toml/tests/array_of_tables_2_level_test.v +++ b/vlib/toml/tests/array_of_tables_2_level_test.v @@ -25,10 +25,10 @@ name = "Born in the USA" const fprefix = os.join_path(os.dir(@FILE), 'testdata', os.file_name(@FILE).all_before_last('.')) fn test_nested_array_of_tables() ? { - mut toml_doc := toml.parse_text(toml_text) ? + mut toml_doc := toml.parse_text(toml_text)? toml_json := to.json(toml_doc) eprintln(toml_json) - assert toml_json == os.read_file(fprefix + '.out') ? + assert toml_json == os.read_file(fprefix + '.out')? } diff --git a/vlib/toml/tests/array_of_tables_edge_case_2_test.v b/vlib/toml/tests/array_of_tables_edge_case_2_test.v index 0c30e8bfc9..e611f400a9 100644 --- a/vlib/toml/tests/array_of_tables_edge_case_2_test.v +++ b/vlib/toml/tests/array_of_tables_edge_case_2_test.v @@ -5,11 +5,11 @@ import toml.to const fprefix = os.join_path(os.dir(@FILE), 'testdata', os.file_name(@FILE).all_before_last('.')) fn test_array_of_tables_edge_case_file() ? { - toml_doc := toml.parse_file(os.real_path(fprefix + '.toml')) ? + toml_doc := toml.parse_file(os.real_path(fprefix + '.toml'))? toml_json := to.json(toml_doc) - out_file_json := os.read_file(os.real_path(fprefix + '.out')) ? + out_file_json := os.read_file(os.real_path(fprefix + '.out'))? println(toml_json) assert toml_json == out_file_json } diff --git a/vlib/toml/tests/burntsushi.toml-test_test.v b/vlib/toml/tests/burntsushi.toml-test_test.v index 346efa83a4..05313b1a39 100644 --- a/vlib/toml/tests/burntsushi.toml-test_test.v +++ b/vlib/toml/tests/burntsushi.toml-test_test.v @@ -82,7 +82,7 @@ fn test_burnt_sushi_tomltest() ? { if !hide_oks { println('OK [${i + 1}/$valid_test_files.len] "$valid_test_file"...') } - toml_doc := toml.parse_file(valid_test_file) ? + toml_doc := toml.parse_file(valid_test_file)? valid++ } println('$valid/$valid_test_files.len TOML files were parsed correctly') @@ -95,12 +95,12 @@ fn test_burnt_sushi_tomltest() ? { println('Testing value output of $valid_test_files.len valid TOML files using "$jq"...') if os.exists(compare_work_dir_root) { - os.rmdir_all(compare_work_dir_root) ? + os.rmdir_all(compare_work_dir_root)? } - os.mkdir_all(compare_work_dir_root) ? + os.mkdir_all(compare_work_dir_root)? jq_normalize_path := os.join_path(compare_work_dir_root, 'normalize.jq') - os.write_file(jq_normalize_path, jq_normalize) ? + os.write_file(jq_normalize_path, jq_normalize)? valid = 0 e = 0 @@ -126,25 +126,25 @@ fn test_burnt_sushi_tomltest() ? { if !hide_oks { println('OK [${i + 1}/$valid_test_files.len] "$valid_test_file"...') } - toml_doc := toml.parse_file(valid_test_file) ? + toml_doc := toml.parse_file(valid_test_file)? v_toml_json_path := os.join_path(compare_work_dir_root, os.file_name(valid_test_file).all_before_last('.') + '.v.json') bs_toml_json_path := os.join_path(compare_work_dir_root, os.file_name(valid_test_file).all_before_last('.') + '.json') - os.write_file(v_toml_json_path, to_burntsushi(toml_doc.ast.table)) ? + os.write_file(v_toml_json_path, to_burntsushi(toml_doc.ast.table))? - bs_json := os.read_file(valid_test_file.all_before_last('.') + '.json') ? + bs_json := os.read_file(valid_test_file.all_before_last('.') + '.json')? - os.write_file(bs_toml_json_path, bs_json) ? + os.write_file(bs_toml_json_path, bs_json)? v_normalized_json := run([jq, '-S', '-f "$jq_normalize_path"', v_toml_json_path]) or { - contents := os.read_file(v_toml_json_path) ? + contents := os.read_file(v_toml_json_path)? panic(err.msg() + '\n$contents') } bs_normalized_json := run([jq, '-S', '-f "$jq_normalize_path"', bs_toml_json_path]) or { - contents := os.read_file(v_toml_json_path) ? + contents := os.read_file(v_toml_json_path)? panic(err.msg() + '\n$contents') } @@ -177,7 +177,7 @@ fn test_burnt_sushi_tomltest() ? { println('OK [${i + 1}/$invalid_test_files.len] "$invalid_test_file"...') } if toml_doc := toml.parse_file(invalid_test_file) { - content_that_should_have_failed := os.read_file(invalid_test_file) ? + content_that_should_have_failed := os.read_file(invalid_test_file)? println(' This TOML should have failed:\n${'-'.repeat(40)}\n$content_that_should_have_failed\n${'-'.repeat(40)}') assert false } else { diff --git a/vlib/toml/tests/crlf_test.v b/vlib/toml/tests/crlf_test.v index 07960c9385..22dea0de46 100644 --- a/vlib/toml/tests/crlf_test.v +++ b/vlib/toml/tests/crlf_test.v @@ -16,8 +16,8 @@ fn test_crlf_is_parsable_just_like_lf() ? { crlf_content := '# a comment\r\ntitle = "TOML Example"\r\n[database]\r\nserver = "192.168.1.1"\r\nports = [ 8000, 8001, 8002 ]\r\n' all := [crlf_content, crlf_content.replace('\r\n', '\n')] for content in all { - res := toml.parse_text(content) ? + res := toml.parse_text(content)? assert res.value('title') == toml.Any('TOML Example') - assert (res.value('database') as map[string]toml.Any)['server'] ? == toml.Any('192.168.1.1') + assert (res.value('database') as map[string]toml.Any)['server']? == toml.Any('192.168.1.1') } } diff --git a/vlib/toml/tests/iarna.toml-spec-tests_test.v b/vlib/toml/tests/iarna.toml-spec-tests_test.v index cb8f1fcf26..6f7610bffd 100644 --- a/vlib/toml/tests/iarna.toml-spec-tests_test.v +++ b/vlib/toml/tests/iarna.toml-spec-tests_test.v @@ -99,7 +99,7 @@ fn test_iarna_toml_spec_tests() ? { if !hide_oks { println('OK [${i + 1}/$valid_test_files.len] "$valid_test_file"...') } - toml_doc := toml.parse_file(valid_test_file) ? + toml_doc := toml.parse_file(valid_test_file)? valid++ } println('$valid/$valid_test_files.len TOML files were parsed correctly') @@ -112,12 +112,12 @@ fn test_iarna_toml_spec_tests() ? { println('Testing value output of $valid_test_files.len valid TOML files using "$jq"...') if os.exists(compare_work_dir_root) { - os.rmdir_all(compare_work_dir_root) ? + os.rmdir_all(compare_work_dir_root)? } - os.mkdir_all(compare_work_dir_root) ? + os.mkdir_all(compare_work_dir_root)? jq_normalize_path := os.join_path(compare_work_dir_root, 'normalize.jq') - os.write_file(jq_normalize_path, jq_normalize) ? + os.write_file(jq_normalize_path, jq_normalize)? valid = 0 e = 0 @@ -177,7 +177,7 @@ fn test_iarna_toml_spec_tests() ? { run([python, '-c', "'import sys, yaml, json; json.dump(yaml.load(sys.stdin, Loader=yaml.FullLoader), sys.stdout, indent=4)'", '<', iarna_yaml_path, '>', converted_json_path]) or { - contents := os.read_file(iarna_yaml_path) ? + contents := os.read_file(iarna_yaml_path)? // NOTE there's known errors with the python convertion method. // For now we just ignore them as it's a broken tool - not a wrong test-case. // Uncomment this print to see/check them. @@ -193,26 +193,26 @@ fn test_iarna_toml_spec_tests() ? { if !hide_oks { println('OK [${i + 1}/$valid_test_files.len] "$valid_test_file"...') } - toml_doc := toml.parse_file(valid_test_file) ? + toml_doc := toml.parse_file(valid_test_file)? v_toml_json_path := os.join_path(compare_work_dir_root, '${valid_test_file_name}.v.json') iarna_toml_json_path := os.join_path(compare_work_dir_root, '${valid_test_file_name}.json') - os.write_file(v_toml_json_path, to_iarna(toml_doc.ast.table, converted_from_yaml)) ? + os.write_file(v_toml_json_path, to_iarna(toml_doc.ast.table, converted_from_yaml))? if converted_json_path == '' { converted_json_path = valid_test_file.all_before_last('.') + '.json' } - iarna_json := os.read_file(converted_json_path) ? - os.write_file(iarna_toml_json_path, iarna_json) ? + iarna_json := os.read_file(converted_json_path)? + os.write_file(iarna_toml_json_path, iarna_json)? v_normalized_json := run([jq, '-S', '-f "$jq_normalize_path"', v_toml_json_path]) or { - contents := os.read_file(v_toml_json_path) ? + contents := os.read_file(v_toml_json_path)? panic(err.msg() + '\n$contents') } cmd := [jq, '-S', '-f "$jq_normalize_path"', iarna_toml_json_path] iarna_normalized_json := run(cmd) or { - contents := os.read_file(v_toml_json_path) ? + contents := os.read_file(v_toml_json_path)? panic(err.msg() + '\n$contents\n\ncmd: ${cmd.join(' ')}') } @@ -245,7 +245,7 @@ fn test_iarna_toml_spec_tests() ? { println('OK [${i + 1}/$invalid_test_files.len] "$invalid_test_file"...') } if toml_doc := toml.parse_file(invalid_test_file) { - content_that_should_have_failed := os.read_file(invalid_test_file) ? + content_that_should_have_failed := os.read_file(invalid_test_file)? println(' This TOML should have failed:\n${'-'.repeat(40)}\n$content_that_should_have_failed\n${'-'.repeat(40)}') assert false } else { diff --git a/vlib/toml/tests/json_encoding_test.v b/vlib/toml/tests/json_encoding_test.v index 9368820348..cda91cb909 100644 --- a/vlib/toml/tests/json_encoding_test.v +++ b/vlib/toml/tests/json_encoding_test.v @@ -5,11 +5,11 @@ import toml.to const fprefix = os.join_path(os.dir(@FILE), 'testdata', os.file_name(@FILE).all_before_last('.')) fn test_parse() ? { - toml_doc := toml.parse_file(os.real_path(fprefix + '.toml')) ? + toml_doc := toml.parse_file(os.real_path(fprefix + '.toml'))? toml_json := to.json(toml_doc) println(toml_json) - out_file_json := os.read_file(os.real_path(fprefix + '.out')) ? + out_file_json := os.read_file(os.real_path(fprefix + '.out'))? assert toml_json == out_file_json } diff --git a/vlib/toml/toml.v b/vlib/toml/toml.v index e85ddb27e6..c26b9fb6a2 100644 --- a/vlib/toml/toml.v +++ b/vlib/toml/toml.v @@ -14,7 +14,7 @@ pub struct Null { // decode decodes a TOML `string` into the target type `T`. pub fn decode(toml_txt string) ?T { - doc := parse_text(toml_txt) ? + doc := parse_text(toml_txt)? mut typ := T{} typ.from_toml(doc.to_any()) return typ @@ -78,10 +78,10 @@ pub fn parse_file(path string) ?Doc { input: input_config } parser_config := parser.Config{ - scanner: scanner.new_scanner(scanner_config) ? + scanner: scanner.new_scanner(scanner_config)? } mut p := parser.new_parser(parser_config) - ast := p.parse() ? + ast := p.parse()? return Doc{ ast: ast } @@ -96,10 +96,10 @@ pub fn parse_text(text string) ?Doc { input: input_config } parser_config := parser.Config{ - scanner: scanner.new_scanner(scanner_config) ? + scanner: scanner.new_scanner(scanner_config)? } mut p := parser.new_parser(parser_config) - ast := p.parse() ? + ast := p.parse()? return Doc{ ast: ast } @@ -111,15 +111,15 @@ pub fn parse_text(text string) ?Doc { [deprecated: 'use parse_file or parse_text instead'] [deprecated_after: '2022-06-18'] pub fn parse(toml string) ?Doc { - mut input_config := input.auto_config(toml) ? + mut input_config := input.auto_config(toml)? scanner_config := scanner.Config{ input: input_config } parser_config := parser.Config{ - scanner: scanner.new_scanner(scanner_config) ? + scanner: scanner.new_scanner(scanner_config)? } mut p := parser.new_parser(parser_config) - ast := p.parse() ? + ast := p.parse()? return Doc{ ast: ast } diff --git a/vlib/v/ast/comptime_const_values.v b/vlib/v/ast/comptime_const_values.v index e9306d3d35..860671f482 100644 --- a/vlib/v/ast/comptime_const_values.v +++ b/vlib/v/ast/comptime_const_values.v @@ -19,7 +19,7 @@ pub fn empty_comptime_const_expr() ComptTimeConstValue { } pub fn (val ComptTimeConstValue) i8() ?i8 { - x := val.i64() ? + x := val.i64()? if x > -129 && x < 128 { return i8(x) } @@ -27,7 +27,7 @@ pub fn (val ComptTimeConstValue) i8() ?i8 { } pub fn (val ComptTimeConstValue) i16() ?i16 { - x := val.i64() ? + x := val.i64()? if x > -32769 && x < 32768 { return i16(x) } @@ -35,7 +35,7 @@ pub fn (val ComptTimeConstValue) i16() ?i16 { } pub fn (val ComptTimeConstValue) int() ?int { - x := val.i64() ? + x := val.i64()? if x > -2147483649 && x < 2147483648 { return int(x) } @@ -94,7 +94,7 @@ pub fn (val ComptTimeConstValue) i64() ?i64 { } pub fn (val ComptTimeConstValue) u8() ?u8 { - x := val.u64() ? + x := val.u64()? if x < 256 { return u8(x) } @@ -102,7 +102,7 @@ pub fn (val ComptTimeConstValue) u8() ?u8 { } pub fn (val ComptTimeConstValue) u16() ?u16 { - x := val.u64() ? + x := val.u64()? if x < 65536 { return u16(x) } @@ -110,7 +110,7 @@ pub fn (val ComptTimeConstValue) u16() ?u16 { } pub fn (val ComptTimeConstValue) u32() ?u32 { - x := val.u64() ? + x := val.u64()? if x < 4294967296 { return u32(x) } @@ -171,7 +171,7 @@ pub fn (val ComptTimeConstValue) u64() ?u64 { } pub fn (val ComptTimeConstValue) f32() ?f32 { - x := val.f64() ? + x := val.f64()? return f32(x) } diff --git a/vlib/v/ast/type_size_test.v b/vlib/v/ast/type_size_test.v index fb79f3b87f..6e2334e723 100644 --- a/vlib/v/ast/type_size_test.v +++ b/vlib/v/ast/type_size_test.v @@ -41,21 +41,21 @@ fn test_type_size() ? { mut t := b.table - size01, _ := t.type_size(t.type_idxs['main.T01'] ?) + size01, _ := t.type_size(t.type_idxs['main.T01']?) assert sizeof(T01) == size01 - size02, _ := t.type_size(t.type_idxs['main.T02'] ?) + size02, _ := t.type_size(t.type_idxs['main.T02']?) assert sizeof(T02) == size02 - size03, _ := t.type_size(t.type_idxs['main.T03'] ?) + size03, _ := t.type_size(t.type_idxs['main.T03']?) assert sizeof(T03) == size03 - size04, _ := t.type_size(t.type_idxs['main.T04'] ?) + size04, _ := t.type_size(t.type_idxs['main.T04']?) assert sizeof(T04) == size04 - size05, _ := t.type_size(t.type_idxs['main.T05'] ?) + size05, _ := t.type_size(t.type_idxs['main.T05']?) assert sizeof(T05) == size05 - size06, _ := t.type_size(t.type_idxs['main.T06'] ?) + size06, _ := t.type_size(t.type_idxs['main.T06']?) assert sizeof(T06) == size06 - size07, _ := t.type_size(t.type_idxs['main.T07'] ?) + size07, _ := t.type_size(t.type_idxs['main.T07']?) assert sizeof(T07) == size07 - size08, _ := t.type_size(t.type_idxs['main.T08'] ?) + size08, _ := t.type_size(t.type_idxs['main.T08']?) assert sizeof(T08) == size08 println('done') diff --git a/vlib/v/ast/types.v b/vlib/v/ast/types.v index c8554716bb..87bfe8c124 100644 --- a/vlib/v/ast/types.v +++ b/vlib/v/ast/types.v @@ -475,7 +475,7 @@ pub const ( pub const ( void_type = new_type(void_type_idx) - ovoid_type = new_type(void_type_idx).set_flag(.optional) // the return type of `fn () ?` + ovoid_type = new_type(void_type_idx).set_flag(.optional) // the return type of `fn ()?` rvoid_type = new_type(void_type_idx).set_flag(.result) // the return type of `fn () !` voidptr_type = new_type(voidptr_type_idx) byteptr_type = new_type(byteptr_type_idx) diff --git a/vlib/v/builder/builder.v b/vlib/v/builder/builder.v index 8750ebb39d..a05fa77a0b 100644 --- a/vlib/v/builder/builder.v +++ b/vlib/v/builder/builder.v @@ -124,8 +124,8 @@ pub fn (mut b Builder) middle_stages() ? { } pub fn (mut b Builder) front_and_middle_stages(v_files []string) ? { - b.front_stages(v_files) ? - b.middle_stages() ? + b.front_stages(v_files)? + b.middle_stages()? } // parse all deps from already parsed files diff --git a/vlib/v/builder/interpreterbuilder/v_interpret_test.v b/vlib/v/builder/interpreterbuilder/v_interpret_test.v index eb6c4e4d27..97b75b1cf7 100644 --- a/vlib/v/builder/interpreterbuilder/v_interpret_test.v +++ b/vlib/v/builder/interpreterbuilder/v_interpret_test.v @@ -17,12 +17,12 @@ fn interp_test(expression string, expected string) ? { // tmpfile := os.join_path(tmpdir, 'input.v') outfile := os.join_path(tmpdir, 'output.txt') - os.write_file(tmpfile, interpreter_wrap(expression)) ? + os.write_file(tmpfile, interpreter_wrap(expression))? if os.system('${os.quoted_path(vexe)} interpret ${os.quoted_path(tmpfile)} > ${os.quoted_path(outfile)}') != 0 { eprintln('>>> Failed to interpret V expression: |$expression|') return error('v interp') } - res := os.read_file(outfile) ? + res := os.read_file(outfile)? output := res.trim_space() if output != expected { eprintln('>>> The output of the V expression, is not the same as the expected one') @@ -49,7 +49,7 @@ fn test_interpreter() ? { tests << InterpTest{'println(3*3)', '9'} tests << InterpTest{'a := 3\nprintln(a*3)', '9'} for test in tests { - interp_test(test.input, test.output) ? + interp_test(test.input, test.output)? assert true } } diff --git a/vlib/v/builder/msvc.v b/vlib/v/builder/msvc.v index eb630e5a44..6db4565b98 100644 --- a/vlib/v/builder/msvc.v +++ b/vlib/v/builder/msvc.v @@ -119,7 +119,7 @@ fn find_windows_kit_root_by_reg(target_arch string) ?WindowsKit { fn new_windows_kit(kit_root string, target_arch string) ?WindowsKit { kit_lib := kit_root + 'Lib' - files := os.ls(kit_lib) ? + files := os.ls(kit_lib)? mut highest_path := '' mut highest_int := 0 for f in files { diff --git a/vlib/v/checker/check_types.v b/vlib/v/checker/check_types.v index 4ff9813805..a5416c92b8 100644 --- a/vlib/v/checker/check_types.v +++ b/vlib/v/checker/check_types.v @@ -375,7 +375,7 @@ pub fn (mut c Checker) check_matching_function_symbols(got_type_sym &ast.TypeSym fn (mut c Checker) check_shift(mut node ast.InfixExpr, left_type ast.Type, right_type ast.Type) ast.Type { if !left_type.is_int() { left_sym := c.table.sym(left_type) - // maybe it's an int alias? TODO move this to is_int() ? + // maybe it's an int alias? TODO move this to is_int()? if left_sym.kind == .alias && (left_sym.info as ast.Alias).parent_type.is_int() { return left_type } diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 02d2d84eb9..c8ba1c068b 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -4284,20 +4284,20 @@ fn (mut c Checker) ensure_type_exists(typ ast.Type, pos token.Pos) ? { } } .array { - c.ensure_type_exists((sym.info as ast.Array).elem_type, pos) ? + c.ensure_type_exists((sym.info as ast.Array).elem_type, pos)? } .array_fixed { - c.ensure_type_exists((sym.info as ast.ArrayFixed).elem_type, pos) ? + c.ensure_type_exists((sym.info as ast.ArrayFixed).elem_type, pos)? } .map { info := sym.info as ast.Map - c.ensure_type_exists(info.key_type, pos) ? - c.ensure_type_exists(info.value_type, pos) ? + c.ensure_type_exists(info.key_type, pos)? + c.ensure_type_exists(info.value_type, pos)? } .sum_type { info := sym.info as ast.SumType for concrete_typ in info.concrete_types { - c.ensure_type_exists(concrete_typ, pos) ? + c.ensure_type_exists(concrete_typ, pos)? } } else {} diff --git a/vlib/v/checker/comptime.v b/vlib/v/checker/comptime.v index 7dfab0c4e5..d5ad6185d3 100644 --- a/vlib/v/checker/comptime.v +++ b/vlib/v/checker/comptime.v @@ -224,8 +224,8 @@ fn (mut c Checker) eval_comptime_const_expr(expr ast.Expr, nlevel int) ?ast.Comp } } ast.InfixExpr { - left := c.eval_comptime_const_expr(expr.left, nlevel + 1) ? - right := c.eval_comptime_const_expr(expr.right, nlevel + 1) ? + left := c.eval_comptime_const_expr(expr.left, nlevel + 1)? + right := c.eval_comptime_const_expr(expr.right, nlevel + 1)? if left is string && right is string { match expr.op { .plus { diff --git a/vlib/v/checker/tests/array_fancy_sort_err.out b/vlib/v/checker/tests/array_fancy_sort_err.out index c61409c1aa..14ffa21407 100644 --- a/vlib/v/checker/tests/array_fancy_sort_err.out +++ b/vlib/v/checker/tests/array_fancy_sort_err.out @@ -1,6 +1,6 @@ vlib/v/checker/tests/array_fancy_sort_err.vv:6:8: error: `.sort()` can only use ident, index or selector as argument, e.g. `arr.sort(a < b)`, `arr.sort(a.id < b.id)`, `arr.sort(a[0] < b[0])` - 4 | text := os.read_file(os.args[0]) ? + 4 | text := os.read_file(os.args[0])? 5 | mut lines := text.split_into_lines() 6 | lines.sort(a.split('/').last() < b.split('/').last()) | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/vlib/v/checker/tests/array_fancy_sort_err.vv b/vlib/v/checker/tests/array_fancy_sort_err.vv index 3c05a5e6bb..f2a6ede100 100644 --- a/vlib/v/checker/tests/array_fancy_sort_err.vv +++ b/vlib/v/checker/tests/array_fancy_sort_err.vv @@ -1,7 +1,7 @@ import os fn main() { - text := os.read_file(os.args[0]) ? + text := os.read_file(os.args[0])? mut lines := text.split_into_lines() lines.sort(a.split('/').last() < b.split('/').last()) println(lines.join('\n')) diff --git a/vlib/v/checker/tests/defer_optional.vv b/vlib/v/checker/tests/defer_optional.vv index f153430535..acb4537853 100644 --- a/vlib/v/checker/tests/defer_optional.vv +++ b/vlib/v/checker/tests/defer_optional.vv @@ -5,4 +5,4 @@ fn thing() ?string { opt() } return 'ok' -} \ No newline at end of file +} diff --git a/vlib/v/checker/tests/go_wait_or.out b/vlib/v/checker/tests/go_wait_or.out index d00dbd2209..92242c6ab4 100644 --- a/vlib/v/checker/tests/go_wait_or.out +++ b/vlib/v/checker/tests/go_wait_or.out @@ -1,12 +1,12 @@ -vlib/v/checker/tests/go_wait_or.vv:11:17: error: unexpected `?`, the function `wait` does neither return an optional nor a result +vlib/v/checker/tests/go_wait_or.vv:11:16: error: unexpected `?`, the function `wait` does neither return an optional nor a result 9 | go d(1) 10 | ] - 11 | r := tg.wait() ? - | ^ + 11 | r := tg.wait()? + | ^ 12 | println(r) 13 | s := tg[0].wait() or { panic('problem') } vlib/v/checker/tests/go_wait_or.vv:13:20: error: unexpected `or` block, the function `wait` does neither return an optional nor a result - 11 | r := tg.wait() ? + 11 | r := tg.wait()? 12 | println(r) 13 | s := tg[0].wait() or { panic('problem') } | ~~~~~~~~~~~~~~~~~~~~~~~ @@ -17,13 +17,13 @@ vlib/v/checker/tests/go_wait_or.vv:19:13: error: unexpected `or` block, the func 18 | ] 19 | tg2.wait() or { panic('problem') } | ~~~~~~~~~~~~~~~~~~~~~~~ - 20 | tg2[0].wait() ? + 20 | tg2[0].wait()? 21 | tg3 := [ -vlib/v/checker/tests/go_wait_or.vv:20:16: error: unexpected `?`, the function `wait` does neither return an optional nor a result +vlib/v/checker/tests/go_wait_or.vv:20:15: error: unexpected `?`, the function `wait` does neither return an optional nor a result 18 | ] 19 | tg2.wait() or { panic('problem') } - 20 | tg2[0].wait() ? - | ^ + 20 | tg2[0].wait()? + | ^ 21 | tg3 := [ 22 | go f(0) vlib/v/checker/tests/go_wait_or.vv:25:6: error: `.wait()` cannot be called for an array when thread functions return optionals. Iterate over the arrays elements instead and handle each returned optional with `or`. diff --git a/vlib/v/checker/tests/go_wait_or.vv b/vlib/v/checker/tests/go_wait_or.vv index 3522f90851..7c5aab9a15 100644 --- a/vlib/v/checker/tests/go_wait_or.vv +++ b/vlib/v/checker/tests/go_wait_or.vv @@ -8,7 +8,7 @@ fn main() { go d(0) go d(1) ] - r := tg.wait() ? + r := tg.wait()? println(r) s := tg[0].wait() or { panic('problem') } println(s) @@ -17,7 +17,7 @@ fn main() { go e(1) ] tg2.wait() or { panic('problem') } - tg2[0].wait() ? + tg2[0].wait()? tg3 := [ go f(0) go f(1) diff --git a/vlib/v/checker/tests/invalid_parameter_name_err.out b/vlib/v/checker/tests/invalid_parameter_name_err.out index f567decd46..b8940b18fc 100644 --- a/vlib/v/checker/tests/invalid_parameter_name_err.out +++ b/vlib/v/checker/tests/invalid_parameter_name_err.out @@ -8,7 +8,7 @@ vlib/v/checker/tests/invalid_parameter_name_err.vv:4:24: error: invalid use of r vlib/v/checker/tests/invalid_parameter_name_err.vv:10:6: error: invalid use of reserved type `char` as a parameter name 8 | interface Writer { 9 | mut: - 10 | put(char u8) ? + 10 | put(char u8)? | ~~~~ 11 | } 12 | diff --git a/vlib/v/checker/tests/invalid_parameter_name_err.vv b/vlib/v/checker/tests/invalid_parameter_name_err.vv index d0132be254..39054879a1 100644 --- a/vlib/v/checker/tests/invalid_parameter_name_err.vv +++ b/vlib/v/checker/tests/invalid_parameter_name_err.vv @@ -7,7 +7,7 @@ fn (mut b Buffer) put8(char u8) ? { interface Writer { mut: - put(char u8) ? + put(char u8)? } fn main() { diff --git a/vlib/v/checker/tests/json_decode.out b/vlib/v/checker/tests/json_decode.out index fd25d4651c..b3ab07b3b5 100644 --- a/vlib/v/checker/tests/json_decode.out +++ b/vlib/v/checker/tests/json_decode.out @@ -1,34 +1,34 @@ vlib/v/checker/tests/json_decode.vv:11:7: error: json.decode: unknown type `St2` 9 | fn main() { - 10 | json.decode(St, '{a: ""}') ? // OK - 11 | json.decode(St2, '{a: ""}') ? // BAD + 10 | json.decode(St, '{a: ""}')? // OK + 11 | json.decode(St2, '{a: ""}')? // BAD | ~~~~~~~~~~~~~~~~~~~~~~ - 12 | json.decode(St) ? // BAD - 13 | json.decode(string, '""') ? // BAD + 12 | json.decode(St)? // BAD + 13 | json.decode(string, '""')? // BAD vlib/v/checker/tests/json_decode.vv:12:7: error: json.decode expects 2 arguments, a type and a string (e.g `json.decode(T, '')`) - 10 | json.decode(St, '{a: ""}') ? // OK - 11 | json.decode(St2, '{a: ""}') ? // BAD - 12 | json.decode(St) ? // BAD + 10 | json.decode(St, '{a: ""}')? // OK + 11 | json.decode(St2, '{a: ""}')? // BAD + 12 | json.decode(St)? // BAD | ~~~~~~~~~~ - 13 | json.decode(string, '""') ? // BAD - 14 | json.decode(Num, '5') ? // BAD + 13 | json.decode(string, '""')? // BAD + 14 | json.decode(Num, '5')? // BAD vlib/v/checker/tests/json_decode.vv:13:14: error: json.decode: expected sum type, struct, map or array, found string - 11 | json.decode(St2, '{a: ""}') ? // BAD - 12 | json.decode(St) ? // BAD - 13 | json.decode(string, '""') ? // BAD + 11 | json.decode(St2, '{a: ""}')? // BAD + 12 | json.decode(St)? // BAD + 13 | json.decode(string, '""')? // BAD | ~~~~~~ - 14 | json.decode(Num, '5') ? // BAD - 15 | json.decode(St, 6) ? // BAD + 14 | json.decode(Num, '5')? // BAD + 15 | json.decode(St, 6)? // BAD vlib/v/checker/tests/json_decode.vv:14:14: error: json.decode: expected sum type, struct, map or array, found u8 - 12 | json.decode(St) ? // BAD - 13 | json.decode(string, '""') ? // BAD - 14 | json.decode(Num, '5') ? // BAD + 12 | json.decode(St)? // BAD + 13 | json.decode(string, '""')? // BAD + 14 | json.decode(Num, '5')? // BAD | ~~~ - 15 | json.decode(St, 6) ? // BAD + 15 | json.decode(St, 6)? // BAD 16 | } vlib/v/checker/tests/json_decode.vv:15:7: error: json.decode: second argument needs to be a string - 13 | json.decode(string, '""') ? // BAD - 14 | json.decode(Num, '5') ? // BAD - 15 | json.decode(St, 6) ? // BAD + 13 | json.decode(string, '""')? // BAD + 14 | json.decode(Num, '5')? // BAD + 15 | json.decode(St, 6)? // BAD | ~~~~~~~~~~~~~ 16 | } diff --git a/vlib/v/checker/tests/json_decode.vv b/vlib/v/checker/tests/json_decode.vv index 4772e438d7..bda81896c5 100644 --- a/vlib/v/checker/tests/json_decode.vv +++ b/vlib/v/checker/tests/json_decode.vv @@ -7,10 +7,10 @@ struct St { type Num = u8 fn main() { - json.decode(St, '{a: ""}') ? // OK - json.decode(St2, '{a: ""}') ? // BAD - json.decode(St) ? // BAD - json.decode(string, '""') ? // BAD - json.decode(Num, '5') ? // BAD - json.decode(St, 6) ? // BAD + json.decode(St, '{a: ""}')? // OK + json.decode(St2, '{a: ""}')? // BAD + json.decode(St)? // BAD + json.decode(string, '""')? // BAD + json.decode(Num, '5')? // BAD + json.decode(St, 6)? // BAD } diff --git a/vlib/v/checker/tests/modules/deprecated_module.out b/vlib/v/checker/tests/modules/deprecated_module.out index ace9220681..918b2ef3a9 100644 --- a/vlib/v/checker/tests/modules/deprecated_module.out +++ b/vlib/v/checker/tests/modules/deprecated_module.out @@ -9,4 +9,4 @@ vlib/v/checker/tests/modules/deprecated_module/main.v:12:11: error: undefined id 11 | dump(yyy.f()) 12 | dump(ttt.non_existing) | ~~~~~~~~~~~~ - 13 | } + 13 | } \ No newline at end of file diff --git a/vlib/v/checker/tests/optional_propagate_nested.out b/vlib/v/checker/tests/optional_propagate_nested.out index f113a890bd..f4b397ef2a 100644 --- a/vlib/v/checker/tests/optional_propagate_nested.out +++ b/vlib/v/checker/tests/optional_propagate_nested.out @@ -1,14 +1,14 @@ -vlib/v/checker/tests/optional_propagate_nested.vv:10:19: error: to propagate the optional call, `xx_prop` must return an optional +vlib/v/checker/tests/optional_propagate_nested.vv:10:18: error: to propagate the optional call, `xx_prop` must return an optional 8 | 9 | fn xx_prop() string { - 10 | s := ret(raise() ?) - | ^ + 10 | s := ret(raise()?) + | ^ 11 | return s 12 | } -vlib/v/checker/tests/optional_propagate_nested.vv:28:22: error: to propagate the optional call, `aa_propagate` must return an optional +vlib/v/checker/tests/optional_propagate_nested.vv:28:21: error: to propagate the optional call, `aa_propagate` must return an optional 26 | 27 | fn (mut s St) aa_propagate() { - 28 | f := retf(s.raise() ?) - | ^ + 28 | f := retf(s.raise()?) + | ^ 29 | s.z = 7.5 30 | println(f) diff --git a/vlib/v/checker/tests/optional_propagate_nested.vv b/vlib/v/checker/tests/optional_propagate_nested.vv index d00ef5392c..07c299b55a 100644 --- a/vlib/v/checker/tests/optional_propagate_nested.vv +++ b/vlib/v/checker/tests/optional_propagate_nested.vv @@ -7,7 +7,7 @@ fn raise() ?string { } fn xx_prop() string { - s := ret(raise() ?) + s := ret(raise()?) return s } @@ -25,7 +25,7 @@ fn retf(f f64) f64 { } fn (mut s St) aa_propagate() { - f := retf(s.raise() ?) + f := retf(s.raise()?) s.z = 7.5 println(f) } diff --git a/vlib/v/checker/tests/orm_using_undefined_var_in_where_err.vv b/vlib/v/checker/tests/orm_using_undefined_var_in_where_err.vv index b3d685398d..b4d86e692f 100644 --- a/vlib/v/checker/tests/orm_using_undefined_var_in_where_err.vv +++ b/vlib/v/checker/tests/orm_using_undefined_var_in_where_err.vv @@ -11,7 +11,7 @@ struct User { } fn main() { - db := sqlite.connect(':memory:') ? + db := sqlite.connect(':memory:')? sql db { create table User } diff --git a/vlib/v/checker/tests/propagate_option_with_result_err.out b/vlib/v/checker/tests/propagate_option_with_result_err.out index edbb23304c..9464691924 100644 --- a/vlib/v/checker/tests/propagate_option_with_result_err.out +++ b/vlib/v/checker/tests/propagate_option_with_result_err.out @@ -1,7 +1,7 @@ -vlib/v/checker/tests/propagate_option_with_result_err.vv:6:8: error: to propagate an option, the call must also return an optional type +vlib/v/checker/tests/propagate_option_with_result_err.vv:6:7: error: to propagate an option, the call must also return an optional type 4 | 5 | fn bar() ?string { - 6 | foo() ? - | ^ + 6 | foo()? + | ^ 7 | return '' 8 | } diff --git a/vlib/v/checker/tests/propagate_option_with_result_err.vv b/vlib/v/checker/tests/propagate_option_with_result_err.vv index 0b57053fbb..ef6482dcb1 100644 --- a/vlib/v/checker/tests/propagate_option_with_result_err.vv +++ b/vlib/v/checker/tests/propagate_option_with_result_err.vv @@ -3,7 +3,7 @@ fn foo() !string { } fn bar() ?string { - foo() ? + foo()? return '' } diff --git a/vlib/v/checker/tests/return_void_type_err.vv b/vlib/v/checker/tests/return_void_type_err.vv index 177da908ca..65a6f99513 100644 --- a/vlib/v/checker/tests/return_void_type_err.vv +++ b/vlib/v/checker/tests/return_void_type_err.vv @@ -3,5 +3,5 @@ fn hello(msg string) ? { } fn main() { - hello('test') ? + hello('test')? } diff --git a/vlib/v/checker/tests/unknown_type_in_anon_fn.out b/vlib/v/checker/tests/unknown_type_in_anon_fn.out index 2045ddbba6..1ccfeaff44 100644 --- a/vlib/v/checker/tests/unknown_type_in_anon_fn.out +++ b/vlib/v/checker/tests/unknown_type_in_anon_fn.out @@ -1,7 +1,7 @@ vlib/v/checker/tests/unknown_type_in_anon_fn.vv:5:10: error: unknown type `Another` 3 | struct Struc{ 4 | mut: - 5 | f fn (s Another, i int) ? + 5 | f fn (s Another, i int)? | ~~~~~~~ 6 | } 7 | diff --git a/vlib/v/checker/tests/unknown_type_in_anon_fn.vv b/vlib/v/checker/tests/unknown_type_in_anon_fn.vv index f03742cc4d..64e1a18db3 100644 --- a/vlib/v/checker/tests/unknown_type_in_anon_fn.vv +++ b/vlib/v/checker/tests/unknown_type_in_anon_fn.vv @@ -2,7 +2,7 @@ module main struct Struc{ mut: - f fn (s Another, i int) ? + f fn (s Another, i int)? } fn main() {} diff --git a/vlib/v/doc/doc.v b/vlib/v/doc/doc.v index 3d914bc83c..3f343709a5 100644 --- a/vlib/v/doc/doc.v +++ b/vlib/v/doc/doc.v @@ -513,7 +513,7 @@ pub fn generate(input_path string, pub_only bool, with_comments bool, platform P doc.with_comments = with_comments doc.filter_symbol_names = filter_symbol_names.filter(it.len != 0) doc.prefs.os = if platform == .auto { pref.get_host_os() } else { pref.OS(int(platform)) } - doc.generate() ? + doc.generate()? return doc } @@ -526,6 +526,6 @@ pub fn generate_with_pos(input_path string, filename string, pos int) ?Doc { doc.with_pos = true doc.filename = filename doc.pos = pos - doc.generate() ? + doc.generate()? return doc } diff --git a/vlib/v/doc/doc_private_fn_test.v b/vlib/v/doc/doc_private_fn_test.v index 100a222b78..fa98c4f7a4 100644 --- a/vlib/v/doc/doc_private_fn_test.v +++ b/vlib/v/doc/doc_private_fn_test.v @@ -28,7 +28,7 @@ fn test_get_parent_mod_current_folder() { fn test_get_parent_mod_on_temp_dir() ? { // TODO: fix this on windows $if !windows { - assert get_parent_mod(os.temp_dir()) ? == '' + assert get_parent_mod(os.temp_dir())? == '' } } @@ -38,10 +38,10 @@ fn test_get_parent_mod_normal_cases() ? { '---' } // TODO: WTF? - // assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'v', 'doc', 'doc.v')) ? == 'v.v.doc' - assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'v', 'doc')) ? == 'v' - assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'os', 'os.v')) ? == 'os' - assert get_parent_mod(os.join_path(@VMODROOT, 'cmd')) ? == '' + // assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'v', 'doc', 'doc.v'))? == 'v.v.doc' + assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'v', 'doc'))? == 'v' + assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'os', 'os.v'))? == 'os' + assert get_parent_mod(os.join_path(@VMODROOT, 'cmd'))? == '' assert get_parent_mod(os.join_path(@VMODROOT, 'cmd', 'tools', 'modules', 'testing', - 'common.v')) ? == 'testing' + 'common.v'))? == 'testing' } diff --git a/vlib/v/doc/module.v b/vlib/v/doc/module.v index 021ba895ec..4c277d4f4b 100644 --- a/vlib/v/doc/module.v +++ b/vlib/v/doc/module.v @@ -85,6 +85,6 @@ pub fn lookup_module(mod string) ?string { // generate_from_mod generates a documentation from a specific module. pub fn generate_from_mod(module_name string, pub_only bool, with_comments bool) ?Doc { - mod_path := lookup_module(module_name) ? + mod_path := lookup_module(module_name)? return generate(mod_path, pub_only, with_comments, .auto) } diff --git a/vlib/v/eval/interpret_test.v b/vlib/v/eval/interpret_test.v index 6dbea784ff..9b1797df3c 100644 --- a/vlib/v/eval/interpret_test.v +++ b/vlib/v/eval/interpret_test.v @@ -8,9 +8,9 @@ fn test_interpret() ? { mut bench := benchmark.new_benchmark() vexe := os.getenv('VEXE') vroot := os.dir(vexe) - os.chdir(vroot) ? + os.chdir(vroot)? dir := os.join_path(vroot, 'vlib/v/eval/testdata') - files := os.ls(dir) ? + files := os.ls(dir)? // tests := files.filter(it.ends_with('.vv')) if tests.len == 0 { @@ -35,7 +35,7 @@ fn test_interpret() ? { eprintln(res.output) continue } - mut expected := os.read_file('$dir/${test_name_without_postfix}.out') ? + mut expected := os.read_file('$dir/${test_name_without_postfix}.out')? expected = normalise_line_endings(expected) mut found := normalise_line_endings(res.output) found = found.trim_space() diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index d79364f189..92e762b585 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -2331,10 +2331,10 @@ pub fn (mut f Fmt) or_expr(node ast.OrExpr) { f.write('}') } .propagate_option { - f.write(' ?') + f.write('?') } .propagate_result { - f.write(' !') + f.write('!') } } } diff --git a/vlib/v/fmt/fmt_keep_test.v b/vlib/v/fmt/fmt_keep_test.v index 7a7ca77e3a..375bc90cea 100644 --- a/vlib/v/fmt/fmt_keep_test.v +++ b/vlib/v/fmt/fmt_keep_test.v @@ -100,7 +100,7 @@ fn prepare_bin2v_file(mut fmt_bench benchmark.Benchmark) { fn write_bin2v_keep_content() ? { img0 := os.join_path('vlib', 'v', 'embed_file', 'tests', 'v.png') img1 := os.join_path('tutorials', 'building_a_simple_web_blog_with_vweb', 'img', 'time.png') - os.rm(b2v_keep_path) ? + os.rm(b2v_keep_path)? res := os.execute('${os.quoted_path(vexe)} bin2v -w ${os.quoted_path(b2v_keep_path)} ${os.quoted_path(img0)} ${os.quoted_path(img1)}') if res.exit_code != 0 { restore_bin2v_placeholder() or {} @@ -111,5 +111,5 @@ fn write_bin2v_keep_content() ? { fn restore_bin2v_placeholder() ? { text := '// This is a placeholder file which will be filled with bin2v output before the test. // HINT: do NOT delete, move or rename this file!\n' - os.write_file(b2v_keep_path, text) ? + os.write_file(b2v_keep_path, text)? } diff --git a/vlib/v/fmt/tests/chan_ops_keep.vv b/vlib/v/fmt/tests/chan_ops_keep.vv index 57ae61688a..facd926336 100644 --- a/vlib/v/fmt/tests/chan_ops_keep.vv +++ b/vlib/v/fmt/tests/chan_ops_keep.vv @@ -9,7 +9,7 @@ struct St { } fn get_val_from_chan(ch chan i64) ?i64 { - r := <-ch ? + r := <-ch? return r } diff --git a/vlib/v/fmt/tests/chan_or_keep.vv b/vlib/v/fmt/tests/chan_or_keep.vv index a6e7a90625..27af5550d3 100644 --- a/vlib/v/fmt/tests/chan_or_keep.vv +++ b/vlib/v/fmt/tests/chan_or_keep.vv @@ -13,7 +13,7 @@ fn f(ch chan int) { } fn do_send(ch chan int, val int) ?int { - ch <- val ? + ch <- val? return val + 1 } diff --git a/vlib/v/fmt/tests/empty_lines_keep.vv b/vlib/v/fmt/tests/empty_lines_keep.vv index 7e22486423..876716e083 100644 --- a/vlib/v/fmt/tests/empty_lines_keep.vv +++ b/vlib/v/fmt/tests/empty_lines_keep.vv @@ -92,7 +92,7 @@ bar' }, Two{ value: 'two' })" - r := m[key] ? + r := m[key]? compile_time_env := $env('ENV_VAR') func() } diff --git a/vlib/v/fmt/tests/optional_propagate_keep.vv b/vlib/v/fmt/tests/optional_propagate_keep.vv index 0cd4524f9e..bf287bd4d9 100644 --- a/vlib/v/fmt/tests/optional_propagate_keep.vv +++ b/vlib/v/fmt/tests/optional_propagate_keep.vv @@ -1,3 +1,3 @@ fn opt_propagate() ?int { - eventual_wrong_int() ? + eventual_wrong_int()? } diff --git a/vlib/v/fmt/tests/orm_keep.vv b/vlib/v/fmt/tests/orm_keep.vv index 26513bde6a..316f55d3c2 100644 --- a/vlib/v/fmt/tests/orm_keep.vv +++ b/vlib/v/fmt/tests/orm_keep.vv @@ -15,7 +15,7 @@ fn find_all_customers(db sqlite.DB) []Customer { } fn main() { - db := sqlite.connect('customers.db') ? + db := sqlite.connect('customers.db')? // select count(*) from Customer nr_customers := sql db { select count from Customer diff --git a/vlib/v/fmt/tests/shared_expected.vv b/vlib/v/fmt/tests/shared_expected.vv index d077f88410..13f76126a6 100644 --- a/vlib/v/fmt/tests/shared_expected.vv +++ b/vlib/v/fmt/tests/shared_expected.vv @@ -34,7 +34,7 @@ fn k() { shared f := St{} f } - shared z := h() ? + shared z := h()? shared p := v v := rlock z { z.a diff --git a/vlib/v/fmt/tests/shared_input.vv b/vlib/v/fmt/tests/shared_input.vv index dccb34a683..9ebf6a7f7f 100644 --- a/vlib/v/fmt/tests/shared_input.vv +++ b/vlib/v/fmt/tests/shared_input.vv @@ -33,7 +33,7 @@ fn k() { shared f := St{} f } - shared z := h() ? + shared z := h()? shared p := v v := rlock z { z.a } rlock x; lock y, z; rlock p { diff --git a/vlib/v/gen/c/auto_str_methods.v b/vlib/v/gen/c/auto_str_methods.v index 62b551e496..a5d5b71f0e 100644 --- a/vlib/v/gen/c/auto_str_methods.v +++ b/vlib/v/gen/c/auto_str_methods.v @@ -979,7 +979,7 @@ fn (mut g Gen) gen_str_for_struct(info ast.Struct, styp string, str_fn_name stri fn_body.write_string('tos2((byteptr)$func)') } else { if field.typ.is_ptr() && sym.kind == .struct_ { - funcprefix += '(indent_count > 25) ? _SLIT("") : ' + funcprefix += '(indent_count > 25)? _SLIT("") : ' } // eprintln('>>> caller_should_free: ${caller_should_free:6s} | funcprefix: $funcprefix | func: $func') if caller_should_free { diff --git a/vlib/v/gen/c/coutput_test.v b/vlib/v/gen/c/coutput_test.v index 8436773b15..4018cc83f4 100644 --- a/vlib/v/gen/c/coutput_test.v +++ b/vlib/v/gen/c/coutput_test.v @@ -22,7 +22,7 @@ fn test_out_files() ? { println(term.colorize(term.green, '> testing whether .out files match:')) os.chdir(vroot) or {} output_path := os.join_path(os.temp_dir(), 'coutput', 'out') - os.mkdir_all(output_path) ? + os.mkdir_all(output_path)? defer { os.rmdir_all(output_path) or {} } @@ -50,7 +50,7 @@ fn test_out_files() ? { panic(res.output) } mut found := res.output.trim_right('\r\n').replace('\r\n', '\n') - mut expected := os.read_file(out_path) ? + mut expected := os.read_file(out_path)? expected = expected.trim_right('\r\n').replace('\r\n', '\n') if expected.contains('================ V panic ================') { // panic include backtraces and absolute file paths, so can't do char by char comparison @@ -93,7 +93,7 @@ fn test_c_must_have_files() ? { println(term.colorize(term.green, '> testing whether `.c.must_have` files match:')) os.chdir(vroot) or {} output_path := os.join_path(os.temp_dir(), 'coutput', 'c_must_have') - os.mkdir_all(output_path) ? + os.mkdir_all(output_path)? defer { os.rmdir_all(output_path) or {} } diff --git a/vlib/v/gen/c/if.v b/vlib/v/gen/c/if.v index 07105e7138..3868d55c77 100644 --- a/vlib/v/gen/c/if.v +++ b/vlib/v/gen/c/if.v @@ -46,7 +46,7 @@ fn (mut g Gen) if_expr(node ast.IfExpr) { return } // For simpe if expressions we can use C's `?:` - // `if x > 0 { 1 } else { 2 }` => `(x > 0) ? (1) : (2)` + // `if x > 0 { 1 } else { 2 }` => `(x > 0)? (1) : (2)` // For if expressions with multiple statements or another if expression inside, it's much // easier to use a temp var, than do C tricks with commas, introduce special vars etc // (as it used to be done). diff --git a/vlib/v/gen/c/match.v b/vlib/v/gen/c/match.v index 9ff991062c..1e1d29f137 100644 --- a/vlib/v/gen/c/match.v +++ b/vlib/v/gen/c/match.v @@ -158,7 +158,7 @@ fn (mut g Gen) match_expr_sumtype(node ast.MatchExpr, is_expr bool, cond_var str } } if is_expr && tmp_var.len == 0 { - g.write(') ? ') + g.write(')? ') } else { g.writeln(') {') } @@ -403,7 +403,7 @@ fn (mut g Gen) match_expr_classic(node ast.MatchExpr, is_expr bool, cond_var str } } if is_expr && tmp_var.len == 0 { - g.write(') ? ') + g.write(')? ') } else { g.writeln(') {') } diff --git a/vlib/v/gen/js/auto_str_methods.v b/vlib/v/gen/js/auto_str_methods.v index f90b24ed4a..d465ba5011 100644 --- a/vlib/v/gen/js/auto_str_methods.v +++ b/vlib/v/gen/js/auto_str_methods.v @@ -207,7 +207,7 @@ fn (mut g JsGen) gen_str_default(sym ast.TypeSymbol, styp string, str_fn_name st g.definitions.writeln('function ${str_fn_name}(it) {') if convertor == 'bool' { - g.definitions.writeln('\tlet tmp1 = string__plus(new string("${styp}("), it.valueOf() ? new string("true") : new string("false"));') + g.definitions.writeln('\tlet tmp1 = string__plus(new string("${styp}("), it.valueOf()? new string("true") : new string("false"));') } else { g.definitions.writeln('\tlet tmp1 = string__plus(new string("${styp}("), new string(${typename_}_str(($convertor)it).str));') } @@ -766,7 +766,7 @@ fn (mut g JsGen) gen_str_for_struct(info ast.Struct, styp string, str_fn_name st fn_builder.write_string('tos2((byteptr)$func)') } else { if field.typ.is_ptr() && sym.kind == .struct_ { - fn_builder.write_string('(indent_count > 25) ? new string("") : ') + fn_builder.write_string('(indent_count > 25)? new string("") : ') } fn_builder.write_string(func) } diff --git a/vlib/v/gen/js/js.v b/vlib/v/gen/js/js.v index af73b5f21a..2896727c13 100644 --- a/vlib/v/gen/js/js.v +++ b/vlib/v/gen/js/js.v @@ -2379,7 +2379,7 @@ fn (mut g JsGen) match_expr_classic(node ast.MatchExpr, is_expr bool, cond_var M } } if is_expr && tmp_var.len == 0 { - g.write(') ? ') + g.write(')? ') } else { g.writeln(') {') } @@ -2585,7 +2585,7 @@ fn (mut g JsGen) match_expr_sumtype(node ast.MatchExpr, is_expr bool, cond_var M } } if is_expr && tmp_var.len == 0 { - g.write(') ? ') + g.write(')? ') } else { g.writeln(') {') } @@ -2757,7 +2757,7 @@ fn (mut g JsGen) gen_if_expr(node ast.IfExpr) { return } // For simpe if expressions we can use C's `?:` - // `if x > 0 { 1 } else { 2 }` => `(x > 0) ? (1) : (2)` + // `if x > 0 { 1 } else { 2 }` => `(x > 0)? (1) : (2)` // For if expressions with multiple statements or another if expression inside, it's much // easier to use a temp var, than do C tricks with commas, introduce special vars etc // (as it used to be done). diff --git a/vlib/v/gen/js/program_test.v b/vlib/v/gen/js/program_test.v index b44c3caf7a..8754854359 100644 --- a/vlib/v/gen/js/program_test.v +++ b/vlib/v/gen/js/program_test.v @@ -40,7 +40,7 @@ fn test_running_programs_compiled_with_the_js_backend() ? { os.chdir(vroot) or {} test_dir := 'vlib/v/gen/js/tests/testdata' main_files := get_main_files_in_dir(test_dir) - fails := check_path(test_dir, main_files) ? + fails := check_path(test_dir, main_files)? assert fails == 0 } @@ -57,14 +57,14 @@ fn check_path(dir string, tests []string) ?int { program := path.replace(vroot + os.path_separator, '') program_out := program.replace('.v', '.out') if !os.exists(program_out) { - os.write_file(program_out, '') ? + os.write_file(program_out, '')? } print(program + ' ') res := os.execute('${os.quoted_path(vexe)} -b js_node run ${os.quoted_path(program)}') if res.exit_code < 0 { panic(res.output) } - mut expected := os.read_file(program_out) ? + mut expected := os.read_file(program_out)? expected = clean_line_endings(expected) found := clean_line_endings(res.output) if expected != found { diff --git a/vlib/v/gen/js/sourcemap/mappings.v b/vlib/v/gen/js/sourcemap/mappings.v index d7aff132ca..46e04a9f5a 100644 --- a/vlib/v/gen/js/sourcemap/mappings.v +++ b/vlib/v/gen/js/sourcemap/mappings.v @@ -109,25 +109,25 @@ fn (mut m Mappings) export_mappings(mut output io.Writer) ? { } } - vlq.encode(i64(mapping.gen_column - previous_generated_column), mut &output) ? + vlq.encode(i64(mapping.gen_column - previous_generated_column), mut &output)? previous_generated_column = mapping.gen_column match mapping.source_position { Empty {} SourcePosition { - vlq.encode(i64(mapping.sources_ind - previous_source_index), mut &output) ? + vlq.encode(i64(mapping.sources_ind - previous_source_index), mut &output)? previous_source_index = mapping.sources_ind // lines are stored 0-based in SourceMap spec version 3 vlq.encode(i64(mapping.source_position.source_line - 1 - previous_source_line), mut - output) ? + output)? previous_source_line = mapping.source_position.source_line - 1 vlq.encode(i64(mapping.source_position.source_column - previous_source_column), mut - output) ? + output)? previous_source_column = mapping.source_position.source_column match mapping.names_ind { Empty {} IndexNumber { - vlq.encode(i64(mapping.names_ind - previous_name_index), mut &output) ? + vlq.encode(i64(mapping.names_ind - previous_name_index), mut &output)? previous_name_index = mapping.names_ind } } diff --git a/vlib/v/gen/js/sourcemap/vlq/vlq_decode_test.v b/vlib/v/gen/js/sourcemap/vlq/vlq_decode_test.v index 85bc70bb77..988307e4e6 100644 --- a/vlib/v/gen/js/sourcemap/vlq/vlq_decode_test.v +++ b/vlib/v/gen/js/sourcemap/vlq/vlq_decode_test.v @@ -30,7 +30,7 @@ fn test_decode_a() ? { for _, test_data in decode_values { mut input := make_test_reader(test_data.decode_val) - res := decode(mut &input) ? + res := decode(mut &input)? assert res == test_data.expected } } diff --git a/vlib/v/gen/js/sourcemap/vlq/vlq_encode_test.v b/vlib/v/gen/js/sourcemap/vlq/vlq_encode_test.v index 21f6587a8c..5e450ee4d1 100644 --- a/vlib/v/gen/js/sourcemap/vlq/vlq_encode_test.v +++ b/vlib/v/gen/js/sourcemap/vlq/vlq_encode_test.v @@ -23,7 +23,7 @@ fn test_encode_a() ? { for _, test_data in decode_values { mut output := TestWriter{} - encode(test_data.data_val, mut &output) ? + encode(test_data.data_val, mut &output)? // dump(output.bytes) assert output.bytes == test_data.expected.bytes() } diff --git a/vlib/v/gen/js/str.v b/vlib/v/gen/js/str.v index 0cfa498e2c..ae19585d82 100644 --- a/vlib/v/gen/js/str.v +++ b/vlib/v/gen/js/str.v @@ -31,7 +31,7 @@ fn (mut g JsGen) gen_expr_to_string(expr ast.Expr, etype ast.Type) { } else if typ == ast.bool_type { g.write('new string((') g.expr(expr) - g.write(').valueOf() ? "true" : "false")') + g.write(').valueOf()? "true" : "false")') } else if sym.kind == .none_ { g.write('new string("")') } else if sym.kind == .enum_ { @@ -100,7 +100,7 @@ fn (mut g JsGen) gen_expr_to_string(expr ast.Expr, etype ast.Type) { g.expr(expr) } else if typ == ast.bool_type { g.expr(expr) - g.write('.valueOf() ? new string("true") : new string("false")') + g.write('.valueOf()? new string("true") : new string("false")') } else if sym.kind == .none_ { g.write('new string("")') } else if sym.kind == .enum_ { diff --git a/vlib/v/gen/js/tests/optional.v b/vlib/v/gen/js/tests/optional.v index 6d52eac8d5..5a6f7720f2 100644 --- a/vlib/v/gen/js/tests/optional.v +++ b/vlib/v/gen/js/tests/optional.v @@ -5,14 +5,14 @@ fn main() { } fn try_propagation() ? { - try_numbers() ? + try_numbers()? } fn try_numbers() ? { for x in 1 .. 10 { y := error_if_even(x) or { x + 1 } println('$x rounded to $y') - error_if_prime(y) ? + error_if_prime(y)? } } diff --git a/vlib/v/parser/assign.v b/vlib/v/parser/assign.v index 9da40ed599..f1603ea9c5 100644 --- a/vlib/v/parser/assign.v +++ b/vlib/v/parser/assign.v @@ -41,77 +41,77 @@ fn (mut p Parser) check_undefined_variables(exprs []ast.Expr, val ast.Expr) ? { } ast.ArrayInit { if val.has_cap { - p.check_undefined_variables(exprs, val.cap_expr) ? + p.check_undefined_variables(exprs, val.cap_expr)? } if val.has_len { - p.check_undefined_variables(exprs, val.len_expr) ? + p.check_undefined_variables(exprs, val.len_expr)? } if val.has_default { - p.check_undefined_variables(exprs, val.default_expr) ? + p.check_undefined_variables(exprs, val.default_expr)? } for expr in val.exprs { - p.check_undefined_variables(exprs, expr) ? + p.check_undefined_variables(exprs, expr)? } } ast.CallExpr { - p.check_undefined_variables(exprs, val.left) ? + p.check_undefined_variables(exprs, val.left)? for arg in val.args { - p.check_undefined_variables(exprs, arg.expr) ? + p.check_undefined_variables(exprs, arg.expr)? } } ast.InfixExpr { - p.check_undefined_variables(exprs, val.left) ? - p.check_undefined_variables(exprs, val.right) ? + p.check_undefined_variables(exprs, val.left)? + p.check_undefined_variables(exprs, val.right)? } ast.IfExpr { - p.check_undefined_variables(exprs, val.left) ? + p.check_undefined_variables(exprs, val.left)? for branch in val.branches { - p.check_undefined_variables(exprs, branch.cond) ? + p.check_undefined_variables(exprs, branch.cond)? for stmt in branch.stmts { if stmt is ast.ExprStmt { - p.check_undefined_variables(exprs, stmt.expr) ? + p.check_undefined_variables(exprs, stmt.expr)? } } } } ast.MapInit { for key in val.keys { - p.check_undefined_variables(exprs, key) ? + p.check_undefined_variables(exprs, key)? } for value in val.vals { - p.check_undefined_variables(exprs, value) ? + p.check_undefined_variables(exprs, value)? } } ast.MatchExpr { - p.check_undefined_variables(exprs, val.cond) ? + p.check_undefined_variables(exprs, val.cond)? for branch in val.branches { for expr in branch.exprs { - p.check_undefined_variables(exprs, expr) ? + p.check_undefined_variables(exprs, expr)? } for stmt in branch.stmts { if stmt is ast.ExprStmt { - p.check_undefined_variables(exprs, stmt.expr) ? + p.check_undefined_variables(exprs, stmt.expr)? } } } } ast.ParExpr { - p.check_undefined_variables(exprs, val.expr) ? + p.check_undefined_variables(exprs, val.expr)? } ast.PostfixExpr { - p.check_undefined_variables(exprs, val.expr) ? + p.check_undefined_variables(exprs, val.expr)? } ast.PrefixExpr { - p.check_undefined_variables(exprs, val.right) ? + p.check_undefined_variables(exprs, val.right)? } ast.StringInterLiteral { for expr_ in val.exprs { - p.check_undefined_variables(exprs, expr_) ? + p.check_undefined_variables(exprs, expr_)? } } ast.StructInit { for field in val.fields { - p.check_undefined_variables(exprs, field.expr) ? + p.check_undefined_variables(exprs, field.expr)? } } else {} diff --git a/vlib/v/parser/tests/defer_propagate.out b/vlib/v/parser/tests/defer_propagate.out index 93dae37fc9..4b31249dd6 100644 --- a/vlib/v/parser/tests/defer_propagate.out +++ b/vlib/v/parser/tests/defer_propagate.out @@ -1,7 +1,7 @@ -vlib/v/parser/tests/defer_propagate.vv:9:15: error: error propagation not allowed inside `defer` blocks +vlib/v/parser/tests/defer_propagate.vv:9:14: error: error propagation not allowed inside `defer` blocks 7 | mut a := 0 8 | defer { - 9 | a = test1() ? - | ^ + 9 | a = test1()? + | ^ 10 | } 11 | return a diff --git a/vlib/v/parser/tests/defer_propagate.vv b/vlib/v/parser/tests/defer_propagate.vv index ad92bb9cd0..8a4876ed41 100644 --- a/vlib/v/parser/tests/defer_propagate.vv +++ b/vlib/v/parser/tests/defer_propagate.vv @@ -6,7 +6,7 @@ fn test1() ?int { fn test2() ?int { mut a := 0 defer { - a = test1() ? + a = test1()? } return a diff --git a/vlib/v/parser/tests/defer_propagate2.out b/vlib/v/parser/tests/defer_propagate2.out index 89962fb1c6..dbd68de80a 100644 --- a/vlib/v/parser/tests/defer_propagate2.out +++ b/vlib/v/parser/tests/defer_propagate2.out @@ -1,7 +1,7 @@ -vlib/v/parser/tests/defer_propagate2.vv:16:13: error: error propagation not allowed inside `defer` blocks +vlib/v/parser/tests/defer_propagate2.vv:16:12: error: error propagation not allowed inside `defer` blocks 14 | dump(s.x) 15 | defer { - 16 | s.close() ? - | ^ + 16 | s.close()? + | ^ 17 | } 18 | return s.x diff --git a/vlib/v/parser/tests/defer_propagate2.vv b/vlib/v/parser/tests/defer_propagate2.vv index 65c3b8e291..c46c96224b 100644 --- a/vlib/v/parser/tests/defer_propagate2.vv +++ b/vlib/v/parser/tests/defer_propagate2.vv @@ -13,11 +13,11 @@ fn opt2() ?int { mut s := Abc{} dump(s.x) defer { - s.close() ? + s.close()? } return s.x } fn main() { - println(opt2() ?) + println(opt2()?) } diff --git a/vlib/v/pkgconfig/main.v b/vlib/v/pkgconfig/main.v index cc27cc77e6..cfd4724288 100644 --- a/vlib/v/pkgconfig/main.v +++ b/vlib/v/pkgconfig/main.v @@ -94,7 +94,7 @@ pub fn (mut m Main) run() ?string { res += pcdep.description } if pc != 0 { - pc.extend(pcdep) ? + pc.extend(pcdep)? } else { pc = pcdep } diff --git a/vlib/v/pkgconfig/pkgconfig.v b/vlib/v/pkgconfig/pkgconfig.v index 3eec069825..54a1d673bb 100644 --- a/vlib/v/pkgconfig/pkgconfig.v +++ b/vlib/v/pkgconfig/pkgconfig.v @@ -190,10 +190,10 @@ pub fn (mut pc PkgConfig) extend(pcdep &PkgConfig) ?string { fn (mut pc PkgConfig) load_requires() ? { for dep in pc.requires { - pc.load_require(dep) ? + pc.load_require(dep)? } for dep in pc.requires_private { - pc.load_require(dep) ? + pc.load_require(dep)? } } @@ -210,8 +210,8 @@ fn (mut pc PkgConfig) load_require(dep string) ? { if !pcdep.parse(depfile) { return error('required file "$depfile" could not be parsed') } - pcdep.load_requires() ? - pc.extend(pcdep) ? + pcdep.load_requires()? + pc.extend(pcdep)? } fn (mut pc PkgConfig) add_path(path string) { @@ -253,7 +253,7 @@ pub fn load(pkgname string, options Options) ?&PkgConfig { return error('file "$file" could not be parsed') } if !options.norecurse { - pc.load_requires() ? + pc.load_requires()? } return pc } diff --git a/vlib/v/preludes/test_runner.v b/vlib/v/preludes/test_runner.v index 8abc80dd4f..b59f6b5c67 100644 --- a/vlib/v/preludes/test_runner.v +++ b/vlib/v/preludes/test_runner.v @@ -119,7 +119,7 @@ pub fn change_test_runner(x &TestRunner) { // TODO: remove vtest_option_cludge, it is only here so that // `vlib/sync/channel_close_test.v` compiles with simpler runners, -// that do not `import os` (which has other `fn() ?`). Without it, +// that do not `import os` (which has other `fn()?`). Without it, // the C `Option_void` type is undefined -> C compilation error. fn vtest_option_cludge() ? { } diff --git a/vlib/v/tests/anon_fn_returning_question_test.v b/vlib/v/tests/anon_fn_returning_question_test.v index 86b80bc5dd..b194614090 100644 --- a/vlib/v/tests/anon_fn_returning_question_test.v +++ b/vlib/v/tests/anon_fn_returning_question_test.v @@ -13,7 +13,7 @@ fn create_and_call_anon_function() ? { // filled with 0s => .ok was false, and that was treated // as a failure, triggering or blocks. } - should_not_call_block(x) ? + should_not_call_block(x)? assert true } diff --git a/vlib/v/tests/array_map_or_test.v b/vlib/v/tests/array_map_or_test.v index 1e62c74509..6e7142cc56 100644 --- a/vlib/v/tests/array_map_or_test.v +++ b/vlib/v/tests/array_map_or_test.v @@ -57,20 +57,20 @@ fn get_map_el(key string) ?int { 'qw': 4 'kl': 5 } - r := m[key] ? + r := m[key]? return r } fn get_arr_el(i int) ?int { m := [3, 4, 5] - r := m[i] ? + r := m[i]? return r } [direct_array_access] fn get_arr_el_direct(i int) ?int { m := [3, 4, 5] - r := m[i] ? + r := m[i]? return r } @@ -108,7 +108,7 @@ fn test_propagation() { fn get_arr_el_nested(i int) ?int { ind := [2, 1, 0, 5] m := [3, 4, 5] - r := m[ind[i]] ? + r := m[ind[i]]? return r } diff --git a/vlib/v/tests/array_methods_test.v b/vlib/v/tests/array_methods_test.v index d36017f2ae..13c24012d5 100644 --- a/vlib/v/tests/array_methods_test.v +++ b/vlib/v/tests/array_methods_test.v @@ -36,6 +36,6 @@ fn opt_bool_fn() ?bool { } fn test_any_called_with_opt_bool_fn() ? { - _ := [1, 2, 3].any(opt_bool_fn() ?) + _ := [1, 2, 3].any(opt_bool_fn()?) assert true } diff --git a/vlib/v/tests/cast_optional_to_interface_test.v b/vlib/v/tests/cast_optional_to_interface_test.v index 9d869da7fe..23c946cd25 100644 --- a/vlib/v/tests/cast_optional_to_interface_test.v +++ b/vlib/v/tests/cast_optional_to_interface_test.v @@ -21,7 +21,7 @@ fn new_0_parser() ?ParserV1 { } fn new_parser() ?Parser { - return Parser(new_0_parser() ?) + return Parser(new_0_parser()?) } struct Engine { @@ -29,7 +29,7 @@ struct Engine { } fn test_cast_optional_to_interface() ? { - parser := new_parser() ? + parser := new_parser()? assert parser.main.str == 'test' eprintln(voidptr(parser.main)) e := Engine{ diff --git a/vlib/v/tests/closure_generator_test.v b/vlib/v/tests/closure_generator_test.v index bd46fc2b9a..565ed0d66a 100644 --- a/vlib/v/tests/closure_generator_test.v +++ b/vlib/v/tests/closure_generator_test.v @@ -163,9 +163,9 @@ fn test_closure_return_${styp}_${i}() ? { code := v_code.str() println('Compiling V code (${code.count('\n')} lines) ...') wrkdir := os.join_path(os.temp_dir(), 'vtests', 'closures') - os.mkdir_all(wrkdir) ? - os.chdir(wrkdir) ? - os.write_file('closure_return_test.v', code) ? + os.mkdir_all(wrkdir)? + os.chdir(wrkdir)? + os.write_file('closure_return_test.v', code)? vexe := os.getenv('VEXE') res := os.execute('${os.quoted_path(vexe)} -keepc -cg -showcc closure_return_test.v') if res.exit_code != 0 { diff --git a/vlib/v/tests/const_can_use_optionals_test.v b/vlib/v/tests/const_can_use_optionals_test.v index c8d5a9c236..cbcca772b5 100644 --- a/vlib/v/tests/const_can_use_optionals_test.v +++ b/vlib/v/tests/const_can_use_optionals_test.v @@ -1,6 +1,6 @@ const ( - aaa = iopt() ? - bbb = sopt() ? + aaa = iopt()? + bbb = sopt()? ) fn iopt() ?int { diff --git a/vlib/v/tests/const_test.v b/vlib/v/tests/const_test.v index a3e664d518..583fd43598 100644 --- a/vlib/v/tests/const_test.v +++ b/vlib/v/tests/const_test.v @@ -32,7 +32,7 @@ fn foo_decode(name string) ?Foo { pub const ( def = foo_decode('baz') or { Foo{} } - bar = foo_decode('bar') ? + bar = foo_decode('bar')? ) fn test_opt_const() { diff --git a/vlib/v/tests/fn_mut_arg_of_interface_test.v b/vlib/v/tests/fn_mut_arg_of_interface_test.v index 7d96706455..d67fd83385 100644 --- a/vlib/v/tests/fn_mut_arg_of_interface_test.v +++ b/vlib/v/tests/fn_mut_arg_of_interface_test.v @@ -20,7 +20,7 @@ fn do(mut inter TheInterface) string { } fn test_fn_mut_arg_of_interface() ? { - mut inner := maker() ? + mut inner := maker()? ret := do(mut inner) println(ret) assert ret == 'ok' diff --git a/vlib/v/tests/fn_shared_return_test.v b/vlib/v/tests/fn_shared_return_test.v index 4df897f977..648993a788 100644 --- a/vlib/v/tests/fn_shared_return_test.v +++ b/vlib/v/tests/fn_shared_return_test.v @@ -29,7 +29,7 @@ fn test_shared_fn_return() { } fn shared_opt_propagate(good bool) ?f64 { - shared x := g(good) ? + shared x := g(good)? ret := rlock x { x.x } diff --git a/vlib/v/tests/generics_interface_with_multi_generic_structs_test.v b/vlib/v/tests/generics_interface_with_multi_generic_structs_test.v index 6f8b8fa939..719e3d1152 100644 --- a/vlib/v/tests/generics_interface_with_multi_generic_structs_test.v +++ b/vlib/v/tests/generics_interface_with_multi_generic_structs_test.v @@ -33,7 +33,7 @@ mut: fn (mut it SkipIter) next() ?T { for it.n > 0 { - it.iter.next() ? + it.iter.next()? it.n-- } return it.iter.next() diff --git a/vlib/v/tests/generics_with_nested_external_generics_fn_test.v b/vlib/v/tests/generics_with_nested_external_generics_fn_test.v index b98b6be90c..b9b7971e2d 100644 --- a/vlib/v/tests/generics_with_nested_external_generics_fn_test.v +++ b/vlib/v/tests/generics_with_nested_external_generics_fn_test.v @@ -4,7 +4,7 @@ pub fn sample(arr []T, k int) ?[]T { mut result := arr.clone() rand.seed([u32(1), 2]) // set seed to produce same results in order - rand.shuffle(mut result) ? + rand.shuffle(mut result)? return result[0..k] } @@ -13,7 +13,7 @@ fn test_generics_with_nested_external_generics_fn() ? { mut arr := [11, 32, 24, 45, 57, 32, 37, 52, 37, 24] println(arr) - ret := sample(arr, 5) ? + ret := sample(arr, 5)? println(ret) assert ret == [32, 45, 57, 11, 37] diff --git a/vlib/v/tests/go_wait_option_test.v b/vlib/v/tests/go_wait_option_test.v index ed910f3cbb..9912b5432a 100644 --- a/vlib/v/tests/go_wait_option_test.v +++ b/vlib/v/tests/go_wait_option_test.v @@ -39,8 +39,8 @@ fn test_opt_void_wait() { fn propagate(n int, m int) ?f64 { h1 := go f(n) h2 := go g(m) - r := h1.wait() ? - h2.wait() ? + r := h1.wait()? + h2.wait()? return r } diff --git a/vlib/v/tests/if_expression_test.v b/vlib/v/tests/if_expression_test.v index dedc6eb1e2..66d1c5b1da 100644 --- a/vlib/v/tests/if_expression_test.v +++ b/vlib/v/tests/if_expression_test.v @@ -222,7 +222,7 @@ fn test_if_expr_with_optional() ? { m := map[string]int{} v := if a := m['a'] { println('$a') - return_optional() ? + return_optional()? } else { 2 } diff --git a/vlib/v/tests/init_multiple_branches_test.v b/vlib/v/tests/init_multiple_branches_test.v index 0144101d0f..686abab714 100644 --- a/vlib/v/tests/init_multiple_branches_test.v +++ b/vlib/v/tests/init_multiple_branches_test.v @@ -20,7 +20,7 @@ fn test_init_multiple_branches() ? { t: m['t'] or { 0 }.bool() s: if a := m['a'] { println('a => $a') - b := return_optional(a) ? // Fails only if the expr in this line has or_block (or_block kind (.propagation or .block) doesn't matter) + b := return_optional(a)? // Fails only if the expr in this line has or_block (or_block kind (.propagation or .block) doesn't matter) b } else { map[string]Sum{} diff --git a/vlib/v/tests/inout/file.html b/vlib/v/tests/inout/file.html index ead45d24b4..d31a77acb0 100644 --- a/vlib/v/tests/inout/file.html +++ b/vlib/v/tests/inout/file.html @@ -23,7 +23,7 @@ color: red; diff --git a/vlib/v/tests/inout/tmpl_parse_html.out b/vlib/v/tests/inout/tmpl_parse_html.out index 23cfd0a1dd..6636a81d67 100644 --- a/vlib/v/tests/inout/tmpl_parse_html.out +++ b/vlib/v/tests/inout/tmpl_parse_html.out @@ -23,7 +23,7 @@ color: red; diff --git a/vlib/v/tests/known_errors/known_errors_test.v b/vlib/v/tests/known_errors/known_errors_test.v index 5fa69c2c0d..656d212273 100644 --- a/vlib/v/tests/known_errors/known_errors_test.v +++ b/vlib/v/tests/known_errors/known_errors_test.v @@ -7,7 +7,7 @@ const vroot = os.dir(vexe) const testdata_folder = 'vlib/v/tests/known_errors/testdata' fn test_known_errors_testdata_folder_exists() ? { - os.chdir(vroot) ? + os.chdir(vroot)? assert os.is_dir(testdata_folder) } diff --git a/vlib/v/tests/match_expr_with_assign_sumtype_test.v b/vlib/v/tests/match_expr_with_assign_sumtype_test.v index 3e1a17aafc..e793b86825 100644 --- a/vlib/v/tests/match_expr_with_assign_sumtype_test.v +++ b/vlib/v/tests/match_expr_with_assign_sumtype_test.v @@ -34,7 +34,7 @@ fn tokenise(args string) ?[]Value { match i { `0`...`9` { state = .parse_num - cur_value = int(i.str().parse_uint(10, 8) ?) + cur_value = int(i.str().parse_uint(10, 8)?) } `+`, `-`, `*`, `/` { state = .parse_operator @@ -67,7 +67,7 @@ fn tokenise(args string) ?[]Value { .parse_num { match i { `0`...`9` { - cur_value = 10 + int(i.str().parse_uint(10, 8) ?) + cur_value = 10 + int(i.str().parse_uint(10, 8)?) } `+`, `-`, `*`, `/` { state = .parse_operator @@ -94,7 +94,7 @@ fn tokenise(args string) ?[]Value { `0`...`9` { state = .parse_num rv << cur_value - cur_value = int(i.str().parse_uint(10, 8) ?) + cur_value = int(i.str().parse_uint(10, 8)?) } ` ` { state = .expecting @@ -115,7 +115,7 @@ fn parse_args(argv []string) ?Expression { rv := Expression{ val: 1 } - tokens := tokenise(argv.join(' ')) ? + tokens := tokenise(argv.join(' '))? println(tokens) assert '$tokens' == '[Value(1), Value(add), Value(subtract), Value(multiply), Value(divide)]' diff --git a/vlib/v/tests/nested_option_call_test.v b/vlib/v/tests/nested_option_call_test.v index f2857f295e..5fe69c57a5 100644 --- a/vlib/v/tests/nested_option_call_test.v +++ b/vlib/v/tests/nested_option_call_test.v @@ -16,7 +16,7 @@ fn test_nested_or() { } fn xx_prop() ?string { - s := ret(raise() ?) + s := ret(raise()?) return s } @@ -53,7 +53,7 @@ fn test_nested_or_method_call() { } fn (mut s St) aa_propagate() ? { - f := retf(s.raise() ?) + f := retf(s.raise()?) s.z = 7.5 println(f) } diff --git a/vlib/v/tests/option_2_test.v b/vlib/v/tests/option_2_test.v index 8537decd1f..3959616250 100644 --- a/vlib/v/tests/option_2_test.v +++ b/vlib/v/tests/option_2_test.v @@ -62,5 +62,5 @@ fn foo() ?string { } fn test_opt_subexp_field() ? { - assert foo() ?.len == 2 + assert foo()?.len == 2 } diff --git a/vlib/v/tests/option_test.v b/vlib/v/tests/option_test.v index dfa0c5e26a..4b715e6452 100644 --- a/vlib/v/tests/option_test.v +++ b/vlib/v/tests/option_test.v @@ -99,12 +99,12 @@ fn foo_str() ?string { } fn propagate_optional(b bool) ?int { - a := err_call(b) ? + a := err_call(b)? return a } fn propagate_different_type(b bool) ?bool { - err_call(b) ? + err_call(b)? return true } @@ -128,7 +128,7 @@ fn test_propagation() { } fn test_q() ? { - assert foo_ok() ? == 777 + assert foo_ok()? == 777 } fn or_return_val() int { diff --git a/vlib/v/tests/optional_multi_return_test.v b/vlib/v/tests/optional_multi_return_test.v index cff19acf24..e916f963a2 100644 --- a/vlib/v/tests/optional_multi_return_test.v +++ b/vlib/v/tests/optional_multi_return_test.v @@ -3,8 +3,8 @@ fn tuple() ?(int, int) { } fn test_optional_multi_return() ? { - println(tuple() ?) - a, b := tuple() ? + println(tuple()?) + a, b := tuple()? assert a == 1 assert b == 2 } diff --git a/vlib/v/tests/repl/runner/runner.v b/vlib/v/tests/repl/runner/runner.v index 0c7c08adcf..6710694ae0 100644 --- a/vlib/v/tests/repl/runner/runner.v +++ b/vlib/v/tests/repl/runner/runner.v @@ -52,7 +52,7 @@ pub fn run_repl_file(wd string, vexec string, file string) ?string { rcmd := '${os.quoted_path(vexec)} repl -replfolder ${os.quoted_path(wd)} -replprefix "${fname}." < ${os.quoted_path(input_temporary_filename)}' r := os.execute(rcmd) if r.exit_code != 0 { - os.rm(input_temporary_filename) ? + os.rm(input_temporary_filename)? return error('Could not execute: $rcmd') } result := r.output.replace('\r', '').replace('>>> ', '').replace('>>>', '').replace('... ', @@ -63,7 +63,7 @@ pub fn run_repl_file(wd string, vexec string, file string) ?string { dump(r.output) dump(result) } - os.rm(input_temporary_filename) ? + os.rm(input_temporary_filename)? if result != output { file_result := '${file}.result.txt' file_expected := '${file}.expected.txt' diff --git a/vlib/v/tests/results_test.v b/vlib/v/tests/results_test.v index defee142a8..9675517581 100644 --- a/vlib/v/tests/results_test.v +++ b/vlib/v/tests/results_test.v @@ -44,7 +44,7 @@ fn test_result_void_err() { } fn propagate() ! { - result_void(false) ! + result_void(false)! } fn test_propagation() { @@ -56,7 +56,7 @@ fn function_that_can_return_error() !int { } fn util_error_propagation() ! { - function_that_can_return_error() ! + function_that_can_return_error()! assert false } diff --git a/vlib/v/tests/return_optional_test.v b/vlib/v/tests/return_optional_test.v index 9e80a5bbfe..eb441a9ec3 100644 --- a/vlib/v/tests/return_optional_test.v +++ b/vlib/v/tests/return_optional_test.v @@ -3,11 +3,11 @@ fn func1() ?int { } fn func2() ?(int, int) { - return func1() ?, 1 + return func1()?, 1 } fn test_return_optional() ? { - a, b := func2() ? + a, b := func2()? println('$a, $b') assert a == 0 assert b == 1 diff --git a/vlib/v/tests/run_project_folders_test.v b/vlib/v/tests/run_project_folders_test.v index 651fb6fa62..8ed2dbb60a 100644 --- a/vlib/v/tests/run_project_folders_test.v +++ b/vlib/v/tests/run_project_folders_test.v @@ -13,7 +13,7 @@ fn test_vexe_exists() { fn test_v_profile_works() ? { os.chdir(vroot) or {} folders_root := os.join_path(vroot, 'vlib/v/tests/run_project_folders') - folder_names := os.ls(folders_root) ? + folder_names := os.ls(folders_root)? mut folder_paths := []string{} for fname in folder_names { folder_path := os.join_path(folders_root, fname) diff --git a/vlib/v/tests/run_v_code_from_stdin_test.v b/vlib/v/tests/run_v_code_from_stdin_test.v index 174bafb0b2..f751ec54a2 100644 --- a/vlib/v/tests/run_v_code_from_stdin_test.v +++ b/vlib/v/tests/run_v_code_from_stdin_test.v @@ -12,7 +12,7 @@ fn pipe_to_v_run() ? { cat_cmd := if os.user_os() == 'windows' { 'cmd /c type' } else { 'cat' } tmp_v_file := os.join_path(os.real_path(os.temp_dir()), 'generated_piped_program.v') // eprintln('>>> tmp_v_file: $tmp_v_file') - os.write_file(tmp_v_file, 'println(1 + 3)\nprintln("hello")\n') ? + os.write_file(tmp_v_file, 'println(1 + 3)\nprintln("hello")\n')? assert os.is_file(tmp_v_file) cmd := '$cat_cmd ${os.quoted_path(tmp_v_file)} | ${os.quoted_path(vexe)} run -' res := os.execute(cmd) diff --git a/vlib/v/tests/shared_fn_return_test.v b/vlib/v/tests/shared_fn_return_test.v index 70e2d8695f..1d5a45bfda 100644 --- a/vlib/v/tests/shared_fn_return_test.v +++ b/vlib/v/tests/shared_fn_return_test.v @@ -29,7 +29,7 @@ fn test_shared_fn_return() { } fn shared_opt_propagate(good bool) ?f64 { - shared x := g(good) ? + shared x := g(good)? ret := rlock x { x.x } diff --git a/vlib/v/tests/string_index_or_test.v b/vlib/v/tests/string_index_or_test.v index be48207b94..f7c8611599 100644 --- a/vlib/v/tests/string_index_or_test.v +++ b/vlib/v/tests/string_index_or_test.v @@ -39,7 +39,7 @@ fn test_if_guard_good() { } fn get_propagate(s string, i int) ?string { - c := s[i] ? + c := s[i]? return 'got `${c:c}`' } diff --git a/vlib/v/tests/testdata/tests_returning_options_failing_test.v b/vlib/v/tests/testdata/tests_returning_options_failing_test.v index a180006cb7..59a0c76da6 100644 --- a/vlib/v/tests/testdata/tests_returning_options_failing_test.v +++ b/vlib/v/tests/testdata/tests_returning_options_failing_test.v @@ -16,5 +16,5 @@ fn test_example() ? { fn test_example_2() ? { assert true assert true - example() ? + example()? } diff --git a/vlib/v/tests/valgrind/1.strings_and_arrays.v b/vlib/v/tests/valgrind/1.strings_and_arrays.v index 1c49315282..eff372041c 100644 --- a/vlib/v/tests/valgrind/1.strings_and_arrays.v +++ b/vlib/v/tests/valgrind/1.strings_and_arrays.v @@ -26,7 +26,7 @@ fn return_array(array_arg []string) []int { // array argument must not be freed } fn return_option(array_arg []string) ?Foo { // array argument must not be freed - s := get_foo() ? // escaping option must not be freed + s := get_foo()? // escaping option must not be freed return s } diff --git a/vlib/v/tests/valgrind/import_x_json2.v b/vlib/v/tests/valgrind/import_x_json2.v index 48576682c5..036ad8e75c 100644 --- a/vlib/v/tests/valgrind/import_x_json2.v +++ b/vlib/v/tests/valgrind/import_x_json2.v @@ -2,5 +2,5 @@ import x.json2 fn main() { x := '[[],[],[]]' - println(json2.raw_decode(x) ?) + println(json2.raw_decode(x)?) } diff --git a/vlib/v/tests/vsh_envbang_test.v b/vlib/v/tests/vsh_envbang_test.v index fcc71b0af0..2b4c774eae 100644 --- a/vlib/v/tests/vsh_envbang_test.v +++ b/vlib/v/tests/vsh_envbang_test.v @@ -19,14 +19,14 @@ fn test_envbang_script_runs() ? { import os println('hello') println(os.args) -") ? - os.chmod(rnd_vsh_script_path, 0o700) ? +")? + os.chmod(rnd_vsh_script_path, 0o700)? res := os.execute('${os.quoted_path(rnd_vsh_script_path)} abc 123 -option') assert res.exit_code == 0 lines := res.output.split_into_lines() assert lines[0] == 'hello' assert lines[1].ends_with(", 'abc', '123', '-option']") - os.rm(rnd_vsh_script_path) ? + os.rm(rnd_vsh_script_path)? } [noreturn] diff --git a/vlib/v/vcache/vcache.v b/vlib/v/vcache/vcache.v index 3401550827..35166bd9c7 100644 --- a/vlib/v/vcache/vcache.v +++ b/vlib/v/vcache/vcache.v @@ -111,14 +111,14 @@ pub fn (mut cm CacheManager) exists(postfix string, key string) ?string { pub fn (mut cm CacheManager) save(postfix string, key string, content string) ?string { fpath := cm.postfix_with_key2cpath(postfix, key) - os.write_file(fpath, content) ? + os.write_file(fpath, content)? dlog(@FN, 'postfix: $postfix | key: $key | fpath: $fpath') return fpath } pub fn (mut cm CacheManager) load(postfix string, key string) ?string { - fpath := cm.exists(postfix, key) ? - content := os.read_file(fpath) ? + fpath := cm.exists(postfix, key)? + content := os.read_file(fpath)? dlog(@FN, 'postfix: $postfix | key: $key | fpath: $fpath') return content } diff --git a/vlib/v/vmod/parser.v b/vlib/v/vmod/parser.v index f516c441e8..e59d09b90e 100644 --- a/vlib/v/vmod/parser.v +++ b/vlib/v/vmod/parser.v @@ -237,14 +237,14 @@ fn (mut p Parser) parse() ?Manifest { mn.author = field_value } 'dependencies' { - deps, idx := get_array_content(tokens, i + 1) ? + deps, idx := get_array_content(tokens, i + 1)? mn.dependencies = deps i = idx continue } else { if tokens[i + 1].typ == .labr { - vals, idx := get_array_content(tokens, i + 1) ? + vals, idx := get_array_content(tokens, i + 1)? mn.unknown[field_name] = vals i = idx continue diff --git a/vlib/v/vmod/parser_test.v b/vlib/v/vmod/parser_test.v index 3bd8b6e188..38a7ca0eb1 100644 --- a/vlib/v/vmod/parser_test.v +++ b/vlib/v/vmod/parser_test.v @@ -15,7 +15,7 @@ fn test_ok() ? { }" for s in [ok_source, ok_source.replace(apos, quote), ok_source.replace('\n', '\r\n'), ok_source.replace('\n', '\r\n '), ok_source.replace('\n', '\n ')] { - content := vmod.decode(s) ? + content := vmod.decode(s)? assert content.name == 'V' assert content.description == 'The V programming language.' assert content.version == '0.2.4' @@ -24,7 +24,7 @@ fn test_ok() ? { assert content.dependencies == [] assert content.unknown == {} } - e := vmod.decode('Module{}') ? + e := vmod.decode('Module{}')? assert e.name == '' assert e.description == '' assert e.version == '' diff --git a/vlib/vweb/sse/sse.v b/vlib/vweb/sse/sse.v index 986c61828c..1e0c444889 100644 --- a/vlib/vweb/sse/sse.v +++ b/vlib/vweb/sse/sse.v @@ -73,5 +73,5 @@ pub fn (mut sse SSEConnection) send_message(message SSEMessage) ? { sb.write_string('retry: $message.retry\n') } sb.write_string('\n') - sse.conn.write(sb) ? + sse.conn.write(sb)? } diff --git a/vlib/vweb/tests/vweb_test.v b/vlib/vweb/tests/vweb_test.v index 44e0ce1fc5..b900a006c3 100644 --- a/vlib/vweb/tests/vweb_test.v +++ b/vlib/vweb/tests/vweb_test.v @@ -111,15 +111,15 @@ fn test_a_simple_tcp_client_html_page() { // net.http client based tests follow: fn assert_common_http_headers(x http.Response) ? { assert x.status() == .ok - assert x.header.get(.server) ? == 'VWeb' - assert x.header.get(.content_length) ?.int() > 0 - assert x.header.get(.connection) ? == 'close' + assert x.header.get(.server)? == 'VWeb' + assert x.header.get(.content_length)?.int() > 0 + assert x.header.get(.connection)? == 'close' } fn test_http_client_index() ? { x := http.get('http://$localserver/') or { panic(err) } - assert_common_http_headers(x) ? - assert x.header.get(.content_type) ? == 'text/plain' + assert_common_http_headers(x)? + assert x.header.get(.content_type)? == 'text/plain' assert x.text == 'Welcome to VWeb' } @@ -137,35 +137,35 @@ fn test_http_client_404() ? { fn test_http_client_simple() ? { x := http.get('http://$localserver/simple') or { panic(err) } - assert_common_http_headers(x) ? - assert x.header.get(.content_type) ? == 'text/plain' + assert_common_http_headers(x)? + assert x.header.get(.content_type)? == 'text/plain' assert x.text == 'A simple result' } fn test_http_client_html_page() ? { x := http.get('http://$localserver/html_page') or { panic(err) } - assert_common_http_headers(x) ? - assert x.header.get(.content_type) ? == 'text/html' + assert_common_http_headers(x)? + assert x.header.get(.content_type)? == 'text/html' assert x.text == '

ok

' } fn test_http_client_settings_page() ? { x := http.get('http://$localserver/bilbo/settings') or { panic(err) } - assert_common_http_headers(x) ? + assert_common_http_headers(x)? assert x.text == 'username: bilbo' // y := http.get('http://$localserver/kent/settings') or { panic(err) } - assert_common_http_headers(y) ? + assert_common_http_headers(y)? assert y.text == 'username: kent' } fn test_http_client_user_repo_settings_page() ? { x := http.get('http://$localserver/bilbo/gostamp/settings') or { panic(err) } - assert_common_http_headers(x) ? + assert_common_http_headers(x)? assert x.text == 'username: bilbo | repository: gostamp' // y := http.get('http://$localserver/kent/golang/settings') or { panic(err) } - assert_common_http_headers(y) ? + assert_common_http_headers(y)? assert y.text == 'username: kent | repository: golang' // z := http.get('http://$localserver/missing/golang/settings') or { panic(err) } @@ -187,7 +187,7 @@ fn test_http_client_json_post() ? { $if debug_net_socket_client ? { eprintln('/json_echo endpoint response: $x') } - assert x.header.get(.content_type) ? == 'application/json' + assert x.header.get(.content_type)? == 'application/json' assert x.text == json_for_ouser nuser := json.decode(User, x.text) or { User{} } assert '$ouser' == '$nuser' @@ -196,7 +196,7 @@ fn test_http_client_json_post() ? { $if debug_net_socket_client ? { eprintln('/json endpoint response: $x') } - assert x.header.get(.content_type) ? == 'application/json' + assert x.header.get(.content_type)? == 'application/json' assert x.text == json_for_ouser nuser2 := json.decode(User, x.text) or { User{} } assert '$ouser' == '$nuser2' @@ -221,7 +221,7 @@ $contents\r value: ct ) data: data - ) ? + )? $if debug_net_socket_client ? { eprintln('/form_echo endpoint response: $x') } @@ -292,8 +292,8 @@ $config.content' $if debug_net_socket_client ? { eprintln('sending:\n$message') } - client.write(message.bytes()) ? - read := io.read_all(reader: client) ? + client.write(message.bytes())? + read := io.read_all(reader: client)? $if debug_net_socket_client ? { eprintln('received:\n$read') } diff --git a/vlib/vweb/tests/vweb_test_server.v b/vlib/vweb/tests/vweb_test_server.v index 6af589aff3..f53ac904be 100644 --- a/vlib/vweb/tests/vweb_test_server.v +++ b/vlib/vweb/tests/vweb_test_server.v @@ -44,7 +44,7 @@ fn main() { global_config: config } eprintln('>> webserver: started on http://localhost:$app.port/ , with maximum runtime of $app.timeout milliseconds.') - vweb.run_at(app, host: 'localhost', port: http_port, family: .ip) ? + vweb.run_at(app, host: 'localhost', port: http_port, family: .ip)? } // pub fn (mut app App) init_server() { diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index 8c131f6e81..630e911751 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -639,7 +639,7 @@ fn (mut ctx Context) scan_static_directory(directory_path string, mount_path str // If `root` is set the mount path for the dir will be in '/' // Usage: // ```v -// os.chdir( os.executable() ) ? +// os.chdir( os.executable() )? // app.handle_static('assets', true) // ``` pub fn (mut ctx Context) handle_static(directory_path string, root bool) bool { @@ -711,7 +711,7 @@ fn send_string(mut conn net.TcpConn, s string) ? { $if trace_response ? { eprintln('> send_string:\n$s\n') } - conn.write(s.bytes()) ? + conn.write(s.bytes())? } // Do not delete. diff --git a/vlib/x/json2/README.md b/vlib/x/json2/README.md index fcefbff7cb..75a1cf7e33 100644 --- a/vlib/x/json2/README.md +++ b/vlib/x/json2/README.md @@ -10,10 +10,10 @@ import net.http fn main() { // Decoding - resp := http.get('https://example.com') ? + resp := http.get('https://example.com')? // raw decode - raw_person := json2.raw_decode(resp.text) ? + raw_person := json2.raw_decode(resp.text)? // Casting `Any` type / Navigating person := raw_person.as_map() diff --git a/vlib/x/json2/decoder.v b/vlib/x/json2/decoder.v index 216921f76e..2a42d51633 100644 --- a/vlib/x/json2/decoder.v +++ b/vlib/x/json2/decoder.v @@ -142,8 +142,8 @@ fn new_parser(srce string, convert_type bool) Parser { fn (mut p Parser) decode() ?Any { p.next() - p.next_with_err() ? - fi := p.decode_value() ? + p.next_with_err()? + fi := p.decode_value()? if p.tok.kind != .eof { return IError(InvalidTokenError{ token: p.tok @@ -168,7 +168,7 @@ fn (mut p Parser) decode_value() ?Any { .int_, .float { tl := p.tok.lit.bytestr() kind := p.tok.kind - p.next_with_err() ? + p.next_with_err()? if p.convert_type { $if !nofloat ? { if kind == .float { @@ -181,14 +181,14 @@ fn (mut p Parser) decode_value() ?Any { } .bool_ { lit := p.tok.lit.bytestr() - p.next_with_err() ? + p.next_with_err()? if p.convert_type { return Any(lit.bool()) } return Any(lit) } .null { - p.next_with_err() ? + p.next_with_err()? if p.convert_type { return Any(null) } @@ -196,7 +196,7 @@ fn (mut p Parser) decode_value() ?Any { } .str_ { str := p.tok.lit.bytestr() - p.next_with_err() ? + p.next_with_err()? return Any(str) } else { @@ -211,13 +211,13 @@ fn (mut p Parser) decode_value() ?Any { [manualfree] fn (mut p Parser) decode_array() ?Any { mut items := []Any{} - p.next_with_err() ? + p.next_with_err()? p.n_level++ for p.tok.kind != .rsbr { - item := p.decode_value() ? + item := p.decode_value()? items << item if p.tok.kind == .comma { - p.next_with_err() ? + p.next_with_err()? if p.tok.kind == .rsbr { return IError(InvalidTokenError{ token: p.tok @@ -230,14 +230,14 @@ fn (mut p Parser) decode_array() ?Any { }) } } - p.next_with_err() ? + p.next_with_err()? p.n_level-- return Any(items) } fn (mut p Parser) decode_object() ?Any { mut fields := map[string]Any{} - p.next_with_err() ? + p.next_with_err()? p.n_level++ for p.tok.kind != .rcbr { if p.tok.kind != .str_ { @@ -248,7 +248,7 @@ fn (mut p Parser) decode_object() ?Any { } cur_key := p.tok.lit.bytestr() - p.next_with_err() ? + p.next_with_err()? if p.tok.kind != .colon { return IError(InvalidTokenError{ token: p.tok @@ -256,18 +256,18 @@ fn (mut p Parser) decode_object() ?Any { }) } - p.next_with_err() ? - fields[cur_key] = p.decode_value() ? + p.next_with_err()? + fields[cur_key] = p.decode_value()? if p.tok.kind != .comma && p.tok.kind != .rcbr { return IError(UnknownTokenError{ token: p.tok kind: .object }) } else if p.tok.kind == .comma { - p.next_with_err() ? + p.next_with_err()? } } - p.next_with_err() ? + p.next_with_err()? p.n_level-- return Any(fields) } diff --git a/vlib/x/json2/decoder_test.v b/vlib/x/json2/decoder_test.v index b2b3956a0c..898e0e5468 100644 --- a/vlib/x/json2/decoder_test.v +++ b/vlib/x/json2/decoder_test.v @@ -1,43 +1,43 @@ module json2 fn test_raw_decode_string() ? { - str := raw_decode('"Hello!"') ? + str := raw_decode('"Hello!"')? assert str.str() == 'Hello!' } fn test_raw_decode_string_escape() ? { - jstr := raw_decode('"\u001b"') ? + jstr := raw_decode('"\u001b"')? str := jstr.str() assert str.len == 1 assert str[0] == 27 } fn test_raw_decode_number() ? { - num := raw_decode('123') ? + num := raw_decode('123')? assert num.int() == 123 } fn test_raw_decode_array() ? { - raw_arr := raw_decode('["Foo", 1]') ? + raw_arr := raw_decode('["Foo", 1]')? arr := raw_arr.arr() assert arr[0] or { 0 }.str() == 'Foo' assert arr[1] or { 0 }.int() == 1 } fn test_raw_decode_bool() ? { - bol := raw_decode('false') ? + bol := raw_decode('false')? assert bol.bool() == false } fn test_raw_decode_map() ? { - raw_mp := raw_decode('{"name":"Bob","age":20}') ? + raw_mp := raw_decode('{"name":"Bob","age":20}')? mp := raw_mp.as_map() assert mp['name'] or { 0 }.str() == 'Bob' assert mp['age'] or { 0 }.int() == 20 } fn test_raw_decode_null() ? { - nul := raw_decode('null') ? + nul := raw_decode('null')? assert nul is Null } @@ -50,12 +50,12 @@ fn test_raw_decode_invalid() ? { } fn test_raw_decode_string_with_dollarsign() ? { - str := raw_decode(r'"Hello $world"') ? + str := raw_decode(r'"Hello $world"')? assert str.str() == r'Hello $world' } fn test_raw_decode_map_with_whitespaces() ? { - raw_mp := raw_decode(' \n\t{"name":"Bob","age":20}\n\t') ? + raw_mp := raw_decode(' \n\t{"name":"Bob","age":20}\n\t')? mp := raw_mp.as_map() assert mp['name'] or { 0 }.str() == 'Bob' assert mp['age'] or { 0 }.int() == 20 @@ -63,7 +63,7 @@ fn test_raw_decode_map_with_whitespaces() ? { fn test_nested_array_object() ? { mut parser := new_parser(r'[[[[[],[],[]]]],{"Test":{}},[[]]]', false) - decoded := parser.decode() ? + decoded := parser.decode()? assert parser.n_level == 0 } diff --git a/vlib/x/json2/encoder.v b/vlib/x/json2/encoder.v index 6f573503c3..4569e565f0 100644 --- a/vlib/x/json2/encoder.v +++ b/vlib/x/json2/encoder.v @@ -39,14 +39,14 @@ const escaped_chars = [(r'\b').bytes(), (r'\f').bytes(), (r'\n').bytes(), // encode_value encodes an `Any` value to the specific writer. pub fn (e &Encoder) encode_value(f Any, mut wr io.Writer) ? { - e.encode_value_with_level(f, 1, mut wr) ? + e.encode_value_with_level(f, 1, mut wr)? } fn (e &Encoder) encode_newline(level int, mut wr io.Writer) ? { if e.newline != 0 { - wr.write([e.newline]) ? + wr.write([e.newline])? for j := 0; j < level * e.newline_spaces_count; j++ { - wr.write(json2.space_bytes) ? + wr.write(json2.space_bytes)? } } } @@ -54,62 +54,62 @@ fn (e &Encoder) encode_newline(level int, mut wr io.Writer) ? { fn (e &Encoder) encode_value_with_level(f Any, level int, mut wr io.Writer) ? { match f { string { - e.encode_string(f, mut wr) ? + e.encode_string(f, mut wr)? } bool { if f == true { - wr.write(json2.true_in_bytes) ? + wr.write(json2.true_in_bytes)? } else { - wr.write(json2.false_in_bytes) ? + wr.write(json2.false_in_bytes)? } } int, u64, i64 { - wr.write(f.str().bytes()) ? + wr.write(f.str().bytes())? } f32, f64 { $if !nofloat ? { str_float := f.str().bytes() - wr.write(str_float) ? + wr.write(str_float)? if str_float[str_float.len - 1] == `.` { - wr.write(json2.zero_in_bytes) ? + wr.write(json2.zero_in_bytes)? } return } - wr.write(json2.zero_in_bytes) ? + wr.write(json2.zero_in_bytes)? } map[string]Any { - wr.write([u8(`{`)]) ? + wr.write([u8(`{`)])? mut i := 0 for k, v in f { - e.encode_newline(level, mut wr) ? - e.encode_string(k, mut wr) ? - wr.write(json2.colon_bytes) ? + e.encode_newline(level, mut wr)? + e.encode_string(k, mut wr)? + wr.write(json2.colon_bytes)? if e.newline != 0 { - wr.write(json2.space_bytes) ? + wr.write(json2.space_bytes)? } - e.encode_value_with_level(v, level + 1, mut wr) ? + e.encode_value_with_level(v, level + 1, mut wr)? if i < f.len - 1 { - wr.write(json2.comma_bytes) ? + wr.write(json2.comma_bytes)? } i++ } - e.encode_newline(level - 1, mut wr) ? - wr.write([u8(`}`)]) ? + e.encode_newline(level - 1, mut wr)? + wr.write([u8(`}`)])? } []Any { - wr.write([u8(`[`)]) ? + wr.write([u8(`[`)])? for i, v in f { - e.encode_newline(level, mut wr) ? - e.encode_value_with_level(v, level + 1, mut wr) ? + e.encode_newline(level, mut wr)? + e.encode_value_with_level(v, level + 1, mut wr)? if i < f.len - 1 { - wr.write(json2.comma_bytes) ? + wr.write(json2.comma_bytes)? } } - e.encode_newline(level - 1, mut wr) ? - wr.write([u8(`]`)]) ? + e.encode_newline(level - 1, mut wr)? + wr.write([u8(`]`)])? } Null { - wr.write(json2.null_in_bytes) ? + wr.write(json2.null_in_bytes)? } } } @@ -195,42 +195,42 @@ fn (e &Encoder) encode_string(s string, mut wr io.Writer) ? { text: s } mut i := 0 - wr.write(json2.quote_bytes) ? + wr.write(json2.quote_bytes)? for char_len in char_lens { if char_len == 1 { chr := s[i] if chr in important_escapable_chars { for j := 0; j < important_escapable_chars.len; j++ { if chr == important_escapable_chars[j] { - wr.write(json2.escaped_chars[j]) ? + wr.write(json2.escaped_chars[j])? break } } } else if chr == `"` || chr == `/` || chr == `\\` { - wr.write([u8(`\\`), chr]) ? + wr.write([u8(`\\`), chr])? } else if int(chr) < 0x20 { hex_code := chr.hex().bytes() - wr.write(json2.unicode_escape_chars) ? // \u - wr.write(json2.zero_in_bytes) ? // \u0 - wr.write(json2.zero_in_bytes) ? // \u00 - wr.write(hex_code) ? // \u00xxxx + wr.write(json2.unicode_escape_chars)? // \u + wr.write(json2.zero_in_bytes)? // \u0 + wr.write(json2.zero_in_bytes)? // \u00 + wr.write(hex_code)? // \u00xxxx } else { - wr.write([u8(chr)]) ? + wr.write([u8(chr)])? } } else { slice := s[i..i + char_len] hex_code := slice.utf32_code().hex().bytes() if !e.escape_unicode || hex_code.len < 4 { // unescaped non-ASCII char - wr.write(slice.bytes()) ? + wr.write(slice.bytes())? } else if hex_code.len == 4 { // a unicode endpoint - wr.write(json2.unicode_escape_chars) ? - wr.write(hex_code) ? + wr.write(json2.unicode_escape_chars)? + wr.write(hex_code)? } else { // TODO: still figuring out what // to do with more than 4 chars - wr.write(json2.space_bytes) ? + wr.write(json2.space_bytes)? } unsafe { slice.free() @@ -240,5 +240,5 @@ fn (e &Encoder) encode_string(s string, mut wr io.Writer) ? { i += char_len } - wr.write(json2.quote_bytes) ? + wr.write(json2.quote_bytes)? } diff --git a/vlib/x/json2/encoder_test.v b/vlib/x/json2/encoder_test.v index 07ce6f75f4..7c2dda2eb3 100644 --- a/vlib/x/json2/encoder_test.v +++ b/vlib/x/json2/encoder_test.v @@ -39,7 +39,7 @@ fn test_json_string_non_ascii() { fn test_utf8_strings_are_not_modified() ? { original := '{"s":"Schilddrüsenerkrankungen"}' // dump(original) - deresult := json2.raw_decode(original) ? + deresult := json2.raw_decode(original)? // dump(deresult) assert deresult.str() == original } @@ -51,13 +51,13 @@ fn test_encoder_unescaped_utf32() ? { } mut sb := strings.new_builder(20) - enc.encode_value(jap_text, mut sb) ? + enc.encode_value(jap_text, mut sb)? assert sb.str() == '"$jap_text"' sb.go_back_to(0) emoji_text := json2.Any('🐈') - enc.encode_value(emoji_text, mut sb) ? + enc.encode_value(emoji_text, mut sb)? assert sb.str() == '"$emoji_text"' } @@ -74,7 +74,7 @@ fn test_encoder_prettify() ? { newline_spaces_count: 2 } mut sb := strings.new_builder(20) - enc.encode_value(obj, mut sb) ? + enc.encode_value(obj, mut sb)? assert sb.str() == '{ "hello": "world", "arr": [ diff --git a/vlib/x/json2/json2.v b/vlib/x/json2/json2.v index e0ae391466..08d2d237a9 100644 --- a/vlib/x/json2/json2.v +++ b/vlib/x/json2/json2.v @@ -26,7 +26,7 @@ pub fn fast_raw_decode(src string) ?Any { // decode is a generic function that decodes a JSON string into the target type. pub fn decode(src string) ?T { - res := raw_decode(src) ? + res := raw_decode(src)? mut typ := T{} typ.from_json(res) return typ