ci: fix `v test-cleancode`

pull/8332/head
Delyan Angelov 2021-01-25 11:26:20 +02:00
parent 94fd3ff431
commit 728344ff65
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
49 changed files with 353 additions and 356 deletions

View File

@ -247,7 +247,7 @@ fn (mut vd VDoc) generate_docs_from_file() {
exit(1) exit(1)
} }
dir_path := if cfg.is_vlib { dir_path := if cfg.is_vlib {
vroot main.vroot
} else if os.is_dir(cfg.input_path) { } else if os.is_dir(cfg.input_path) {
cfg.input_path cfg.input_path
} else { } else {
@ -404,8 +404,8 @@ fn parse_arguments(args []string) Config {
} }
'-f' { '-f' {
format := cmdline.option(current_args, '-f', '') format := cmdline.option(current_args, '-f', '')
if format !in allowed_formats { if format !in main.allowed_formats {
allowed_str := allowed_formats.join(', ') allowed_str := main.allowed_formats.join(', ')
eprintln('vdoc: "$format" is not a valid format. Only $allowed_str are allowed.') eprintln('vdoc: "$format" is not a valid format. Only $allowed_str are allowed.')
exit(1) exit(1)
} }
@ -472,7 +472,7 @@ fn parse_arguments(args []string) Config {
if cfg.input_path.trim_right('/') == 'vlib' { if cfg.input_path.trim_right('/') == 'vlib' {
cfg.is_vlib = true cfg.is_vlib = true
cfg.is_multi = true cfg.is_multi = true
cfg.input_path = os.join_path(vroot, 'vlib') cfg.input_path = os.join_path(main.vroot, 'vlib')
} else if !is_path { } else if !is_path {
// TODO vd.vprintln('Input "$cfg.input_path" is not a valid path. Looking for modules named "$cfg.input_path"...') // TODO vd.vprintln('Input "$cfg.input_path" is not a valid path. Looking for modules named "$cfg.input_path"...')
mod_path := doc.lookup_module(cfg.input_path) or { mod_path := doc.lookup_module(cfg.input_path) or {
@ -486,7 +486,7 @@ fn parse_arguments(args []string) Config {
fn main() { fn main() {
if os.args.len < 2 || '-h' in os.args || '--help' in os.args || os.args[1..] == ['doc', 'help'] { if os.args.len < 2 || '-h' in os.args || '--help' in os.args || os.args[1..] == ['doc', 'help'] {
os.system('$vexe help doc') os.system('$main.vexe help doc')
exit(0) exit(0)
} }
args := os.args[2..].clone() args := os.args[2..].clone()

View File

@ -75,21 +75,21 @@ fn (cmd Command) help_message() string {
help += '\n$cmd.description\n' help += '\n$cmd.description\n'
} }
mut abbrev_len := 0 mut abbrev_len := 0
mut name_len := min_description_indent_len mut name_len := cli.min_description_indent_len
if cmd.flags.have_abbrev() { if cmd.flags.have_abbrev() {
for flag in cmd.flags { for flag in cmd.flags {
abbrev_len = max(abbrev_len, flag.abbrev.len + spacing + 1) // + 1 for '-' in front abbrev_len = max(abbrev_len, flag.abbrev.len + cli.spacing + 1) // + 1 for '-' in front
name_len = max(name_len, abbrev_len + flag.name.len + spacing + 2) // + 2 for '--' in front name_len = max(name_len, abbrev_len + flag.name.len + cli.spacing + 2) // + 2 for '--' in front
} }
for command in cmd.commands { for command in cmd.commands {
name_len = max(name_len, command.name.len + spacing) name_len = max(name_len, command.name.len + cli.spacing)
} }
} else { } else {
for flag in cmd.flags { for flag in cmd.flags {
name_len = max(name_len, abbrev_len + flag.name.len + spacing + 1) // + 1 for '-' in front name_len = max(name_len, abbrev_len + flag.name.len + cli.spacing + 1) // + 1 for '-' in front
} }
for command in cmd.commands { for command in cmd.commands {
name_len = max(name_len, command.name.len + spacing) name_len = max(name_len, command.name.len + cli.spacing)
} }
} }
if cmd.flags.len > 0 { if cmd.flags.len > 0 {
@ -109,16 +109,17 @@ fn (cmd Command) help_message() string {
if flag.required { if flag.required {
required = ' (required)' required = ' (required)'
} }
base_indent := ' '.repeat(base_indent_len) base_indent := ' '.repeat(cli.base_indent_len)
description_indent := ' '.repeat(name_len - flag_name.len) description_indent := ' '.repeat(name_len - flag_name.len)
help += '$base_indent$flag_name$description_indent' + help += '$base_indent$flag_name$description_indent' +
pretty_description(flag.description + required, base_indent_len + name_len) + '\n' pretty_description(flag.description + required, cli.base_indent_len + name_len) +
'\n'
} }
} }
if cmd.commands.len > 0 { if cmd.commands.len > 0 {
help += '\nCommands:\n' help += '\nCommands:\n'
for command in cmd.commands { for command in cmd.commands {
base_indent := ' '.repeat(base_indent_len) base_indent := ' '.repeat(cli.base_indent_len)
description_indent := ' '.repeat(name_len - command.name.len) description_indent := ' '.repeat(name_len - command.name.len)
help += '$base_indent$command.name$description_indent' + help += '$base_indent$command.name$description_indent' +
pretty_description(command.description, name_len) + '\n' pretty_description(command.description, name_len) + '\n'

View File

@ -50,7 +50,7 @@ pub const (
pub fn new_flag_parser(args []string) &FlagParser { pub fn new_flag_parser(args []string) &FlagParser {
return &FlagParser{ return &FlagParser{
args: args.clone() args: args.clone()
max_free_args: max_args_number max_free_args: flag.max_args_number
} }
} }
@ -303,8 +303,8 @@ pub fn (mut fs FlagParser) string(name string, abbr byte, sdefault string, usage
} }
pub fn (mut fs FlagParser) limit_free_args_to_at_least(n int) { pub fn (mut fs FlagParser) limit_free_args_to_at_least(n int) {
if n > max_args_number { if n > flag.max_args_number {
panic('flag.limit_free_args_to_at_least expect n to be smaller than $max_args_number') panic('flag.limit_free_args_to_at_least expect n to be smaller than $flag.max_args_number')
} }
if n <= 0 { if n <= 0 {
panic('flag.limit_free_args_to_at_least expect n to be a positive number') panic('flag.limit_free_args_to_at_least expect n to be a positive number')
@ -313,8 +313,8 @@ pub fn (mut fs FlagParser) limit_free_args_to_at_least(n int) {
} }
pub fn (mut fs FlagParser) limit_free_args_to_exactly(n int) { pub fn (mut fs FlagParser) limit_free_args_to_exactly(n int) {
if n > max_args_number { if n > flag.max_args_number {
panic('flag.limit_free_args_to_exactly expect n to be smaller than $max_args_number') panic('flag.limit_free_args_to_exactly expect n to be smaller than $flag.max_args_number')
} }
if n < 0 { if n < 0 {
panic('flag.limit_free_args_to_exactly expect n to be a non negative number') panic('flag.limit_free_args_to_exactly expect n to be a non negative number')
@ -340,7 +340,7 @@ pub fn (mut fs FlagParser) arguments_description(description string) {
// collect all given information and // collect all given information and
pub fn (fs FlagParser) usage() string { pub fn (fs FlagParser) usage() string {
positive_min_arg := (fs.min_free_args > 0) positive_min_arg := (fs.min_free_args > 0)
positive_max_arg := (fs.max_free_args > 0 && fs.max_free_args != max_args_number) positive_max_arg := (fs.max_free_args > 0 && fs.max_free_args != flag.max_args_number)
no_arguments := (fs.min_free_args == 0 && fs.max_free_args == 0) no_arguments := (fs.min_free_args == 0 && fs.max_free_args == 0)
mut adesc := if fs.args_description.len > 0 { fs.args_description } else { '[ARGS]' } mut adesc := if fs.args_description.len > 0 { fs.args_description } else { '[ARGS]' }
if no_arguments { if no_arguments {
@ -349,7 +349,7 @@ pub fn (fs FlagParser) usage() string {
mut use := '' mut use := ''
if fs.application_version != '' { if fs.application_version != '' {
use += '$fs.application_name $fs.application_version\n' use += '$fs.application_name $fs.application_version\n'
use += '$underline\n' use += '$flag.underline\n'
} }
use += 'Usage: $fs.application_name [options] $adesc\n' use += 'Usage: $fs.application_name [options] $adesc\n'
use += '\n' use += '\n'
@ -394,10 +394,10 @@ pub fn (fs FlagParser) usage() string {
} }
option_names := ' ' + onames.join(', ') option_names := ' ' + onames.join(', ')
mut xspace := '' mut xspace := ''
if option_names.len > space.len - 2 { if option_names.len > flag.space.len - 2 {
xspace = '\n$space' xspace = '\n$flag.space'
} else { } else {
xspace = space[option_names.len..] xspace = flag.space[option_names.len..]
} }
use += '$option_names$xspace$f.usage\n' use += '$option_names$xspace$f.usage\n'
} }

View File

@ -112,7 +112,7 @@ pub fn from_string(input string) Number {
mut n := from_int(0) mut n := from_int(0)
for _, c in input { for _, c in input {
d := from_int(int(c - `0`)) d := from_int(int(c - `0`))
n = (n * ten) + d n = (n * big.ten) + d
} }
return n return n
} }
@ -136,7 +136,7 @@ pub fn (n Number) str() string {
mut x := n.clone() mut x := n.clone()
div := Number{} div := Number{}
for !x.is_zero() { for !x.is_zero() {
mod := divmod(&x, &ten, &div) mod := divmod(&x, &big.ten, &div)
digits << byte(mod.int()) + `0` digits << byte(mod.int()) + `0`
x = div x = div
} }

View File

@ -8,18 +8,18 @@ const (
) )
fn testsuite_begin() { fn testsuite_begin() {
eprintln('testsuite_begin, tfolder = $tfolder') eprintln('testsuite_begin, tfolder = $main.tfolder')
os.rmdir_all(tfolder) os.rmdir_all(main.tfolder)
assert !os.is_dir(tfolder) assert !os.is_dir(main.tfolder)
os.mkdir_all(tfolder) os.mkdir_all(main.tfolder)
os.chdir(tfolder) os.chdir(main.tfolder)
assert os.is_dir(tfolder) assert os.is_dir(main.tfolder)
} }
fn testsuite_end() { fn testsuite_end() {
os.chdir(os.wd_at_startup) os.chdir(os.wd_at_startup)
os.rmdir_all(tfolder) os.rmdir_all(main.tfolder)
assert !os.is_dir(tfolder) assert !os.is_dir(main.tfolder)
} }
fn test_inode_file_type() { fn test_inode_file_type() {

View File

@ -330,11 +330,11 @@ pub fn write_file_array(path string, buffer array) ? {
// It relies on path manipulation of os.args[0] and os.wd_at_startup, so it may not work properly in // It relies on path manipulation of os.args[0] and os.wd_at_startup, so it may not work properly in
// all cases, but it should be better, than just using os.args[0] directly. // all cases, but it should be better, than just using os.args[0] directly.
fn executable_fallback() string { fn executable_fallback() string {
if args.len == 0 { if os.args.len == 0 {
// we are early in the bootstrap, os.args has not been initialized yet :-| // we are early in the bootstrap, os.args has not been initialized yet :-|
return '' return ''
} }
mut exepath := args[0] mut exepath := os.args[0]
$if windows { $if windows {
if !exepath.contains('.exe') { if !exepath.contains('.exe') {
exepath += '.exe' exepath += '.exe'
@ -342,7 +342,7 @@ fn executable_fallback() string {
} }
if !is_abs_path(exepath) { if !is_abs_path(exepath) {
if exepath.contains(path_separator) { if exepath.contains(path_separator) {
exepath = join_path(wd_at_startup, exepath) exepath = join_path(os.wd_at_startup, exepath)
} else { } else {
// no choice but to try to walk the PATH folders :-| ... // no choice but to try to walk the PATH folders :-| ...
foundpath := find_abs_path_of_executable(exepath) or { '' } foundpath := find_abs_path_of_executable(exepath) or { '' }

View File

@ -12,21 +12,21 @@ const (
const args_at_start = os.args.clone() const args_at_start = os.args.clone()
fn testsuite_begin() { fn testsuite_begin() {
eprintln('testsuite_begin, tfolder = $tfolder') eprintln('testsuite_begin, tfolder = $main.tfolder')
os.rmdir_all(tfolder) os.rmdir_all(main.tfolder)
assert !os.is_dir(tfolder) assert !os.is_dir(main.tfolder)
os.mkdir_all(tfolder) os.mkdir_all(main.tfolder)
os.chdir(tfolder) os.chdir(main.tfolder)
assert os.is_dir(tfolder) assert os.is_dir(main.tfolder)
// println('args_at_start: $args_at_start') // println('args_at_start: $args_at_start')
assert args_at_start.len > 0 assert main.args_at_start.len > 0
assert args_at_start == os.args assert main.args_at_start == os.args
} }
fn testsuite_end() { fn testsuite_end() {
os.chdir(os.wd_at_startup) os.chdir(os.wd_at_startup)
os.rmdir_all(tfolder) os.rmdir_all(main.tfolder)
assert !os.is_dir(tfolder) assert !os.is_dir(main.tfolder)
// eprintln('testsuite_end , tfolder = $tfolder removed.') // eprintln('testsuite_end , tfolder = $tfolder removed.')
} }
@ -434,8 +434,8 @@ struct IntPoint {
fn test_write_file_array_bytes() { fn test_write_file_array_bytes() {
fpath := './abytes.bin' fpath := './abytes.bin'
mut arr := []byte{len: maxn} mut arr := []byte{len: main.maxn}
for i in 0 .. maxn { for i in 0 .. main.maxn {
arr[i] = 65 + byte(i) arr[i] = 65 + byte(i)
} }
os.write_file_array(fpath, arr) os.write_file_array(fpath, arr)
@ -447,14 +447,14 @@ fn test_write_file_array_bytes() {
fn test_write_file_array_structs() { fn test_write_file_array_structs() {
fpath := './astructs.bin' fpath := './astructs.bin'
mut arr := []IntPoint{len: maxn} mut arr := []IntPoint{len: main.maxn}
for i in 0 .. maxn { for i in 0 .. main.maxn {
arr[i] = IntPoint{65 + i, 65 + i + 10} arr[i] = IntPoint{65 + i, 65 + i + 10}
} }
os.write_file_array(fpath, arr) os.write_file_array(fpath, arr)
rarr := os.read_file_array<IntPoint>(fpath) rarr := os.read_file_array<IntPoint>(fpath)
assert rarr == arr assert rarr == arr
assert rarr.len == maxn assert rarr.len == main.maxn
// eprintln( rarr.str().replace('\n', ' ').replace('},', '},\n')) // eprintln( rarr.str().replace('\n', ' ').replace('},', '},\n'))
} }

View File

@ -199,11 +199,12 @@ const (
fn ptr_win_get_error_msg(code u32) voidptr { fn ptr_win_get_error_msg(code u32) voidptr {
mut buf := voidptr(0) mut buf := voidptr(0)
// Check for code overflow // Check for code overflow
if code > u32(max_error_code) { if code > u32(os.max_error_code) {
return buf return buf
} }
C.FormatMessage(format_message_allocate_buffer | format_message_from_system | format_message_ignore_inserts, C.FormatMessage(os.format_message_allocate_buffer | os.format_message_from_system | os.format_message_ignore_inserts,
0, code, C.MAKELANGID(lang_neutral, sublang_default), voidptr(&buf), 0, 0) 0, code, C.MAKELANGID(os.lang_neutral, os.sublang_default), voidptr(&buf), 0,
0)
return buf return buf
} }

View File

@ -43,8 +43,9 @@ fn (ver RawVersion) is_valid() bool {
if ver.raw_ints.len != 3 { if ver.raw_ints.len != 3 {
return false return false
} }
return is_valid_number(ver.raw_ints[ver_major]) && is_valid_number(ver.raw_ints[ver_minor]) return is_valid_number(ver.raw_ints[semver.ver_major])
&& is_valid_number(ver.raw_ints[ver_patch]) && is_valid_string(ver.prerelease) && is_valid_number(ver.raw_ints[semver.ver_minor])
&& is_valid_number(ver.raw_ints[semver.ver_patch]) && is_valid_string(ver.prerelease)
&& is_valid_string(ver.metadata) && is_valid_string(ver.metadata)
} }
@ -54,7 +55,7 @@ fn (ver RawVersion) is_missing(typ int) bool {
fn (raw_ver RawVersion) coerce() ?Version { fn (raw_ver RawVersion) coerce() ?Version {
ver := raw_ver.complete() ver := raw_ver.complete()
if !is_valid_number(ver.raw_ints[ver_major]) { if !is_valid_number(ver.raw_ints[semver.ver_major]) {
return error('Invalid major version: $ver.raw_ints[ver_major]') return error('Invalid major version: $ver.raw_ints[ver_major]')
} }
return ver.to_version() return ver.to_version()
@ -80,5 +81,5 @@ fn (raw_ver RawVersion) validate() ?Version {
} }
fn (raw_ver RawVersion) to_version() Version { fn (raw_ver RawVersion) to_version() Version {
return Version{raw_ver.raw_ints[ver_major].int(), raw_ver.raw_ints[ver_minor].int(), raw_ver.raw_ints[ver_patch].int(), raw_ver.prerelease, raw_ver.metadata} return Version{raw_ver.raw_ints[semver.ver_major].int(), raw_ver.raw_ints[semver.ver_minor].int(), raw_ver.raw_ints[semver.ver_patch].int(), raw_ver.prerelease, raw_ver.metadata}
} }

View File

@ -57,7 +57,7 @@ fn (c Comparator) satisfies(ver Version) bool {
} }
fn parse_range(input string) ?Range { fn parse_range(input string) ?Range {
raw_comparator_sets := input.split(comparator_set_sep) raw_comparator_sets := input.split(semver.comparator_set_sep)
mut comparator_sets := []ComparatorSet{} mut comparator_sets := []ComparatorSet{}
for raw_comp_set in raw_comparator_sets { for raw_comp_set in raw_comparator_sets {
if can_expand(raw_comp_set) { if can_expand(raw_comp_set) {
@ -72,7 +72,7 @@ fn parse_range(input string) ?Range {
} }
fn parse_comparator_set(input string) ?ComparatorSet { fn parse_comparator_set(input string) ?ComparatorSet {
raw_comparators := input.split(comparator_sep) raw_comparators := input.split(semver.comparator_sep)
if raw_comparators.len > 2 { if raw_comparators.len > 2 {
return error('Invalid format of comparator set for input "$input"') return error('Invalid format of comparator set for input "$input"')
} }
@ -113,7 +113,7 @@ fn parse_comparator(input string) ?Comparator {
fn parse_xrange(input string) ?Version { fn parse_xrange(input string) ?Version {
mut raw_ver := parse(input).complete() mut raw_ver := parse(input).complete()
for typ in versions { for typ in versions {
if raw_ver.raw_ints[typ].index_any(x_range_symbols) == -1 { if raw_ver.raw_ints[typ].index_any(semver.x_range_symbols) == -1 {
continue continue
} }
match typ { match typ {
@ -139,8 +139,8 @@ fn parse_xrange(input string) ?Version {
} }
fn can_expand(input string) bool { fn can_expand(input string) bool {
return input[0] == `~` || input[0] == `^` || input.contains(hyphen_range_sep) return input[0] == `~` || input[0] == `^` || input.contains(semver.hyphen_range_sep)
|| input.index_any(x_range_symbols) > -1 || input.index_any(semver.x_range_symbols) > -1
} }
fn expand_comparator_set(input string) ?ComparatorSet { fn expand_comparator_set(input string) ?ComparatorSet {
@ -149,7 +149,7 @@ fn expand_comparator_set(input string) ?ComparatorSet {
`^` { return expand_caret(input[1..]) } `^` { return expand_caret(input[1..]) }
else {} else {}
} }
if input.contains(hyphen_range_sep) { if input.contains(semver.hyphen_range_sep) {
return expand_hyphen(input) return expand_hyphen(input)
} }
return expand_xrange(input) return expand_xrange(input)
@ -178,7 +178,7 @@ fn expand_caret(raw_version string) ?ComparatorSet {
} }
fn expand_hyphen(raw_range string) ?ComparatorSet { fn expand_hyphen(raw_range string) ?ComparatorSet {
raw_versions := raw_range.split(hyphen_range_sep) raw_versions := raw_range.split(semver.hyphen_range_sep)
if raw_versions.len != 2 { if raw_versions.len != 2 {
return none return none
} }

View File

@ -76,7 +76,7 @@ const (
) )
fn test_from() { fn test_from() {
for item in versions_to_test { for item in main.versions_to_test {
ver := semver.from(item.raw) or { ver := semver.from(item.raw) or {
assert false assert false
return return
@ -87,7 +87,7 @@ fn test_from() {
assert ver.metadata == item.metadata assert ver.metadata == item.metadata
assert ver.prerelease == item.prerelease assert ver.prerelease == item.prerelease
} }
for ver in invalid_versions_to_test { for ver in main.invalid_versions_to_test {
semver.from(ver) or { semver.from(ver) or {
assert true assert true
continue continue
@ -140,7 +140,7 @@ fn test_compare() {
} }
fn test_satisfies() { fn test_satisfies() {
for item in ranges_to_test { for item in main.ranges_to_test {
ver := semver.from(item.raw_version) or { ver := semver.from(item.raw_version) or {
assert false assert false
return return
@ -155,13 +155,13 @@ fn test_satisfies_invalid() {
assert false assert false
return return
} }
for item in invalid_ranges_to_test { for item in main.invalid_ranges_to_test {
assert ver.satisfies(item) == false assert ver.satisfies(item) == false
} }
} }
fn test_coerce() { fn test_coerce() {
for item in coerce_to_test { for item in main.coerce_to_test {
valid := semver.from(item.valid) or { valid := semver.from(item.valid) or {
assert false assert false
return return
@ -183,10 +183,10 @@ fn test_coerce_invalid() {
} }
fn test_is_valid() { fn test_is_valid() {
for item in versions_to_test { for item in main.versions_to_test {
assert semver.is_valid(item.raw) assert semver.is_valid(item.raw)
} }
for item in invalid_versions_to_test { for item in main.invalid_versions_to_test {
assert semver.is_valid(item) == false assert semver.is_valid(item) == false
} }
} }

View File

@ -9,5 +9,5 @@ const (
// random returns a random time struct in *the past*. // random returns a random time struct in *the past*.
pub fn random() time.Time { pub fn random() time.Time {
return time.unix(int(rand.u64n(start_time_unix))) return time.unix(int(rand.u64n(misc.start_time_unix)))
} }

View File

@ -13,9 +13,9 @@ const (
// but otherwise can be changed at will. // but otherwise can be changed at will.
absolute_zero_year = i64(-292277022399) // as i64 absolute_zero_year = i64(-292277022399) // as i64
seconds_per_minute = 60 seconds_per_minute = 60
seconds_per_hour = 60 * time.seconds_per_minute seconds_per_hour = 60 * seconds_per_minute
seconds_per_day = 24 * time.seconds_per_hour seconds_per_day = 24 * seconds_per_hour
seconds_per_week = 7 * time.seconds_per_day seconds_per_week = 7 * seconds_per_day
days_per_400_years = 365 * 400 + 97 days_per_400_years = 365 * 400 + 97
days_per_100_years = 365 * 100 + 24 days_per_100_years = 365 * 100 + 24
days_per_4_years = 365 * 4 + 1 days_per_4_years = 365 * 4 + 1
@ -392,11 +392,11 @@ pub type Duration = i64
pub const ( pub const (
nanosecond = Duration(1) nanosecond = Duration(1)
microsecond = Duration(1000 * time.nanosecond) microsecond = Duration(1000 * nanosecond)
millisecond = Duration(1000 * time.microsecond) millisecond = Duration(1000 * microsecond)
second = Duration(1000 * time.millisecond) second = Duration(1000 * millisecond)
minute = Duration(60 * time.second) minute = Duration(60 * second)
hour = Duration(60 * time.minute) hour = Duration(60 * minute)
infinite = Duration(-1) infinite = Duration(-1)
) )

View File

@ -40,10 +40,10 @@ fn init_time_base() C.mach_timebase_info_data_t {
fn sys_mono_now_darwin() u64 { fn sys_mono_now_darwin() u64 {
tm := C.mach_absolute_time() tm := C.mach_absolute_time()
if time_base.denom == 0 { if time.time_base.denom == 0 {
C.mach_timebase_info(&time_base) C.mach_timebase_info(&time.time_base)
} }
return (tm - start_time) * time_base.numer / time_base.denom return (tm - time.start_time) * time.time_base.numer / time.time_base.denom
} }
// NB: vpc_now_darwin is used by `v -profile` . // NB: vpc_now_darwin is used by `v -profile` .
@ -51,10 +51,10 @@ fn sys_mono_now_darwin() u64 {
[inline] [inline]
fn vpc_now_darwin() u64 { fn vpc_now_darwin() u64 {
tm := C.mach_absolute_time() tm := C.mach_absolute_time()
if time_base.denom == 0 { if time.time_base.denom == 0 {
C.mach_timebase_info(&time_base) C.mach_timebase_info(&time.time_base)
} }
return (tm - start_time) * time_base.numer / time_base.denom return (tm - time.start_time) * time.time_base.numer / time.time_base.denom
} }
// darwin_now returns a better precision current time for Darwin based operating system // darwin_now returns a better precision current time for Darwin based operating system

View File

@ -19,70 +19,70 @@ fn test_now_format() {
} }
fn test_format() { fn test_format() {
assert '11.07.1980 21:23' == time_to_test.get_fmt_str(.dot, .hhmm24, .ddmmyyyy) assert '11.07.1980 21:23' == main.time_to_test.get_fmt_str(.dot, .hhmm24, .ddmmyyyy)
} }
fn test_hhmm() { fn test_hhmm() {
assert '21:23' == time_to_test.hhmm() assert '21:23' == main.time_to_test.hhmm()
} }
fn test_hhmm12() { fn test_hhmm12() {
assert '9:23 p.m.' == time_to_test.hhmm12() assert '9:23 p.m.' == main.time_to_test.hhmm12()
} }
fn test_hhmmss() { fn test_hhmmss() {
assert '21:23:42' == time_to_test.hhmmss() assert '21:23:42' == main.time_to_test.hhmmss()
} }
fn test_ymmdd() { fn test_ymmdd() {
assert '1980-07-11' == time_to_test.ymmdd() assert '1980-07-11' == main.time_to_test.ymmdd()
} }
fn test_ddmmy() { fn test_ddmmy() {
assert '11.07.1980' == time_to_test.ddmmy() assert '11.07.1980' == main.time_to_test.ddmmy()
} }
fn test_md() { fn test_md() {
assert 'Jul 11' == time_to_test.md() assert 'Jul 11' == main.time_to_test.md()
} }
fn test_get_fmt_time_str() { fn test_get_fmt_time_str() {
assert '21:23:42' == time_to_test.get_fmt_time_str(.hhmmss24) assert '21:23:42' == main.time_to_test.get_fmt_time_str(.hhmmss24)
assert '21:23' == time_to_test.get_fmt_time_str(.hhmm24) assert '21:23' == main.time_to_test.get_fmt_time_str(.hhmm24)
assert '9:23:42 p.m.' == time_to_test.get_fmt_time_str(.hhmmss12) assert '9:23:42 p.m.' == main.time_to_test.get_fmt_time_str(.hhmmss12)
assert '9:23 p.m.' == time_to_test.get_fmt_time_str(.hhmm12) assert '9:23 p.m.' == main.time_to_test.get_fmt_time_str(.hhmm12)
} }
fn test_get_fmt_date_str() { fn test_get_fmt_date_str() {
assert '11.07.1980' == time_to_test.get_fmt_date_str(.dot, .ddmmyyyy) assert '11.07.1980' == main.time_to_test.get_fmt_date_str(.dot, .ddmmyyyy)
assert '11/07/1980' == time_to_test.get_fmt_date_str(.slash, .ddmmyyyy) assert '11/07/1980' == main.time_to_test.get_fmt_date_str(.slash, .ddmmyyyy)
assert '11-07-1980' == time_to_test.get_fmt_date_str(.hyphen, .ddmmyyyy) assert '11-07-1980' == main.time_to_test.get_fmt_date_str(.hyphen, .ddmmyyyy)
assert '11 07 1980' == time_to_test.get_fmt_date_str(.space, .ddmmyyyy) assert '11 07 1980' == main.time_to_test.get_fmt_date_str(.space, .ddmmyyyy)
assert '07.11.1980' == time_to_test.get_fmt_date_str(.dot, .mmddyyyy) assert '07.11.1980' == main.time_to_test.get_fmt_date_str(.dot, .mmddyyyy)
assert '07/11/1980' == time_to_test.get_fmt_date_str(.slash, .mmddyyyy) assert '07/11/1980' == main.time_to_test.get_fmt_date_str(.slash, .mmddyyyy)
assert '07-11-1980' == time_to_test.get_fmt_date_str(.hyphen, .mmddyyyy) assert '07-11-1980' == main.time_to_test.get_fmt_date_str(.hyphen, .mmddyyyy)
assert '07 11 1980' == time_to_test.get_fmt_date_str(.space, .mmddyyyy) assert '07 11 1980' == main.time_to_test.get_fmt_date_str(.space, .mmddyyyy)
assert '11.07.80' == time_to_test.get_fmt_date_str(.dot, .ddmmyy) assert '11.07.80' == main.time_to_test.get_fmt_date_str(.dot, .ddmmyy)
assert '11/07/80' == time_to_test.get_fmt_date_str(.slash, .ddmmyy) assert '11/07/80' == main.time_to_test.get_fmt_date_str(.slash, .ddmmyy)
assert '11-07-80' == time_to_test.get_fmt_date_str(.hyphen, .ddmmyy) assert '11-07-80' == main.time_to_test.get_fmt_date_str(.hyphen, .ddmmyy)
assert '11 07 80' == time_to_test.get_fmt_date_str(.space, .ddmmyy) assert '11 07 80' == main.time_to_test.get_fmt_date_str(.space, .ddmmyy)
assert '07.11.80' == time_to_test.get_fmt_date_str(.dot, .mmddyy) assert '07.11.80' == main.time_to_test.get_fmt_date_str(.dot, .mmddyy)
assert '07/11/80' == time_to_test.get_fmt_date_str(.slash, .mmddyy) assert '07/11/80' == main.time_to_test.get_fmt_date_str(.slash, .mmddyy)
assert '07-11-80' == time_to_test.get_fmt_date_str(.hyphen, .mmddyy) assert '07-11-80' == main.time_to_test.get_fmt_date_str(.hyphen, .mmddyy)
assert '07 11 80' == time_to_test.get_fmt_date_str(.space, .mmddyy) assert '07 11 80' == main.time_to_test.get_fmt_date_str(.space, .mmddyy)
assert 'Jul 11' == time_to_test.get_fmt_date_str(.space, .mmmd) assert 'Jul 11' == main.time_to_test.get_fmt_date_str(.space, .mmmd)
assert 'Jul 11' == time_to_test.get_fmt_date_str(.space, .mmmdd) assert 'Jul 11' == main.time_to_test.get_fmt_date_str(.space, .mmmdd)
assert 'Jul 11 1980' == time_to_test.get_fmt_date_str(.space, .mmmddyyyy) assert 'Jul 11 1980' == main.time_to_test.get_fmt_date_str(.space, .mmmddyyyy)
assert '1980-07-11' == time_to_test.get_fmt_date_str(.hyphen, .yyyymmdd) assert '1980-07-11' == main.time_to_test.get_fmt_date_str(.hyphen, .yyyymmdd)
} }
fn test_get_fmt_str() { fn test_get_fmt_str() {
// Since get_fmt_time_str and get_fmt_date_str do have comprehensive // Since get_fmt_time_str and get_fmt_date_str do have comprehensive
// tests I don't want to exaggerate here with all possible // tests I don't want to exaggerate here with all possible
// combinations. // combinations.
assert '11.07.1980 21:23:42' == time_to_test.get_fmt_str(.dot, .hhmmss24, .ddmmyyyy) assert '11.07.1980 21:23:42' == main.time_to_test.get_fmt_str(.dot, .hhmmss24, .ddmmyyyy)
} }
fn test_utc_string() { fn test_utc_string() {
assert 'Fri, 11 Jul 1980 21:23:42 UTC' == time_to_test.utc_string() assert 'Fri, 11 Jul 1980 21:23:42 UTC' == main.time_to_test.utc_string()
} }

View File

@ -83,17 +83,17 @@ fn test_unix() {
} }
fn test_format_ss() { fn test_format_ss() {
assert '11.07.1980 21:23:42' == time_to_test.get_fmt_str(.dot, .hhmmss24, .ddmmyyyy) assert '11.07.1980 21:23:42' == main.time_to_test.get_fmt_str(.dot, .hhmmss24, .ddmmyyyy)
} }
fn test_format_ss_milli() { fn test_format_ss_milli() {
assert '11.07.1980 21:23:42.123' == time_to_test.get_fmt_str(.dot, .hhmmss24_milli, .ddmmyyyy) assert '11.07.1980 21:23:42.123' == main.time_to_test.get_fmt_str(.dot, .hhmmss24_milli, .ddmmyyyy)
assert '1980-07-11 21:23:42.123' == time_to_test.format_ss_milli() assert '1980-07-11 21:23:42.123' == main.time_to_test.format_ss_milli()
} }
fn test_format_ss_micro() { fn test_format_ss_micro() {
assert '11.07.1980 21:23:42.123456' == time_to_test.get_fmt_str(.dot, .hhmmss24_micro, .ddmmyyyy) assert '11.07.1980 21:23:42.123456' == main.time_to_test.get_fmt_str(.dot, .hhmmss24_micro, .ddmmyyyy)
assert '1980-07-11 21:23:42.123456' == time_to_test.format_ss_micro() assert '1980-07-11 21:23:42.123456' == main.time_to_test.format_ss_micro()
} }
fn test_smonth() { fn test_smonth() {
@ -153,12 +153,12 @@ fn test_add() {
d_seconds := 3 d_seconds := 3
d_microseconds := 13 d_microseconds := 13
duration := time.Duration(d_seconds * time.second + d_microseconds * time.microsecond) duration := time.Duration(d_seconds * time.second + d_microseconds * time.microsecond)
t1 := time_to_test t1 := main.time_to_test
t2 := time_to_test.add(duration) t2 := main.time_to_test.add(duration)
assert t2.second == t1.second + d_seconds assert t2.second == t1.second + d_seconds
assert t2.microsecond == t1.microsecond + d_microseconds assert t2.microsecond == t1.microsecond + d_microseconds
assert t2.unix == t1.unix + u64(d_seconds) assert t2.unix == t1.unix + u64(d_seconds)
t3 := time_to_test.add(-duration) t3 := main.time_to_test.add(-duration)
assert t3.second == t1.second - d_seconds assert t3.second == t1.second - d_seconds
assert t3.microsecond == t1.microsecond - d_microseconds assert t3.microsecond == t1.microsecond - d_microseconds
assert t3.unix == t1.unix - u64(d_seconds) assert t3.unix == t1.unix - u64(d_seconds)
@ -166,13 +166,13 @@ fn test_add() {
fn test_add_days() { fn test_add_days() {
num_of_days := 3 num_of_days := 3
t := time_to_test.add_days(num_of_days) t := main.time_to_test.add_days(num_of_days)
assert t.day == time_to_test.day + num_of_days assert t.day == main.time_to_test.day + num_of_days
assert t.unix == time_to_test.unix + 86400 * u64(num_of_days) assert t.unix == main.time_to_test.unix + 86400 * u64(num_of_days)
} }
fn test_str() { fn test_str() {
assert '1980-07-11 21:23:42' == time_to_test.str() assert '1980-07-11 21:23:42' == main.time_to_test.str()
} }
// not optimal test but will find obvious bugs // not optimal test but will find obvious bugs

View File

@ -75,7 +75,7 @@ fn init_win_time_start() u64 {
pub fn sys_mono_now() u64 { pub fn sys_mono_now() u64 {
tm := u64(0) tm := u64(0)
C.QueryPerformanceCounter(&tm) // XP or later never fail C.QueryPerformanceCounter(&tm) // XP or later never fail
return (tm - start_time) * 1000000000 / freq_time return (tm - time.start_time) * 1000000000 / time.freq_time
} }
// NB: vpc_now is used by `v -profile` . // NB: vpc_now is used by `v -profile` .

View File

@ -97,7 +97,7 @@ fn (mut v Builder) post_process_c_compiler_output(res os.Result) {
} }
return return
} }
for emsg_marker in [c_verror_message_marker, 'error: include file '] { for emsg_marker in [builder.c_verror_message_marker, 'error: include file '] {
if res.output.contains(emsg_marker) { if res.output.contains(emsg_marker) {
emessage := res.output.all_after(emsg_marker).all_before('\n').all_before('\r').trim_right('\r\n') emessage := res.output.all_after(emsg_marker).all_before('\n').all_before('\r').trim_right('\r\n')
verror(emessage) verror(emessage)
@ -121,7 +121,7 @@ fn (mut v Builder) post_process_c_compiler_output(res os.Result) {
println('(Use `v -cg` to print the entire error message)\n') println('(Use `v -cg` to print the entire error message)\n')
} }
} }
verror(c_error_info) verror(builder.c_error_info)
} }
fn (mut v Builder) rebuild_cached_module(vexe string, imp_path string) string { fn (mut v Builder) rebuild_cached_module(vexe string, imp_path string) string {
@ -858,7 +858,7 @@ fn (mut c Builder) cc_windows_cross() {
println(os.user_os()) println(os.user_os())
panic('your platform is not supported yet') panic('your platform is not supported yet')
} }
mut cmd := '$mingw_cc $optimization_options $debug_options -std=gnu11 $args -municode' mut cmd := '$builder.mingw_cc $optimization_options $debug_options -std=gnu11 $args -municode'
// cmd := 'clang -o $obj_name -w $include -m32 -c -target x86_64-win32 ${pref.default_module_path}/$c.out_name_c' // cmd := 'clang -o $obj_name -w $include -m32 -c -target x86_64-win32 ${pref.default_module_path}/$c.out_name_c'
if c.pref.is_verbose || c.pref.show_cc { if c.pref.is_verbose || c.pref.show_cc {
println(cmd) println(cmd)

View File

@ -81,7 +81,7 @@ fn find_windows_kit_root(host_arch string) ?WindowsKit {
$if windows { $if windows {
root_key := RegKey(0) root_key := RegKey(0)
path := 'SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots' path := 'SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots'
rc := C.RegOpenKeyEx(hkey_local_machine, path.to_wide(), 0, key_query_value | key_wow64_32key | key_enumerate_sub_keys, rc := C.RegOpenKeyEx(builder.hkey_local_machine, path.to_wide(), 0, builder.key_query_value | builder.key_wow64_32key | builder.key_enumerate_sub_keys,
&root_key) &root_key)
// TODO: Fix defer inside ifs // TODO: Fix defer inside ifs
// defer { // defer {

View File

@ -1284,7 +1284,7 @@ pub fn (mut c Checker) call_method(mut call_expr ast.CallExpr) table.Type {
} }
// TODO: remove this for actual methods, use only for compiler magic // TODO: remove this for actual methods, use only for compiler magic
// FIXME: Argument count != 1 will break these // FIXME: Argument count != 1 will break these
if left_type_sym.kind == .array && method_name in array_builtin_methods { if left_type_sym.kind == .array && method_name in checker.array_builtin_methods {
mut elem_typ := table.void_type mut elem_typ := table.void_type
is_filter_map := method_name in ['filter', 'map'] is_filter_map := method_name in ['filter', 'map']
is_sort := method_name == 'sort' is_sort := method_name == 'sort'
@ -2309,7 +2309,7 @@ pub fn (mut c Checker) enum_decl(decl ast.EnumDecl) {
match field.expr { match field.expr {
ast.IntegerLiteral { ast.IntegerLiteral {
val := field.expr.val.i64() val := field.expr.val.i64()
if val < int_min || val > int_max { if val < checker.int_min || val > checker.int_max {
c.error('enum value `$val` overflows int', field.expr.pos) c.error('enum value `$val` overflows int', field.expr.pos)
} else if !decl.is_multi_allowed && i64(val) in seen { } else if !decl.is_multi_allowed && i64(val) in seen {
c.error('enum value `$val` already exists', field.expr.pos) c.error('enum value `$val` already exists', field.expr.pos)
@ -2333,7 +2333,7 @@ pub fn (mut c Checker) enum_decl(decl ast.EnumDecl) {
} else { } else {
if seen.len > 0 { if seen.len > 0 {
last := seen[seen.len - 1] last := seen[seen.len - 1]
if last == int_max { if last == checker.int_max {
c.error('enum value overflows', field.pos) c.error('enum value overflows', field.pos)
} }
seen << last + 1 seen << last + 1
@ -2406,7 +2406,7 @@ pub fn (mut c Checker) assign_stmt(mut assign_stmt ast.AssignStmt) {
mut is_large := right.val.len > 13 mut is_large := right.val.len > 13
if !is_large && right.val.len > 8 { if !is_large && right.val.len > 8 {
val := right.val.i64() val := right.val.i64()
is_large = val > int_max || val < int_min is_large = val > checker.int_max || val < checker.int_min
} }
if is_large { if is_large {
c.error('overflow in implicit type `int`, use explicit type casting instead', c.error('overflow in implicit type `int`, use explicit type casting instead',
@ -4136,11 +4136,11 @@ fn (mut c Checker) match_exprs(mut node ast.MatchExpr, cond_type_sym table.TypeS
mut err_details := 'match must be exhaustive' mut err_details := 'match must be exhaustive'
if unhandled.len > 0 { if unhandled.len > 0 {
err_details += ' (add match branches for: ' err_details += ' (add match branches for: '
if unhandled.len < match_exhaustive_cutoff_limit { if unhandled.len < checker.match_exhaustive_cutoff_limit {
err_details += unhandled.join(', ') err_details += unhandled.join(', ')
} else { } else {
remaining := unhandled.len - match_exhaustive_cutoff_limit remaining := unhandled.len - checker.match_exhaustive_cutoff_limit
err_details += unhandled[0..match_exhaustive_cutoff_limit].join(', ') err_details += unhandled[0..checker.match_exhaustive_cutoff_limit].join(', ')
err_details += ', and $remaining others ...' err_details += ', and $remaining others ...'
} }
err_details += ' or `else {}` at the end)' err_details += ' or `else {}` at the end)'
@ -4637,13 +4637,13 @@ fn (mut c Checker) comp_if_branch(cond ast.Expr, pos token.Position) bool {
} }
} }
ast.Ident { ast.Ident {
if cond.name in valid_comp_if_os { if cond.name in checker.valid_comp_if_os {
return cond.name != c.pref.os.str().to_lower() // TODO hack return cond.name != c.pref.os.str().to_lower() // TODO hack
} else if cond.name in valid_comp_if_compilers { } else if cond.name in checker.valid_comp_if_compilers {
return pref.cc_from_string(cond.name) != c.pref.ccompiler_type return pref.cc_from_string(cond.name) != c.pref.ccompiler_type
} else if cond.name in valid_comp_if_platforms { } else if cond.name in checker.valid_comp_if_platforms {
return false // TODO return false // TODO
} else if cond.name in valid_comp_if_other { } else if cond.name in checker.valid_comp_if_other {
// TODO: This should probably be moved // TODO: This should probably be moved
match cond.name { match cond.name {
'js' { return c.pref.backend != .js } 'js' { return c.pref.backend != .js }

View File

@ -14,10 +14,10 @@ pub mut:
// is_example returns true if the contents of this comment is a doc example. // is_example returns true if the contents of this comment is a doc example.
// The current convention is '// Example: <content>' // The current convention is '// Example: <content>'
pub fn (dc DocComment) is_example() bool { pub fn (dc DocComment) is_example() bool {
return dc.text.starts_with(example_pattern) return dc.text.starts_with(doc.example_pattern)
} }
// example returns the content of the example body // example returns the content of the example body
pub fn (dc DocComment) example() string { pub fn (dc DocComment) example() string {
return dc.text.all_after(example_pattern) return dc.text.all_after(doc.example_pattern)
} }

View File

@ -21,7 +21,7 @@ fn test_fmt() {
vexe := os.getenv('VEXE') vexe := os.getenv('VEXE')
if vexe.len == 0 || !os.exists(vexe) { if vexe.len == 0 || !os.exists(vexe) {
eprintln('VEXE must be set') eprintln('VEXE must be set')
exit(error_missing_vexe) exit(main.error_missing_vexe)
} }
vroot := os.dir(vexe) vroot := os.dir(vexe)
os.chdir(vroot) os.chdir(vroot)
@ -59,7 +59,7 @@ fn test_fmt() {
if expected_ocontent != result_ocontent { if expected_ocontent != result_ocontent {
fmt_bench.fail() fmt_bench.fail()
eprintln(fmt_bench.step_message_fail('file $vrelpath after formatting, does not look as expected.')) eprintln(fmt_bench.step_message_fail('file $vrelpath after formatting, does not look as expected.'))
if ipath.ends_with(b2v_keep_path) { if ipath.ends_with(main.b2v_keep_path) {
continue continue
} }
if diff_cmd == '' { if diff_cmd == '' {
@ -79,19 +79,19 @@ fn test_fmt() {
eprintln(term.h_divider('-')) eprintln(term.h_divider('-'))
eprintln(fmt_bench.total_message(fmt_message)) eprintln(fmt_bench.total_message(fmt_message))
if fmt_bench.nfail > 0 { if fmt_bench.nfail > 0 {
exit(error_failed_tests) exit(main.error_failed_tests)
} }
} }
fn fill_bin2v_keep() ? { fn fill_bin2v_keep() ? {
img0 := os.join_path('tutorials', 'img', 'hello.png') img0 := os.join_path('tutorials', 'img', 'hello.png')
img1 := os.join_path('tutorials', 'img', 'time.png') img1 := os.join_path('tutorials', 'img', 'time.png')
os.rm(b2v_keep_path) ? os.rm(main.b2v_keep_path) ?
os.exec('v bin2v -w $b2v_keep_path $img0 $img1') ? os.exec('v bin2v -w $main.b2v_keep_path $img0 $img1') ?
} }
fn restore_bin2v_placeholder() ? { fn restore_bin2v_placeholder() ? {
text := '// This is a placeholder file which will be filled with bin2v output before the test. 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' // HINT: do NOT delete, move or rename this file!\n'
os.write_file(b2v_keep_path, text) ? os.write_file(main.b2v_keep_path, text) ?
} }

View File

@ -19,7 +19,7 @@ fn test_fmt() {
vexe := os.getenv('VEXE') vexe := os.getenv('VEXE')
if vexe.len == 0 || !os.exists(vexe) { if vexe.len == 0 || !os.exists(vexe) {
eprintln('VEXE must be set') eprintln('VEXE must be set')
exit(error_missing_vexe) exit(main.error_missing_vexe)
} }
vroot := os.dir(vexe) vroot := os.dir(vexe)
tmpfolder := os.temp_dir() tmpfolder := os.temp_dir()
@ -69,6 +69,6 @@ fn test_fmt() {
eprintln(term.h_divider('-')) eprintln(term.h_divider('-'))
eprintln(fmt_bench.total_message(fmt_message)) eprintln(fmt_bench.total_message(fmt_message))
if fmt_bench.nfail > 0 { if fmt_bench.nfail > 0 {
exit(error_failed_tests) exit(main.error_failed_tests)
} }
} }

View File

@ -22,7 +22,7 @@ fn test_vlib_fmt() {
vexe := os.getenv('VEXE') vexe := os.getenv('VEXE')
if vexe.len == 0 || !os.exists(vexe) { if vexe.len == 0 || !os.exists(vexe) {
eprintln('VEXE must be set') eprintln('VEXE must be set')
exit(error_missing_vexe) exit(main.error_missing_vexe)
} }
vroot := os.dir(vexe) vroot := os.dir(vexe)
tmpfolder := os.temp_dir() tmpfolder := os.temp_dir()
@ -67,6 +67,6 @@ fn test_vlib_fmt() {
eprintln(term.h_divider('-')) eprintln(term.h_divider('-'))
eprintln(fmt_bench.total_message(fmt_message)) eprintln(fmt_bench.total_message(fmt_message))
if fmt_bench.nfail > 0 { if fmt_bench.nfail > 0 {
exit(error_failed_tests) exit(main.error_failed_tests)
} }
} }

View File

@ -16,7 +16,7 @@ fn test_c_files() {
println('Running V => C tests') println('Running V => C tests')
vexe := os.getenv('VEXE') vexe := os.getenv('VEXE')
vroot := os.dir(vexe) vroot := os.dir(vexe)
for i in 1 .. (nr_tests + 1) { for i in 1 .. (main.nr_tests + 1) {
path := '$vroot/vlib/v/gen/tests/${i}.vv' path := '$vroot/vlib/v/gen/tests/${i}.vv'
ctext := os.read_file('$vroot/vlib/v/gen/tests/${i}.c') or { panic(err) } ctext := os.read_file('$vroot/vlib/v/gen/tests/${i}.c') or { panic(err) }
mut b := builder.new_builder(pref.Preferences{}) mut b := builder.new_builder(pref.Preferences{})
@ -28,7 +28,7 @@ fn test_c_files() {
res = res[..pos] + res[end + 15..] res = res[..pos] + res[end + 15..]
} }
if compare_texts(res, ctext, path) { if compare_texts(res, ctext, path) {
println('$term_ok $i') println('$main.term_ok $i')
} else { } else {
assert false assert false
} }
@ -57,7 +57,7 @@ fn compare_texts(a string, b string, path string) bool {
line_b := lines_b[i] line_b := lines_b[i]
if line_a.trim_space() != line_b.trim_space() { if line_a.trim_space() != line_b.trim_space() {
println('$path: Got\n$a') println('$path: Got\n$a')
println('$path:$i: $term_fail') println('$path:$i: $main.term_fail')
println(term.bold(term.bright_yellow('actual : ')) + line_a) println(term.bold(term.bright_yellow('actual : ')) + line_a)
println(term.green('expected: ') + line_b) println(term.green('expected: ') + line_b)
println(lines_b[i + 1]) println(lines_b[i + 1])

View File

@ -42,12 +42,12 @@ fn (mut g Gen) generate_hotcode_reloader_code() {
for so_fn in g.hotcode_fn_names { for so_fn in g.hotcode_fn_names {
load_code << 'impl_live_$so_fn = dlsym(live_lib, "impl_live_$so_fn");' load_code << 'impl_live_$so_fn = dlsym(live_lib, "impl_live_$so_fn");'
} }
phd = posix_hotcode_definitions_1 phd = gen.posix_hotcode_definitions_1
} else { } else {
for so_fn in g.hotcode_fn_names { for so_fn in g.hotcode_fn_names {
load_code << 'impl_live_$so_fn = (void *)GetProcAddress(live_lib, "impl_live_$so_fn"); ' load_code << 'impl_live_$so_fn = (void *)GetProcAddress(live_lib, "impl_live_$so_fn"); '
} }
phd = windows_hotcode_definitions_1 phd = gen.windows_hotcode_definitions_1
} }
g.hotcode_definitions.writeln(phd.replace('@LOAD_FNS@', load_code.join('\n'))) g.hotcode_definitions.writeln(phd.replace('@LOAD_FNS@', load_code.join('\n')))
} }

View File

@ -22,10 +22,10 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) {
g.writeln('\n\t// sql insert') g.writeln('\n\t// sql insert')
db_name := g.new_tmp_var() db_name := g.new_tmp_var()
g.sql_stmt_name = g.new_tmp_var() g.sql_stmt_name = g.new_tmp_var()
g.write('${dbtype}__DB $db_name = ') g.write('${gen.dbtype}__DB $db_name = ')
g.expr(node.db_expr) g.expr(node.db_expr)
g.writeln(';') g.writeln(';')
g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt($db_name, _SLIT("') g.write('sqlite3_stmt* $g.sql_stmt_name = ${gen.dbtype}__DB_init_stmt($db_name, _SLIT("')
table_name := util.strip_mod_name(g.table.get_type_symbol(node.table_expr.typ).name) table_name := util.strip_mod_name(g.table.get_type_symbol(node.table_expr.typ).name)
if node.kind == .insert { if node.kind == .insert {
g.write('INSERT INTO `$table_name` (') g.write('INSERT INTO `$table_name` (')
@ -131,11 +131,11 @@ fn (mut g Gen) sql_select_expr(node ast.SqlExpr) {
db_name := g.new_tmp_var() db_name := g.new_tmp_var()
g.writeln('\n\t// sql select') g.writeln('\n\t// sql select')
// g.write('${dbtype}__DB $db_name = *(${dbtype}__DB*)${node.db_var_name}.data;') // g.write('${dbtype}__DB $db_name = *(${dbtype}__DB*)${node.db_var_name}.data;')
g.write('${dbtype}__DB $db_name = ') // $node.db_var_name;') g.write('${gen.dbtype}__DB $db_name = ') // $node.db_var_name;')
g.expr(node.db_expr) g.expr(node.db_expr)
g.writeln(';') g.writeln(';')
// g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt(*(${dbtype}__DB*)${node.db_var_name}.data, _SLIT("$sql_query') // g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt(*(${dbtype}__DB*)${node.db_var_name}.data, _SLIT("$sql_query')
g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt($db_name, _SLIT("') g.write('sqlite3_stmt* $g.sql_stmt_name = ${gen.dbtype}__DB_init_stmt($db_name, _SLIT("')
g.write(sql_query) g.write(sql_query)
if node.has_where && node.where_expr is ast.InfixExpr { if node.has_where && node.where_expr is ast.InfixExpr {
g.expr_to_sql(node.where_expr) g.expr_to_sql(node.where_expr)
@ -170,7 +170,7 @@ fn (mut g Gen) sql_select_expr(node ast.SqlExpr) {
g.writeln('if ($binding_res != SQLITE_OK) { puts(sqlite3_errmsg(${db_name}.conn)); }') g.writeln('if ($binding_res != SQLITE_OK) { puts(sqlite3_errmsg(${db_name}.conn)); }')
// //
if node.is_count { if node.is_count {
g.writeln('$cur_line ${dbtype}__get_int_from_stmt($g.sql_stmt_name);') g.writeln('$cur_line ${gen.dbtype}__get_int_from_stmt($g.sql_stmt_name);')
} else { } else {
// `user := sql db { select from User where id = 1 }` // `user := sql db { select from User where id = 1 }`
tmp := g.new_tmp_var() tmp := g.new_tmp_var()

View File

@ -34,18 +34,18 @@ const (
) )
pub fn (mut g Gen) generate_elf_header() { pub fn (mut g Gen) generate_elf_header() {
g.buf << [byte(mag0), mag1, mag2, mag3] g.buf << [byte(x64.mag0), x64.mag1, x64.mag2, x64.mag3]
g.buf << elfclass64 // file class g.buf << x64.elfclass64 // file class
g.buf << elfdata2lsb // data encoding g.buf << x64.elfdata2lsb // data encoding
g.buf << ev_current // file version g.buf << x64.ev_current // file version
g.buf << 1 // elf_osabi g.buf << 1 // elf_osabi
g.write64(0) // et_rel) // et_rel for .o g.write64(0) // et_rel) // et_rel for .o
g.write16(2) // e_type g.write16(2) // e_type
g.write16(e_machine) // g.write16(x64.e_machine) //
g.write32(ev_current) // e_version g.write32(x64.ev_current) // e_version
eh_size := 0x40 eh_size := 0x40
phent_size := 0x38 phent_size := 0x38
g.write64(segment_start + eh_size + phent_size) // e_entry g.write64(x64.segment_start + eh_size + phent_size) // e_entry
g.write64(0x40) // e_phoff g.write64(0x40) // e_phoff
g.write64(0) // e_shoff g.write64(0) // e_shoff
g.write32(0) // e_flags g.write32(0) // e_flags
@ -59,8 +59,8 @@ pub fn (mut g Gen) generate_elf_header() {
g.write32(1) // p_type g.write32(1) // p_type
g.write32(5) // p_flags g.write32(5) // p_flags
g.write64(0) // p_offset g.write64(0) // p_offset
g.write64(segment_start) // p_vaddr addr:050 g.write64(x64.segment_start) // p_vaddr addr:050
g.write64(segment_start) // g.write64(x64.segment_start) //
g.file_size_pos = i64(g.buf.len) g.file_size_pos = i64(g.buf.len)
g.write64(0) // p_filesz PLACEHOLDER, set to file_size later // addr: 060 g.write64(0) // p_filesz PLACEHOLDER, set to file_size later // addr: 060
g.write64(0) // p_memsz g.write64(0) // p_memsz
@ -70,7 +70,7 @@ pub fn (mut g Gen) generate_elf_header() {
println('code_start_pos = $g.buf.len.hex()') println('code_start_pos = $g.buf.len.hex()')
g.code_start_pos = i64(g.buf.len) g.code_start_pos = i64(g.buf.len)
g.debug_pos = g.buf.len g.debug_pos = g.buf.len
g.call(placeholder) // call main function, it's not guaranteed to be the first, we don't know its address yet g.call(x64.placeholder) // call main function, it's not guaranteed to be the first, we don't know its address yet
g.println('call fn main') g.println('call fn main')
} }
@ -84,7 +84,7 @@ pub fn (mut g Gen) generate_elf_footer() {
// Strings table // Strings table
// Loop thru all strings and set the right addresses // Loop thru all strings and set the right addresses
for i, s in g.strings { for i, s in g.strings {
g.write64_at(segment_start + g.buf.len, int(g.str_pos[i])) g.write64_at(x64.segment_start + g.buf.len, int(g.str_pos[i]))
g.write_string(s) g.write_string(s)
g.write8(0) g.write8(0)
} }

View File

@ -610,16 +610,16 @@ pub fn (mut g Gen) call_fn(node ast.CallExpr) {
match expr { match expr {
ast.IntegerLiteral { ast.IntegerLiteral {
// `foo(2)` => `mov edi,0x2` // `foo(2)` => `mov edi,0x2`
g.mov(fn_arg_registers[i], expr.val.int()) g.mov(x64.fn_arg_registers[i], expr.val.int())
} }
ast.Ident { ast.Ident {
// `foo(x)` => `mov edi,DWORD PTR [rbp-0x8]` // `foo(x)` => `mov edi,DWORD PTR [rbp-0x8]`
var_offset := g.get_var_offset(expr.name) var_offset := g.get_var_offset(expr.name)
if g.pref.is_verbose { if g.pref.is_verbose {
println('i=$i fn name= $name offset=$var_offset') println('i=$i fn name= $name offset=$var_offset')
println(int(fn_arg_registers[i])) println(int(x64.fn_arg_registers[i]))
} }
g.mov_var_to_reg(fn_arg_registers[i], var_offset) g.mov_var_to_reg(x64.fn_arg_registers[i], var_offset)
} }
else { else {
verror('unhandled call_fn (name=$name) node: ' + expr.type_name()) verror('unhandled call_fn (name=$name) node: ' + expr.type_name())
@ -877,7 +877,7 @@ fn (mut g Gen) fn_decl(node ast.FnDecl) {
g.allocate_var(name, 4, 0) g.allocate_var(name, 4, 0)
// `mov DWORD PTR [rbp-0x4],edi` // `mov DWORD PTR [rbp-0x4],edi`
offset += 4 offset += 4
g.mov_reg_to_rbp(offset, fn_arg_registers[i]) g.mov_reg_to_rbp(offset, x64.fn_arg_registers[i])
} }
// //
g.stmts(node.stmts) g.stmts(node.stmts)

View File

@ -54,7 +54,7 @@ fn (mut p Parser) comp_call() ast.ComptimeCall {
p.check(.dot) p.check(.dot)
} }
n := p.check_name() // (.name) n := p.check_name() // (.name)
if n !in supported_comptime_calls { if n !in parser.supported_comptime_calls {
p.error(error_msg) p.error(error_msg)
return ast.ComptimeCall{} return ast.ComptimeCall{}
} }

View File

@ -2048,7 +2048,7 @@ const (
fn (mut p Parser) global_decl() ast.GlobalDecl { fn (mut p Parser) global_decl() ast.GlobalDecl {
if !p.pref.translated && !p.pref.is_livemain && !p.builtin_mod && !p.pref.building_v if !p.pref.translated && !p.pref.is_livemain && !p.builtin_mod && !p.pref.building_v
&& p.mod != 'ui' && p.mod != 'gg2' && p.mod != 'uiold' && !p.pref.enable_globals && p.mod != 'ui' && p.mod != 'gg2' && p.mod != 'uiold' && !p.pref.enable_globals
&& !p.pref.is_fmt&& p.mod !in global_enabled_mods { && !p.pref.is_fmt&& p.mod !in parser.global_enabled_mods {
p.error('use `v --enable-globals ...` to enable globals') p.error('use `v --enable-globals ...` to enable globals')
return ast.GlobalDecl{} return ast.GlobalDecl{}
} }

View File

@ -178,9 +178,9 @@ fn test_parse_expr() {
fn test_num_literals() { fn test_num_literals() {
inputs := [ inputs := [
'a := -1', 'a := -1',
'b := -12.e17' 'b := -12.e17',
'c := -12.' 'c := -12.',
'd := -a' 'd := -a',
] ]
table := table.new_table() table := table.new_table()
mut scope := &ast.Scope{ mut scope := &ast.Scope{
@ -189,21 +189,13 @@ fn test_num_literals() {
} }
mut rhs_types := []string{} mut rhs_types := []string{}
for input in inputs { for input in inputs {
stmt := parser.parse_stmt(input, table, scope) stmt := parse_stmt(input, table, scope)
r := (stmt as ast.AssignStmt).right r := (stmt as ast.AssignStmt).right
match r[0] { match r[0] {
ast.IntegerLiteral { ast.IntegerLiteral { rhs_types << 'int literal' }
rhs_types << 'int literal' ast.FloatLiteral { rhs_types << 'float literal' }
} ast.PrefixExpr { rhs_types << 'prefix expression' }
ast.FloatLiteral { else { rhs_types << 'something else' }
rhs_types << 'float literal'
}
ast.PrefixExpr {
rhs_types << 'prefix expression'
}
else {
rhs_types << 'something else'
}
} }
} }
mut rhs_type := rhs_types[0] mut rhs_type := rhs_types[0]
@ -216,7 +208,6 @@ fn test_num_literals() {
assert rhs_type == 'prefix expression' assert rhs_type == 'prefix expression'
} }
/* /*
table := &table.Table{} table := &table.Table{}
for s in text_expr { for s in text_expr {

View File

@ -393,7 +393,7 @@ pub fn parse_args(args []string) (&Preferences, string) {
exit(1) exit(1)
} }
if arg[0] == `-` { if arg[0] == `-` {
if arg[1..] in list_of_flags_with_param { if arg[1..] in pref.list_of_flags_with_param {
// skip parameter // skip parameter
i++ i++
continue continue

View File

@ -196,7 +196,7 @@ fn (s Scanner) num_lit(start int, end int) string {
mut b := malloc(end - start + 1) // add a byte for the endstring 0 mut b := malloc(end - start + 1) // add a byte for the endstring 0
mut i1 := 0 mut i1 := 0
for i := start; i < end; i++ { for i := start; i < end; i++ {
if txt[i] != num_sep { if txt[i] != scanner.num_sep {
b[i1] = txt[i] b[i1] = txt[i]
i1++ i1++
} }
@ -212,15 +212,15 @@ fn (mut s Scanner) ident_bin_number() string {
mut first_wrong_digit := `\0` mut first_wrong_digit := `\0`
start_pos := s.pos start_pos := s.pos
s.pos += 2 // skip '0b' s.pos += 2 // skip '0b'
if s.pos < s.text.len && s.text[s.pos] == num_sep { if s.pos < s.text.len && s.text[s.pos] == scanner.num_sep {
s.error('separator `_` is only valid between digits in a numeric literal') s.error('separator `_` is only valid between digits in a numeric literal')
} }
for s.pos < s.text.len { for s.pos < s.text.len {
c := s.text[s.pos] c := s.text[s.pos]
if c == num_sep && s.text[s.pos - 1] == num_sep { if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively') s.error('cannot use `_` consecutively')
} }
if !c.is_bin_digit() && c != num_sep { if !c.is_bin_digit() && c != scanner.num_sep {
if (!c.is_digit() && !c.is_letter()) || s.is_inside_string { if (!c.is_digit() && !c.is_letter()) || s.is_inside_string {
break break
} else if !has_wrong_digit { } else if !has_wrong_digit {
@ -231,7 +231,7 @@ fn (mut s Scanner) ident_bin_number() string {
} }
s.pos++ s.pos++
} }
if s.text[s.pos - 1] == num_sep { if s.text[s.pos - 1] == scanner.num_sep {
s.pos-- s.pos--
s.error('cannot use `_` at the end of a numeric literal') s.error('cannot use `_` at the end of a numeric literal')
} else if start_pos + 2 == s.pos { } else if start_pos + 2 == s.pos {
@ -255,15 +255,15 @@ fn (mut s Scanner) ident_hex_number() string {
return '0x' return '0x'
} }
s.pos += 2 // skip '0x' s.pos += 2 // skip '0x'
if s.pos < s.text.len && s.text[s.pos] == num_sep { if s.pos < s.text.len && s.text[s.pos] == scanner.num_sep {
s.error('separator `_` is only valid between digits in a numeric literal') s.error('separator `_` is only valid between digits in a numeric literal')
} }
for s.pos < s.text.len { for s.pos < s.text.len {
c := s.text[s.pos] c := s.text[s.pos]
if c == num_sep && s.text[s.pos - 1] == num_sep { if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively') s.error('cannot use `_` consecutively')
} }
if !c.is_hex_digit() && c != num_sep { if !c.is_hex_digit() && c != scanner.num_sep {
if !c.is_letter() || s.is_inside_string { if !c.is_letter() || s.is_inside_string {
break break
} else if !has_wrong_digit { } else if !has_wrong_digit {
@ -274,7 +274,7 @@ fn (mut s Scanner) ident_hex_number() string {
} }
s.pos++ s.pos++
} }
if s.text[s.pos - 1] == num_sep { if s.text[s.pos - 1] == scanner.num_sep {
s.pos-- s.pos--
s.error('cannot use `_` at the end of a numeric literal') s.error('cannot use `_` at the end of a numeric literal')
} else if start_pos + 2 == s.pos { } else if start_pos + 2 == s.pos {
@ -295,15 +295,15 @@ fn (mut s Scanner) ident_oct_number() string {
mut first_wrong_digit := `\0` mut first_wrong_digit := `\0`
start_pos := s.pos start_pos := s.pos
s.pos += 2 // skip '0o' s.pos += 2 // skip '0o'
if s.pos < s.text.len && s.text[s.pos] == num_sep { if s.pos < s.text.len && s.text[s.pos] == scanner.num_sep {
s.error('separator `_` is only valid between digits in a numeric literal') s.error('separator `_` is only valid between digits in a numeric literal')
} }
for s.pos < s.text.len { for s.pos < s.text.len {
c := s.text[s.pos] c := s.text[s.pos]
if c == num_sep && s.text[s.pos - 1] == num_sep { if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively') s.error('cannot use `_` consecutively')
} }
if !c.is_oct_digit() && c != num_sep { if !c.is_oct_digit() && c != scanner.num_sep {
if (!c.is_digit() && !c.is_letter()) || s.is_inside_string { if (!c.is_digit() && !c.is_letter()) || s.is_inside_string {
break break
} else if !has_wrong_digit { } else if !has_wrong_digit {
@ -314,7 +314,7 @@ fn (mut s Scanner) ident_oct_number() string {
} }
s.pos++ s.pos++
} }
if s.text[s.pos - 1] == num_sep { if s.text[s.pos - 1] == scanner.num_sep {
s.pos-- s.pos--
s.error('cannot use `_` at the end of a numeric literal') s.error('cannot use `_` at the end of a numeric literal')
} else if start_pos + 2 == s.pos { } else if start_pos + 2 == s.pos {
@ -337,10 +337,10 @@ fn (mut s Scanner) ident_dec_number() string {
// scan integer part // scan integer part
for s.pos < s.text.len { for s.pos < s.text.len {
c := s.text[s.pos] c := s.text[s.pos]
if c == num_sep && s.text[s.pos - 1] == num_sep { if c == scanner.num_sep && s.text[s.pos - 1] == scanner.num_sep {
s.error('cannot use `_` consecutively') s.error('cannot use `_` consecutively')
} }
if !c.is_digit() && c != num_sep { if !c.is_digit() && c != scanner.num_sep {
if !c.is_letter() || c in [`e`, `E`] || s.is_inside_string { if !c.is_letter() || c in [`e`, `E`] || s.is_inside_string {
break break
} else if !has_wrong_digit { } else if !has_wrong_digit {
@ -351,7 +351,7 @@ fn (mut s Scanner) ident_dec_number() string {
} }
s.pos++ s.pos++
} }
if s.text[s.pos - 1] == num_sep { if s.text[s.pos - 1] == scanner.num_sep {
s.pos-- s.pos--
s.error('cannot use `_` at the end of a numeric literal') s.error('cannot use `_` at the end of a numeric literal')
} }
@ -698,7 +698,7 @@ fn (mut s Scanner) text_scan() token.Token {
`?` { `?` {
return s.new_token(.question, '', 1) return s.new_token(.question, '', 1)
} }
single_quote, double_quote { scanner.single_quote, scanner.double_quote {
ident_string := s.ident_string() ident_string := s.ident_string()
return s.new_token(.string, ident_string, ident_string.len + 2) // + two quotes return s.new_token(.string, ident_string, ident_string.len + 2) // + two quotes
} }
@ -1021,7 +1021,7 @@ fn (s &Scanner) count_symbol_before(p int, sym byte) int {
fn (mut s Scanner) ident_string() string { fn (mut s Scanner) ident_string() string {
q := s.text[s.pos] q := s.text[s.pos]
is_quote := q == single_quote || q == double_quote is_quote := q == scanner.single_quote || q == scanner.double_quote
is_raw := is_quote && s.pos > 0 && s.text[s.pos - 1] == `r` is_raw := is_quote && s.pos > 0 && s.text[s.pos - 1] == `r`
is_cstr := is_quote && s.pos > 0 && s.text[s.pos - 1] == `c` is_cstr := is_quote && s.pos > 0 && s.text[s.pos - 1] == `c`
if is_quote { if is_quote {

View File

@ -6,8 +6,8 @@ module table
import v.cflag import v.cflag
// check if cflag is in table // check if cflag is in table
fn (table &Table) has_cflag(flag cflag.CFlag) bool { fn (mytable &Table) has_cflag(flag cflag.CFlag) bool {
for cf in table.cflags { for cf in mytable.cflags {
if cf.os == flag.os && cf.name == flag.name && cf.value == flag.value { if cf.os == flag.os && cf.name == flag.name && cf.value == flag.value {
return true return true
} }
@ -17,7 +17,7 @@ fn (table &Table) has_cflag(flag cflag.CFlag) bool {
// parse the flags to (table.cflags) []CFlag // parse the flags to (table.cflags) []CFlag
// Note: clean up big time (joe-c) // Note: clean up big time (joe-c)
pub fn (mut table Table) parse_cflag(cflg string, mod string, ctimedefines []string) ?bool { pub fn (mut mytable Table) parse_cflag(cflg string, mod string, ctimedefines []string) ?bool {
allowed_flags := ['framework', 'library', 'Wa', 'Wl', 'Wp', 'I', 'l', 'L'] allowed_flags := ['framework', 'library', 'Wa', 'Wl', 'Wp', 'I', 'l', 'L']
flag_orig := cflg.trim_space() flag_orig := cflg.trim_space()
mut flag := flag_orig mut flag := flag_orig
@ -78,8 +78,8 @@ pub fn (mut table Table) parse_cflag(cflg string, mod string, ctimedefines []str
name: name name: name
value: value value: value
} }
if !table.has_cflag(cf) { if !mytable.has_cflag(cf) {
table.cflags << cf mytable.cflags << cf
} }
if index == -1 { if index == -1 {
break break

View File

@ -14,12 +14,12 @@ fn test_parse_valid_cflags() {
expected_flags := [ expected_flags := [
make_flag('freebsd', '-I', '/usr/local/include/freetype2'), make_flag('freebsd', '-I', '/usr/local/include/freetype2'),
make_flag('linux', '-l', 'glfw'), make_flag('linux', '-l', 'glfw'),
make_flag('mingw', no_name, '-mwindows'), make_flag('mingw', main.no_name, '-mwindows'),
make_flag('solaris', '-L', '/opt/local/lib'), make_flag('solaris', '-L', '/opt/local/lib'),
make_flag('darwin', '-framework', 'Cocoa'), make_flag('darwin', '-framework', 'Cocoa'),
make_flag('windows', '-l', 'gdi32'), make_flag('windows', '-l', 'gdi32'),
make_flag(no_os, '-l', 'mysqlclient'), make_flag(main.no_os, '-l', 'mysqlclient'),
make_flag(no_os, no_name, '-test'), make_flag(main.no_os, main.no_name, '-test'),
] ]
parse_valid_flag(mut t, '-lmysqlclient') parse_valid_flag(mut t, '-lmysqlclient')
parse_valid_flag(mut t, '-test') parse_valid_flag(mut t, '-test')
@ -49,22 +49,22 @@ fn test_parse_invalid_cflags() {
assert_parse_invalid_flag(mut t, 'solaris') assert_parse_invalid_flag(mut t, 'solaris')
assert_parse_invalid_flag(mut t, 'windows') assert_parse_invalid_flag(mut t, 'windows')
// Empty flag is not allowed // Empty flag is not allowed
assert_parse_invalid_flag(mut t, no_flag) assert_parse_invalid_flag(mut t, main.no_flag)
assert t.cflags.len == 0 assert t.cflags.len == 0
} }
fn parse_valid_flag(mut t table.Table, flag string) { fn parse_valid_flag(mut t table.Table, flag string) {
t.parse_cflag(flag, module_name, cdefines) or { } t.parse_cflag(flag, main.module_name, main.cdefines) or { }
} }
fn assert_parse_invalid_flag(mut t table.Table, flag string) { fn assert_parse_invalid_flag(mut t table.Table, flag string) {
t.parse_cflag(flag, module_name, cdefines) or { return } t.parse_cflag(flag, main.module_name, main.cdefines) or { return }
assert false assert false
} }
fn make_flag(os string, name string, value string) cflag.CFlag { fn make_flag(os string, name string, value string) cflag.CFlag {
return cflag.CFlag{ return cflag.CFlag{
mod: module_name mod: main.module_name
os: os os: os
name: name name: name
value: value value: value

View File

@ -728,19 +728,19 @@ pub fn (t &Table) mktyp(typ Type) Type {
} }
} }
pub fn (mut table Table) register_fn_gen_type(fn_name string, types []Type) { pub fn (mut mytable Table) register_fn_gen_type(fn_name string, types []Type) {
mut a := table.fn_gen_types[fn_name] mut a := mytable.fn_gen_types[fn_name]
if types in a { if types in a {
return return
} }
a << types a << types
table.fn_gen_types[fn_name] = a mytable.fn_gen_types[fn_name] = a
} }
// TODO: there is a bug when casting sumtype the other way if its pointer // TODO: there is a bug when casting sumtype the other way if its pointer
// so until fixed at least show v (not C) error `x(variant) = y(SumType*)` // so until fixed at least show v (not C) error `x(variant) = y(SumType*)`
pub fn (table &Table) sumtype_has_variant(parent Type, variant Type) bool { pub fn (mytable &Table) sumtype_has_variant(parent Type, variant Type) bool {
parent_sym := table.get_type_symbol(parent) parent_sym := mytable.get_type_symbol(parent)
if parent_sym.kind == .sum_type { if parent_sym.kind == .sum_type {
parent_info := parent_sym.info as SumType parent_info := parent_sym.info as SumType
for v in parent_info.variants { for v in parent_info.variants {
@ -752,14 +752,14 @@ pub fn (table &Table) sumtype_has_variant(parent Type, variant Type) bool {
return false return false
} }
pub fn (table &Table) known_type_names() []string { pub fn (mytable &Table) known_type_names() []string {
mut res := []string{} mut res := []string{}
for _, idx in table.type_idxs { for _, idx in mytable.type_idxs {
// Skip `int_literal_type_idx` and `float_literal_type_idx` because they shouldn't be visible to the User. // Skip `int_literal_type_idx` and `float_literal_type_idx` because they shouldn't be visible to the User.
if idx in [0, int_literal_type_idx, float_literal_type_idx] { if idx in [0, int_literal_type_idx, float_literal_type_idx] {
continue continue
} }
res << table.type_to_str(idx) res << mytable.type_to_str(idx)
} }
return res return res
} }
@ -767,11 +767,11 @@ pub fn (table &Table) known_type_names() []string {
// has_deep_child_no_ref returns true if type is struct and has any child or nested child with the type of the given name // has_deep_child_no_ref returns true if type is struct and has any child or nested child with the type of the given name
// the given name consists of module and name (`mod.Name`) // the given name consists of module and name (`mod.Name`)
// it doesn't care about childs that are references // it doesn't care about childs that are references
pub fn (table &Table) has_deep_child_no_ref(ts &TypeSymbol, name string) bool { pub fn (mytable &Table) has_deep_child_no_ref(ts &TypeSymbol, name string) bool {
if ts.info is Struct { if ts.info is Struct {
for _, field in ts.info.fields { for _, field in ts.info.fields {
sym := table.get_type_symbol(field.typ) sym := mytable.get_type_symbol(field.typ)
if !field.typ.is_ptr() && (sym.name == name || table.has_deep_child_no_ref(sym, name)) { if !field.typ.is_ptr() && (sym.name == name || mytable.has_deep_child_no_ref(sym, name)) {
return true return true
} }
} }

View File

@ -76,10 +76,10 @@ pub fn (t ShareType) str() string {
pub fn (t Type) atomic_typename() string { pub fn (t Type) atomic_typename() string {
idx := t.idx() idx := t.idx()
match idx { match idx {
u32_type_idx { return 'atomic_uint' } table.u32_type_idx { return 'atomic_uint' }
int_type_idx { return 'atomic_int' } table.int_type_idx { return 'atomic_int' }
u64_type_idx { return 'atomic_ullong' } table.u64_type_idx { return 'atomic_ullong' }
i64_type_idx { return 'atomic_llong' } table.i64_type_idx { return 'atomic_llong' }
else { return 'unknown_atomic' } else { return 'unknown_atomic' }
} }
} }
@ -100,12 +100,12 @@ pub fn (t Type) idx() int {
[inline] [inline]
pub fn (t Type) is_void() bool { pub fn (t Type) is_void() bool {
return t == void_type return t == table.void_type
} }
[inline] [inline]
pub fn (t Type) is_full() bool { pub fn (t Type) is_full() bool {
return t != 0 && t != void_type return t != 0 && t != table.void_type
} }
// return nr_muls for `t` // return nr_muls for `t`
@ -240,42 +240,42 @@ pub fn new_type_ptr(idx int, nr_muls int) Type {
// built in pointers (voidptr, byteptr, charptr) // built in pointers (voidptr, byteptr, charptr)
[inline] [inline]
pub fn (typ Type) is_pointer() bool { pub fn (typ Type) is_pointer() bool {
return typ.idx() in pointer_type_idxs return typ.idx() in table.pointer_type_idxs
} }
[inline] [inline]
pub fn (typ Type) is_float() bool { pub fn (typ Type) is_float() bool {
return typ.idx() in float_type_idxs return typ.idx() in table.float_type_idxs
} }
[inline] [inline]
pub fn (typ Type) is_int() bool { pub fn (typ Type) is_int() bool {
return typ.idx() in integer_type_idxs return typ.idx() in table.integer_type_idxs
} }
[inline] [inline]
pub fn (typ Type) is_signed() bool { pub fn (typ Type) is_signed() bool {
return typ.idx() in signed_integer_type_idxs return typ.idx() in table.signed_integer_type_idxs
} }
[inline] [inline]
pub fn (typ Type) is_unsigned() bool { pub fn (typ Type) is_unsigned() bool {
return typ.idx() in unsigned_integer_type_idxs return typ.idx() in table.unsigned_integer_type_idxs
} }
[inline] [inline]
pub fn (typ Type) is_int_literal() bool { pub fn (typ Type) is_int_literal() bool {
return typ.idx() == int_literal_type_idx return typ.idx() == table.int_literal_type_idx
} }
[inline] [inline]
pub fn (typ Type) is_number() bool { pub fn (typ Type) is_number() bool {
return typ.idx() in number_type_idxs return typ.idx() in table.number_type_idxs
} }
[inline] [inline]
pub fn (typ Type) is_string() bool { pub fn (typ Type) is_string() bool {
return typ.idx() in string_type_idxs return typ.idx() in table.string_type_idxs
} }
pub const ( pub const (
@ -745,16 +745,16 @@ pub fn (table &Table) type_to_str(t Type) string {
} }
// type name in code (for builtin) // type name in code (for builtin)
pub fn (table &Table) type_to_code(t Type) string { pub fn (mytable &Table) type_to_code(t Type) string {
match t { match t {
int_literal_type, float_literal_type { return table.get_type_symbol(t).kind.str() } table.int_literal_type, table.float_literal_type { return mytable.get_type_symbol(t).kind.str() }
else { return table.type_to_str_using_aliases(t, map[string]string{}) } else { return mytable.type_to_str_using_aliases(t, map[string]string{}) }
} }
} }
// import_aliases is a map of imported symbol aliases 'module.Type' => 'Type' // import_aliases is a map of imported symbol aliases 'module.Type' => 'Type'
pub fn (table &Table) type_to_str_using_aliases(t Type, import_aliases map[string]string) string { pub fn (mytable &Table) type_to_str_using_aliases(t Type, import_aliases map[string]string) string {
sym := table.get_type_symbol(t) sym := mytable.get_type_symbol(t)
mut res := sym.name mut res := sym.name
match sym.kind { match sym.kind {
.int_literal, .float_literal { .int_literal, .float_literal {
@ -766,20 +766,20 @@ pub fn (table &Table) type_to_str_using_aliases(t Type, import_aliases map[strin
res = sym.kind.str() res = sym.kind.str()
} }
.array { .array {
if t == array_type { if t == table.array_type {
return 'array' return 'array'
} }
if t.has_flag(.variadic) { if t.has_flag(.variadic) {
res = table.type_to_str_using_aliases(table.value_type(t), import_aliases) res = mytable.type_to_str_using_aliases(mytable.value_type(t), import_aliases)
} else { } else {
info := sym.info as Array info := sym.info as Array
elem_str := table.type_to_str_using_aliases(info.elem_type, import_aliases) elem_str := mytable.type_to_str_using_aliases(info.elem_type, import_aliases)
res = '[]$elem_str' res = '[]$elem_str'
} }
} }
.array_fixed { .array_fixed {
info := sym.info as ArrayFixed info := sym.info as ArrayFixed
elem_str := table.type_to_str_using_aliases(info.elem_type, import_aliases) elem_str := mytable.type_to_str_using_aliases(info.elem_type, import_aliases)
res = '[$info.size]$elem_str' res = '[$info.size]$elem_str'
} }
.chan { .chan {
@ -792,31 +792,31 @@ pub fn (table &Table) type_to_str_using_aliases(t Type, import_aliases map[strin
mut_str = 'mut ' mut_str = 'mut '
elem_type = elem_type.set_nr_muls(elem_type.nr_muls() - 1) elem_type = elem_type.set_nr_muls(elem_type.nr_muls() - 1)
} }
elem_str := table.type_to_str_using_aliases(elem_type, import_aliases) elem_str := mytable.type_to_str_using_aliases(elem_type, import_aliases)
res = 'chan $mut_str$elem_str' res = 'chan $mut_str$elem_str'
} }
} }
.function { .function {
info := sym.info as FnType info := sym.info as FnType
if !table.is_fmt { if !mytable.is_fmt {
res = table.fn_signature(info.func, type_only: true) res = mytable.fn_signature(info.func, type_only: true)
} else { } else {
if res.starts_with('fn (') { if res.starts_with('fn (') {
// fn foo () // fn foo ()
res = table.fn_signature(info.func, type_only: true) res = mytable.fn_signature(info.func, type_only: true)
} else { } else {
// FnFoo // FnFoo
res = table.shorten_user_defined_typenames(res, import_aliases) res = mytable.shorten_user_defined_typenames(res, import_aliases)
} }
} }
} }
.map { .map {
if int(t) == map_type_idx { if int(t) == table.map_type_idx {
return 'map' return 'map'
} }
info := sym.info as Map info := sym.info as Map
key_str := table.type_to_str_using_aliases(info.key_type, import_aliases) key_str := mytable.type_to_str_using_aliases(info.key_type, import_aliases)
val_str := table.type_to_str_using_aliases(info.value_type, import_aliases) val_str := mytable.type_to_str_using_aliases(info.value_type, import_aliases)
res = 'map[$key_str]$val_str' res = 'map[$key_str]$val_str'
} }
.multi_return { .multi_return {
@ -826,7 +826,7 @@ pub fn (table &Table) type_to_str_using_aliases(t Type, import_aliases map[strin
if i > 0 { if i > 0 {
res += ', ' res += ', '
} }
res += table.type_to_str_using_aliases(typ, import_aliases) res += mytable.type_to_str_using_aliases(typ, import_aliases)
} }
res += ')' res += ')'
} }
@ -837,7 +837,7 @@ pub fn (table &Table) type_to_str_using_aliases(t Type, import_aliases map[strin
return 'void' return 'void'
} }
else { else {
res = table.shorten_user_defined_typenames(res, import_aliases) res = mytable.shorten_user_defined_typenames(res, import_aliases)
} }
} }
nr_muls := t.nr_muls() nr_muls := t.nr_muls()
@ -899,7 +899,7 @@ pub fn (t &Table) fn_signature(func &Fn, opts FnSignatureOpts) string {
sb.write('$styp') sb.write('$styp')
} }
sb.write(')') sb.write(')')
if func.return_type != void_type { if func.return_type != table.void_type {
sb.write(' ${t.type_to_str(func.return_type)}') sb.write(' ${t.type_to_str(func.return_type)}')
} }
return sb.str() return sb.str()

View File

@ -47,14 +47,14 @@ pub fn (e &EManager) set_support_color(b bool) {
} }
pub fn bold(msg string) string { pub fn bold(msg string) string {
if !emanager.support_color { if !util.emanager.support_color {
return msg return msg
} }
return term.bold(msg) return term.bold(msg)
} }
fn color(kind string, msg string) string { fn color(kind string, msg string) string {
if !emanager.support_color { if !util.emanager.support_color {
return msg return msg
} }
if kind.contains('error') { if kind.contains('error') {
@ -112,8 +112,8 @@ pub fn source_context(kind string, source string, column int, pos token.Position
return clines return clines
} }
source_lines := source.split_into_lines() source_lines := source.split_into_lines()
bline := imax(0, pos.line_nr - error_context_before) bline := imax(0, pos.line_nr - util.error_context_before)
aline := imax(0, imin(source_lines.len - 1, pos.line_nr + error_context_after)) aline := imax(0, imin(source_lines.len - 1, pos.line_nr + util.error_context_after))
tab_spaces := ' ' tab_spaces := ' '
for iline := bline; iline <= aline; iline++ { for iline := bline; iline <= aline; iline++ {
sline := source_lines[iline] sline := source_lines[iline]

View File

@ -58,7 +58,7 @@ pub fn smart_quote(str string, raw bool) string {
skip_next = true skip_next = true
} }
// keep all valid escape sequences // keep all valid escape sequences
else if next !in invalid_escapes { else if next !in util.invalid_escapes {
toadd = '\\' + next toadd = '\\' + next
skip_next = true skip_next = true
} else { } else {

View File

@ -45,10 +45,10 @@ pub fn full_hash() string {
// full_v_version() returns the full version of the V compiler // full_v_version() returns the full version of the V compiler
pub fn full_v_version(is_verbose bool) string { pub fn full_v_version(is_verbose bool) string {
if is_verbose { if is_verbose {
return 'V $v_version $full_hash()' return 'V $util.v_version $full_hash()'
} }
hash := githash(false) hash := githash(false)
return 'V $v_version $hash' return 'V $util.v_version $hash'
} }
// githash(x) returns the current git commit hash. // githash(x) returns the current git commit hash.
@ -163,7 +163,7 @@ pub fn launch_tool(is_verbose bool, tool_name string, args []string) {
println('launch_tool should_compile: $should_compile') println('launch_tool should_compile: $should_compile')
} }
if should_compile { if should_compile {
emodules := external_module_dependencies_for_tool[tool_name] emodules := util.external_module_dependencies_for_tool[tool_name]
for emodule in emodules { for emodule in emodules {
check_module_is_installed(emodule, is_verbose) or { panic(err) } check_module_is_installed(emodule, is_verbose) or { panic(err) }
} }
@ -411,7 +411,7 @@ and the existing module `$modulename` may still work.')
} }
pub fn ensure_modules_for_all_tools_are_installed(is_verbose bool) { pub fn ensure_modules_for_all_tools_are_installed(is_verbose bool) {
for tool_name, tool_modules in external_module_dependencies_for_tool { for tool_name, tool_modules in util.external_module_dependencies_for_tool {
if is_verbose { if is_verbose {
eprintln('Installing modules for tool: $tool_name ...') eprintln('Installing modules for tool: $tool_name ...')
} }
@ -444,9 +444,9 @@ const (
pub fn no_cur_mod(typename string, cur_mod string) string { pub fn no_cur_mod(typename string, cur_mod string) string {
mut res := typename mut res := typename
mod_prefix := cur_mod + '.' mod_prefix := cur_mod + '.'
has_map_prefix := res.starts_with(map_prefix) has_map_prefix := res.starts_with(util.map_prefix)
if has_map_prefix { if has_map_prefix {
res = res.replace_once(map_prefix, '') res = res.replace_once(util.map_prefix, '')
} }
no_symbols := res.trim_left('&[]') no_symbols := res.trim_left('&[]')
should_shorten := no_symbols.starts_with(mod_prefix) should_shorten := no_symbols.starts_with(mod_prefix)
@ -454,7 +454,7 @@ pub fn no_cur_mod(typename string, cur_mod string) string {
res = res.replace_once(mod_prefix, '') res = res.replace_once(mod_prefix, '')
} }
if has_map_prefix { if has_map_prefix {
res = map_prefix + res res = util.map_prefix + res
} }
return res return res
} }
@ -496,5 +496,6 @@ pub fn get_vtmp_folder() string {
} }
pub fn should_bundle_module(mod string) bool { pub fn should_bundle_module(mod string) bool {
return mod in bundle_modules || (mod.contains('.') && mod.all_before('.') in bundle_modules) return mod in util.bundle_modules
|| (mod.contains('.') && mod.all_before('.') in util.bundle_modules)
} }

View File

@ -139,7 +139,7 @@ const (
) )
fn (mcache &ModFileCacher) check_for_stop(cfolder string, files []string) bool { fn (mcache &ModFileCacher) check_for_stop(cfolder string, files []string) bool {
for i in mod_file_stop_paths { for i in vmod.mod_file_stop_paths {
if i in files { if i in files {
return true return true
} }
@ -167,5 +167,5 @@ const (
) )
pub fn get_cache() &ModFileCacher { pub fn get_cache() &ModFileCacher {
return private_file_cacher return vmod.private_file_cacher
} }

View File

@ -159,7 +159,7 @@ fn (mut am AssetManager) add(asset_type string, file string) bool {
} else if asset_type == 'js' { } else if asset_type == 'js' {
am.js << asset am.js << asset
} else { } else {
panic('$unknown_asset_type_error ($asset_type).') panic('$assets.unknown_asset_type_error ($asset_type).')
} }
return true return true
} }
@ -176,7 +176,7 @@ fn (am AssetManager) exists(asset_type string, file string) bool {
fn (am AssetManager) get_assets(asset_type string) []Asset { fn (am AssetManager) get_assets(asset_type string) []Asset {
if asset_type != 'css' && asset_type != 'js' { if asset_type != 'css' && asset_type != 'js' {
panic('$unknown_asset_type_error ($asset_type).') panic('$assets.unknown_asset_type_error ($asset_type).')
} }
assets := if asset_type == 'css' { am.css } else { am.js } assets := if asset_type == 'css' { am.css } else { am.js }
return assets return assets

View File

@ -18,18 +18,18 @@ const (
// setup of vweb webserver // setup of vweb webserver
fn testsuite_begin() { fn testsuite_begin() {
os.chdir(vroot) os.chdir(main.vroot)
if os.exists(serverexe) { if os.exists(main.serverexe) {
os.rm(serverexe) os.rm(main.serverexe)
} }
} }
fn test_a_simple_vweb_app_can_be_compiled() { fn test_a_simple_vweb_app_can_be_compiled() {
// did_server_compile := os.system('$vexe -g -o $serverexe vlib/vweb/tests/vweb_test_server.v') // did_server_compile := os.system('$vexe -g -o $serverexe vlib/vweb/tests/vweb_test_server.v')
// TODO: find out why it does not compile with -usecache and -g // TODO: find out why it does not compile with -usecache and -g
did_server_compile := os.system('$vexe -o $serverexe vlib/vweb/tests/vweb_test_server.v') did_server_compile := os.system('$main.vexe -o $main.serverexe vlib/vweb/tests/vweb_test_server.v')
assert did_server_compile == 0 assert did_server_compile == 0
assert os.exists(serverexe) assert os.exists(main.serverexe)
} }
fn test_a_simple_vweb_app_runs_in_the_background() { fn test_a_simple_vweb_app_runs_in_the_background() {
@ -37,10 +37,10 @@ fn test_a_simple_vweb_app_runs_in_the_background() {
$if !windows { $if !windows {
suffix = ' > /dev/null &' suffix = ' > /dev/null &'
} }
if vweb_logfile != '' { if main.vweb_logfile != '' {
suffix = ' 2>> $vweb_logfile >> $vweb_logfile &' suffix = ' 2>> $main.vweb_logfile >> $main.vweb_logfile &'
} }
server_exec_cmd := '$serverexe $sport $exit_after_time $suffix' server_exec_cmd := '$main.serverexe $main.sport $main.exit_after_time $suffix'
$if debug_net_socket_client ? { $if debug_net_socket_client ? {
eprintln('running:\n$server_exec_cmd') eprintln('running:\n$server_exec_cmd')
} }
@ -102,14 +102,14 @@ fn assert_common_http_headers(x http.Response) {
} }
fn test_http_client_index() { fn test_http_client_index() {
x := http.get('http://127.0.0.1:$sport/') or { panic(err) } x := http.get('http://127.0.0.1:$main.sport/') or { panic(err) }
assert_common_http_headers(x) assert_common_http_headers(x)
assert x.headers['Content-Type'] == 'text/plain' assert x.headers['Content-Type'] == 'text/plain'
assert x.text == 'Welcome to VWeb' assert x.text == 'Welcome to VWeb'
} }
fn test_http_client_chunk_transfer() { fn test_http_client_chunk_transfer() {
x := http.get('http://127.0.0.1:$sport/chunk') or { panic(err) } x := http.get('http://127.0.0.1:$main.sport/chunk') or { panic(err) }
assert_common_http_headers(x) assert_common_http_headers(x)
assert x.headers['Transfer-Encoding'] == 'chunked' assert x.headers['Transfer-Encoding'] == 'chunked'
assert x.text == 'Lorem ipsum dolor sit amet, consetetur sadipscing' assert x.text == 'Lorem ipsum dolor sit amet, consetetur sadipscing'
@ -117,9 +117,9 @@ fn test_http_client_chunk_transfer() {
fn test_http_client_404() { fn test_http_client_404() {
url_404_list := [ url_404_list := [
'http://127.0.0.1:$sport/zxcnbnm', 'http://127.0.0.1:$main.sport/zxcnbnm',
'http://127.0.0.1:$sport/JHKAJA', 'http://127.0.0.1:$main.sport/JHKAJA',
'http://127.0.0.1:$sport/unknown', 'http://127.0.0.1:$main.sport/unknown',
] ]
for url in url_404_list { for url in url_404_list {
res := http.get(url) or { panic(err) } res := http.get(url) or { panic(err) }
@ -128,39 +128,39 @@ fn test_http_client_404() {
} }
fn test_http_client_simple() { fn test_http_client_simple() {
x := http.get('http://127.0.0.1:$sport/simple') or { panic(err) } x := http.get('http://127.0.0.1:$main.sport/simple') or { panic(err) }
assert_common_http_headers(x) assert_common_http_headers(x)
assert x.headers['Content-Type'] == 'text/plain' assert x.headers['Content-Type'] == 'text/plain'
assert x.text == 'A simple result' assert x.text == 'A simple result'
} }
fn test_http_client_html_page() { fn test_http_client_html_page() {
x := http.get('http://127.0.0.1:$sport/html_page') or { panic(err) } x := http.get('http://127.0.0.1:$main.sport/html_page') or { panic(err) }
assert_common_http_headers(x) assert_common_http_headers(x)
assert x.headers['Content-Type'] == 'text/html' assert x.headers['Content-Type'] == 'text/html'
assert x.text == '<h1>ok</h1>' assert x.text == '<h1>ok</h1>'
} }
fn test_http_client_settings_page() { fn test_http_client_settings_page() {
x := http.get('http://127.0.0.1:$sport/bilbo/settings') or { panic(err) } x := http.get('http://127.0.0.1:$main.sport/bilbo/settings') or { panic(err) }
assert_common_http_headers(x) assert_common_http_headers(x)
assert x.text == 'username: bilbo' assert x.text == 'username: bilbo'
// //
y := http.get('http://127.0.0.1:$sport/kent/settings') or { panic(err) } y := http.get('http://127.0.0.1:$main.sport/kent/settings') or { panic(err) }
assert_common_http_headers(y) assert_common_http_headers(y)
assert y.text == 'username: kent' assert y.text == 'username: kent'
} }
fn test_http_client_user_repo_settings_page() { fn test_http_client_user_repo_settings_page() {
x := http.get('http://127.0.0.1:$sport/bilbo/gostamp/settings') or { panic(err) } x := http.get('http://127.0.0.1:$main.sport/bilbo/gostamp/settings') or { panic(err) }
assert_common_http_headers(x) assert_common_http_headers(x)
assert x.text == 'username: bilbo | repository: gostamp' assert x.text == 'username: bilbo | repository: gostamp'
// //
y := http.get('http://127.0.0.1:$sport/kent/golang/settings') or { panic(err) } y := http.get('http://127.0.0.1:$main.sport/kent/golang/settings') or { panic(err) }
assert_common_http_headers(y) assert_common_http_headers(y)
assert y.text == 'username: kent | repository: golang' assert y.text == 'username: kent | repository: golang'
// //
z := http.get('http://127.0.0.1:$sport/missing/golang/settings') or { panic(err) } z := http.get('http://127.0.0.1:$main.sport/missing/golang/settings') or { panic(err) }
assert z.status_code == 404 assert z.status_code == 404
} }
@ -175,7 +175,9 @@ fn test_http_client_json_post() {
age: 123 age: 123
} }
json_for_ouser := json.encode(ouser) json_for_ouser := json.encode(ouser)
mut x := http.post_json('http://127.0.0.1:$sport/json_echo', json_for_ouser) or { panic(err) } mut x := http.post_json('http://127.0.0.1:$main.sport/json_echo', json_for_ouser) or {
panic(err)
}
$if debug_net_socket_client ? { $if debug_net_socket_client ? {
eprintln('/json_echo endpoint response: $x') eprintln('/json_echo endpoint response: $x')
} }
@ -184,7 +186,7 @@ fn test_http_client_json_post() {
nuser := json.decode(User, x.text) or { User{} } nuser := json.decode(User, x.text) or { User{} }
assert '$ouser' == '$nuser' assert '$ouser' == '$nuser'
// //
x = http.post_json('http://127.0.0.1:$sport/json', json_for_ouser) or { panic(err) } x = http.post_json('http://127.0.0.1:$main.sport/json', json_for_ouser) or { panic(err) }
$if debug_net_socket_client ? { $if debug_net_socket_client ? {
eprintln('/json endpoint response: $x') eprintln('/json endpoint response: $x')
} }
@ -195,7 +197,7 @@ fn test_http_client_json_post() {
} }
fn test_http_client_shutdown_does_not_work_without_a_cookie() { fn test_http_client_shutdown_does_not_work_without_a_cookie() {
x := http.get('http://127.0.0.1:$sport/shutdown') or { x := http.get('http://127.0.0.1:$main.sport/shutdown') or {
assert err == '' assert err == ''
return return
} }
@ -206,7 +208,7 @@ fn test_http_client_shutdown_does_not_work_without_a_cookie() {
fn testsuite_end() { fn testsuite_end() {
// This test is guaranteed to be called last. // This test is guaranteed to be called last.
// It sends a request to the server to shutdown. // It sends a request to the server to shutdown.
x := http.fetch('http://127.0.0.1:$sport/shutdown', x := http.fetch('http://127.0.0.1:$main.sport/shutdown',
method: .get method: .get
cookies: { cookies: {
'skey': 'superman' 'skey': 'superman'
@ -234,7 +236,7 @@ fn simple_tcp_client(config SimpleTcpClientConfig) ?string {
mut tries := 0 mut tries := 0
for tries < config.retries { for tries < config.retries {
tries++ tries++
client = net.dial_tcp('127.0.0.1:$sport') or { client = net.dial_tcp('127.0.0.1:$main.sport') or {
if tries > config.retries { if tries > config.retries {
return error(err) return error(err)
} }
@ -243,8 +245,8 @@ fn simple_tcp_client(config SimpleTcpClientConfig) ?string {
} }
break break
} }
client.set_read_timeout(tcp_r_timeout) client.set_read_timeout(main.tcp_r_timeout)
client.set_write_timeout(tcp_w_timeout) client.set_write_timeout(main.tcp_w_timeout)
defer { defer {
client.close() client.close()
} }

View File

@ -64,7 +64,7 @@ pub fn (mut app App) chunk() vweb.Result {
// the following serve custom routes // the following serve custom routes
['/:user/settings'] ['/:user/settings']
pub fn (mut app App) settings(username string) vweb.Result { pub fn (mut app App) settings(username string) vweb.Result {
if username !in known_users { if username !in main.known_users {
return app.not_found() return app.not_found()
} }
return app.html('username: $username') return app.html('username: $username')
@ -72,7 +72,7 @@ pub fn (mut app App) settings(username string) vweb.Result {
['/:user/:repo/settings'] ['/:user/:repo/settings']
pub fn (mut app App) user_repo_settings(username string, repository string) vweb.Result { pub fn (mut app App) user_repo_settings(username string, repository string) vweb.Result {
if username !in known_users { if username !in main.known_users {
return app.not_found() return app.not_found()
} }
return app.html('username: $username | repository: $repository') return app.html('username: $username | repository: $repository')

View File

@ -58,7 +58,7 @@ footer := \' \' // TODO remove
_ = footer _ = footer
") ")
s.write(str_start) s.write(tmpl.str_start)
mut state := State.html mut state := State.html
mut in_span := false mut in_span := false
// for _line in lines { // for _line in lines {
@ -99,23 +99,23 @@ _ = footer
s.write(line[pos + 6..line.len - 1]) s.write(line[pos + 6..line.len - 1])
s.writeln('" rel="stylesheet" type="text/css">') s.writeln('" rel="stylesheet" type="text/css">')
} else if line.contains('@if ') { } else if line.contains('@if ') {
s.writeln(str_end) s.writeln(tmpl.str_end)
pos := line.index('@if') or { continue } pos := line.index('@if') or { continue }
s.writeln('if ' + line[pos + 4..] + '{') s.writeln('if ' + line[pos + 4..] + '{')
s.writeln(str_start) s.writeln(tmpl.str_start)
} else if line.contains('@end') { } else if line.contains('@end') {
s.writeln(str_end) s.writeln(tmpl.str_end)
s.writeln('}') s.writeln('}')
s.writeln(str_start) s.writeln(tmpl.str_start)
} else if line.contains('@else') { } else if line.contains('@else') {
s.writeln(str_end) s.writeln(tmpl.str_end)
s.writeln(' } else { ') s.writeln(' } else { ')
s.writeln(str_start) s.writeln(tmpl.str_start)
} else if line.contains('@for') { } else if line.contains('@for') {
s.writeln(str_end) s.writeln(tmpl.str_end)
pos := line.index('@for') or { continue } pos := line.index('@for') or { continue }
s.writeln('for ' + line[pos + 4..] + '{') s.writeln('for ' + line[pos + 4..] + '{')
s.writeln(str_start) s.writeln(tmpl.str_start)
} else if state == .html && line.contains('span.') && line.ends_with('{') { } else if state == .html && line.contains('span.') && line.ends_with('{') {
// `span.header {` => `<span class='header'>` // `span.header {` => `<span class='header'>`
class := line.find_between('span.', '{').trim_space() class := line.find_between('span.', '{').trim_space()
@ -142,7 +142,7 @@ _ = footer
s.writeln(line.replace('@', '$').replace("'", '"')) s.writeln(line.replace('@', '$').replace("'", '"'))
} }
} }
s.writeln(str_end) s.writeln(tmpl.str_end)
s.writeln('_tmpl_res_$fn_name := sb.str() ') s.writeln('_tmpl_res_$fn_name := sb.str() ')
s.writeln('}') s.writeln('}')
s.writeln('// === end of vweb html template ===') s.writeln('// === end of vweb html template ===')

View File

@ -106,7 +106,7 @@ pub fn (mut ctx Context) send_response_to_client(mimetype string, res string) bo
} }
sb.write(ctx.headers) sb.write(ctx.headers)
sb.write('\r\n') sb.write('\r\n')
sb.write(headers_close) sb.write(vweb.headers_close)
if ctx.chunked_transfer { if ctx.chunked_transfer {
mut i := 0 mut i := 0
mut len := res.len mut len := res.len
@ -163,7 +163,7 @@ pub fn (mut ctx Context) redirect(url string) Result {
return Result{} return Result{}
} }
ctx.done = true ctx.done = true
send_string(mut ctx.conn, 'HTTP/1.1 302 Found\r\nLocation: $url$ctx.headers\r\n$headers_close') or { send_string(mut ctx.conn, 'HTTP/1.1 302 Found\r\nLocation: $url$ctx.headers\r\n$vweb.headers_close') or {
return Result{} return Result{}
} }
return Result{} return Result{}
@ -174,7 +174,7 @@ pub fn (mut ctx Context) not_found() Result {
return Result{} return Result{}
} }
ctx.done = true ctx.done = true
send_string(mut ctx.conn, http_404) or { } send_string(mut ctx.conn, vweb.http_404) or { }
return Result{} return Result{}
} }
@ -317,7 +317,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T) {
vals := first_line.split(' ') vals := first_line.split(' ')
if vals.len < 2 { if vals.len < 2 {
println('no vals for http') println('no vals for http')
send_string(mut conn, http_500) or { } send_string(mut conn, vweb.http_500) or { }
return return
} }
mut headers := []string{} mut headers := []string{}
@ -397,7 +397,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T) {
page_gen_start: page_gen_start page_gen_start: page_gen_start
} }
// } // }
if req.method in methods_with_form { if req.method in vweb.methods_with_form {
if ct == 'multipart/form-data' { if ct == 'multipart/form-data' {
app.parse_multipart_form(body, boundary) app.parse_multipart_form(body, boundary)
} else { } else {
@ -420,7 +420,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T) {
mime_type := app.static_mime_types[static_file_name] mime_type := app.static_mime_types[static_file_name]
if static_file != '' && mime_type != '' { if static_file != '' && mime_type != '' {
data := os.read_file(static_file) or { data := os.read_file(static_file) or {
send_string(mut conn, http_404) or { } send_string(mut conn, vweb.http_404) or { }
return return
} }
app.send_response_to_client(mime_type, data) app.send_response_to_client(mime_type, data)
@ -516,7 +516,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T) {
for route_words_ in route_words_a { for route_words_ in route_words_a {
// cannot move to line initialize line because of C error with map(it.filter(it != '')) // cannot move to line initialize line because of C error with map(it.filter(it != ''))
route_words := route_words_.filter(it != '') route_words := route_words_.filter(it != '')
if route_words.len == 1 && route_words[0] in methods_without_first { if route_words.len == 1 && route_words[0] in vweb.methods_without_first {
req_method << route_words[0] req_method << route_words[0]
} }
if url_words.len == route_words.len if url_words.len == route_words.len
@ -581,7 +581,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T) {
} }
if action == '' { if action == '' {
// site not found // site not found
send_string(mut conn, http_404) or { } send_string(mut conn, vweb.http_404) or { }
return return
} }
$for method in T.methods { $for method in T.methods {
@ -600,7 +600,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T) {
} }
pub fn (mut ctx Context) parse_form(s string) { pub fn (mut ctx Context) parse_form(s string) {
if ctx.req.method !in methods_with_form { if ctx.req.method !in vweb.methods_with_form {
return return
} }
// pos := s.index('\r\n\r\n') // pos := s.index('\r\n\r\n')
@ -630,7 +630,7 @@ pub fn (mut ctx Context) parse_form(s string) {
[manualfree] [manualfree]
pub fn (mut ctx Context) parse_multipart_form(s string, b string) { pub fn (mut ctx Context) parse_multipart_form(s string, b string) {
if ctx.req.method !in methods_with_form { if ctx.req.method !in vweb.methods_with_form {
return return
} }
a := s.split('$b')[1..] a := s.split('$b')[1..]
@ -696,8 +696,8 @@ fn (mut ctx Context) scan_static_directory(directory_path string, mount_path str
ext := os.file_ext(file) ext := os.file_ext(file)
// Rudimentary guard against adding files not in mime_types. // Rudimentary guard against adding files not in mime_types.
// Use serve_static directly to add non-standard mime types. // Use serve_static directly to add non-standard mime types.
if ext in mime_types { if ext in vweb.mime_types {
ctx.serve_static(mount_path + '/' + file, full_path, mime_types[ext]) ctx.serve_static(mount_path + '/' + file, full_path, vweb.mime_types[ext])
} }
} }
} }

View File

@ -223,7 +223,7 @@ pub fn (mut ws Client) parse_frame_header() ?Frame {
buffer[bytes_read] = rbuff[0] buffer[bytes_read] = rbuff[0]
bytes_read++ bytes_read++
// parses the first two header bytes to get basic frame information // parses the first two header bytes to get basic frame information
if bytes_read == u64(header_len_offset) { if bytes_read == u64(websocket.header_len_offset) {
frame.fin = (buffer[0] & 0x80) == 0x80 frame.fin = (buffer[0] & 0x80) == 0x80
frame.rsv1 = (buffer[0] & 0x40) == 0x40 frame.rsv1 = (buffer[0] & 0x40) == 0x40
frame.rsv2 = (buffer[0] & 0x20) == 0x20 frame.rsv2 = (buffer[0] & 0x20) == 0x20
@ -234,11 +234,11 @@ pub fn (mut ws Client) parse_frame_header() ?Frame {
// if has mask set the byte postition where mask ends // if has mask set the byte postition where mask ends
if frame.has_mask { if frame.has_mask {
mask_end_byte = if frame.payload_len < 126 { mask_end_byte = if frame.payload_len < 126 {
header_len_offset + 4 websocket.header_len_offset + 4
} else if frame.payload_len == 126 { } else if frame.payload_len == 126 {
header_len_offset + 6 websocket.header_len_offset + 6
} else if frame.payload_len == 127 { } else if frame.payload_len == 127 {
header_len_offset + 12 websocket.header_len_offset + 12
} else { } else {
0 0
} // impossible } // impossible
@ -249,7 +249,7 @@ pub fn (mut ws Client) parse_frame_header() ?Frame {
break break
} }
} }
if frame.payload_len == 126 && bytes_read == u64(extended_payload16_end_byte) { if frame.payload_len == 126 && bytes_read == u64(websocket.extended_payload16_end_byte) {
frame.header_len += 2 frame.header_len += 2
frame.payload_len = 0 frame.payload_len = 0
frame.payload_len |= buffer[2] << 8 frame.payload_len |= buffer[2] << 8
@ -259,7 +259,7 @@ pub fn (mut ws Client) parse_frame_header() ?Frame {
break break
} }
} }
if frame.payload_len == 127 && bytes_read == u64(extended_payload64_end_byte) { if frame.payload_len == 127 && bytes_read == u64(websocket.extended_payload64_end_byte) {
frame.header_len += 8 frame.header_len += 8
// these shift operators needs 64 bit on clang with -prod flag // these shift operators needs 64 bit on clang with -prod flag
mut payload_len := u64(0) mut payload_len := u64(0)

View File

@ -360,7 +360,7 @@ fn (mut ws Client) send_control_frame(code OPCode, frame_typ string, payload []b
header_len := if ws.is_server { 2 } else { 6 } header_len := if ws.is_server { 2 } else { 6 }
frame_len := header_len + payload.len frame_len := header_len + payload.len
mut control_frame := []byte{len: frame_len} mut control_frame := []byte{len: frame_len}
mut masking_key := if !ws.is_server { create_masking_key() } else { empty_bytearr } mut masking_key := if !ws.is_server { create_masking_key() } else { websocket.empty_bytearr }
defer { defer {
unsafe { unsafe {
control_frame.free() control_frame.free()