all: unify const names to snake_case

pull/4989/head^2
yuyi 2020-05-22 23:36:09 +08:00 committed by GitHub
parent aef751861d
commit dda875a9c8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
58 changed files with 543 additions and 540 deletions

View File

@ -10,7 +10,7 @@ import os
import benchmark import benchmark
const ( const (
INNER_INDENT = ' ' inner_indent = ' '
) )
struct BenchedTests { struct BenchedTests {
@ -21,7 +21,7 @@ mut:
test_suit_file string test_suit_file string
step_func_name string step_func_name string
} }
// /////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////
// Called at the start of the test program produced by `v -stats file_test.v` // Called at the start of the test program produced by `v -stats file_test.v`
fn start_testing(total_number_of_tests int, vfilename string) BenchedTests { fn start_testing(total_number_of_tests int, vfilename string) BenchedTests {
@ -49,7 +49,7 @@ fn (mut b BenchedTests) testing_step_end() {
// //////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////
if ok_diff == 0 && fail_diff == 0 { if ok_diff == 0 && fail_diff == 0 {
b.bench.neither_fail_nor_ok() b.bench.neither_fail_nor_ok()
println(INNER_INDENT + b.bench.step_message_ok(' NO asserts | ') + b.fn_name()) println(inner_indent + b.bench.step_message_ok(' NO asserts | ') + b.fn_name())
return return
} }
// //////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////
@ -61,11 +61,11 @@ fn (mut b BenchedTests) testing_step_end() {
} }
// //////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////
if ok_diff > 0 && fail_diff == 0 { if ok_diff > 0 && fail_diff == 0 {
println(INNER_INDENT + b.bench.step_message_ok(nasserts(ok_diff)) + b.fn_name()) println(inner_indent + b.bench.step_message_ok(nasserts(ok_diff)) + b.fn_name())
return return
} }
if fail_diff > 0 { if fail_diff > 0 {
println(INNER_INDENT + b.bench.step_message_fail(nasserts(fail_diff)) + b.fn_name()) println(inner_indent + b.bench.step_message_fail(nasserts(fail_diff)) + b.fn_name())
return return
} }
} }
@ -77,7 +77,7 @@ fn (b &BenchedTests) fn_name() string {
// Called at the end of the test program produced by `v -stats file_test.v` // Called at the end of the test program produced by `v -stats file_test.v`
fn (mut b BenchedTests) end_testing() { fn (mut b BenchedTests) end_testing() {
b.bench.stop() b.bench.stop()
println(INNER_INDENT + b.bench.total_message('running V tests in "' + os.file_name(b.test_suit_file) + '"')) println(inner_indent + b.bench.total_message('running V tests in "' + os.file_name(b.test_suit_file) + '"'))
} }
// /////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////

View File

@ -30,7 +30,7 @@ const (
'_linux.v', '_nix.v'], ['macos', '_mac.v', '_darwin.v'], ['freebsd', '_bsd.v', '_freebsd.v'], '_linux.v', '_nix.v'], ['macos', '_mac.v', '_darwin.v'], ['freebsd', '_bsd.v', '_freebsd.v'],
['netbsd', '_bsd.v', '_netbsd.v'], ['openbsd', '_bsd.v', '_openbsd.v'], ['solaris', '_solaris.v'], ['netbsd', '_bsd.v', '_netbsd.v'], ['openbsd', '_bsd.v', '_openbsd.v'], ['solaris', '_solaris.v'],
['haiku', '_haiku.v'], ['qnx', '_qnx.v']] ['haiku', '_haiku.v'], ['qnx', '_qnx.v']]
FORMATTED_FILE_TOKEN = '\@\@\@' + 'FORMATTED_FILE: ' formatted_file_token = '\@\@\@' + 'FORMATTED_FILE: '
) )
fn main() { fn main() {
@ -116,8 +116,8 @@ fn main() {
continue continue
} }
if worker_result.output.len > 0 { if worker_result.output.len > 0 {
if worker_result.output.contains(FORMATTED_FILE_TOKEN) { if worker_result.output.contains(formatted_file_token) {
wresult := worker_result.output.split(FORMATTED_FILE_TOKEN) wresult := worker_result.output.split(formatted_file_token)
formatted_warn_errs := wresult[0] formatted_warn_errs := wresult[0]
formatted_file_path := wresult[1] formatted_file_path := wresult[1]
foptions.post_process_file(fpath, formatted_file_path) foptions.post_process_file(fpath, formatted_file_path)
@ -157,7 +157,7 @@ fn (foptions &FormatOptions) format_file(file string) {
if foptions.is_verbose { if foptions.is_verbose {
eprintln('fmt.fmt worked and ${formatted_content.len} bytes were written to ${vfmt_output_path} .') eprintln('fmt.fmt worked and ${formatted_content.len} bytes were written to ${vfmt_output_path} .')
} }
eprintln('${FORMATTED_FILE_TOKEN}${vfmt_output_path}') eprintln('${formatted_file_token}${vfmt_output_path}')
} }
fn print_compiler_options(compiler_params &pref.Preferences) { fn print_compiler_options(compiler_params &pref.Preferences) {

View File

@ -6,16 +6,16 @@ import gx
import automaton import automaton
const ( const (
screenWidth = 800 screen_width = 800
screenHeight = 600 screen_height = 600
filled_color = gx.Blue filled_color = gx.blue
) )
fn new_graphics() &gg.GG { fn new_graphics() &gg.GG {
glfw.init_glfw() glfw.init_glfw()
return gg.new_context(gg.Cfg{ return gg.new_context(gg.Cfg{
width: screenWidth width: screen_width
height: screenHeight height: screen_height
use_ortho: true use_ortho: true
create_window: true create_window: true
resizable: false resizable: false
@ -49,7 +49,7 @@ fn main() {
gg.post_empty_event() // needed so the animation does not stop gg.post_empty_event() // needed so the animation does not stop
/////////////////////////////////////////////// ///////////////////////////////////////////////
a.update() a.update()
print_automaton(a) print_automaton(a)
graphics.render() graphics.render()
} }
} }

View File

@ -1,10 +1,10 @@
// hanoi tower // hanoi tower
const ( const (
Num = 7 num = 7
) )
fn main() { fn main() {
hanoi(Num, 'A','B','C') hanoi(num, 'A','B','C')
} }
fn move(n int, a, b string) int { fn move(n int, a, b string) int {

View File

@ -7,8 +7,8 @@ import glfw
import math import math
const ( const (
Size = 700 size = 700
Scale = 50.0 scale = 50.0
pi = math.pi pi = math.pi
) )
@ -19,8 +19,8 @@ struct Context {
fn main() { fn main() {
glfw.init_glfw() glfw.init_glfw()
gconfig := gg.Cfg { gconfig := gg.Cfg {
width: Size width: size
height: Size height: size
use_ortho: true use_ortho: true
create_window: true create_window: true
window_title: 'Graph builder' window_title: 'Graph builder'
@ -41,9 +41,9 @@ fn main() {
[live] [live]
fn (ctx &Context) draw() { fn (ctx &Context) draw() {
center := f64(Size / 2) center := f64(size / 2)
ctx.gg.draw_line(0, center, Size, center, gx.gray) // x axis ctx.gg.draw_line(0, center, size, center, gx.gray) // x axis
ctx.gg.draw_line(center, 0, center, Size, gx.gray) // y axis ctx.gg.draw_line(center, 0, center, size, gx.gray) // y axis
atime := f64( time.ticks() / 10 ) atime := f64( time.ticks() / 10 )
stime := math.sin( 2.0 * pi * f64( time.ticks() % 6000 ) / 6000 ) stime := math.sin( 2.0 * pi * f64( time.ticks() % 6000 ) / 6000 )
mut y := 0.0 mut y := 0.0
@ -58,8 +58,8 @@ fn (ctx &Context) draw() {
//y = (x + 3) * (x + 3) / stime + stime*2.5 //y = (x + 3) * (x + 3) / stime + stime*2.5
//y = math.sqrt(30.0 - x * x) * stime //y = math.sqrt(30.0 - x * x) * stime
//y -= (stime-0.5) + stime //y -= (stime-0.5) + stime
ctx.gg.draw_rect(center + x * Scale, center - y * Scale, 1, 1, gx.Blue) ctx.gg.draw_rect(center + x * scale, center - y * scale, 1, 1, gx.blue)
ctx.gg.draw_rect(center + x * Scale, center + y * Scale, 1, 1, gx.Red) ctx.gg.draw_rect(center + x * scale, center + y * scale, 1, 1, gx.red)
} }
} }

View File

@ -4,7 +4,7 @@
import os import os
const ( const (
NUMERIC_CHAR = [`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`.`,`e`,`E`] numeric_char = [`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`.`,`e`,`E`]
) )
// Convert expression to Reverse Polish Notation. // Convert expression to Reverse Polish Notation.
@ -17,7 +17,7 @@ fn expr_to_rev_pol(expr string) ?[]string {
mut pos := 0 mut pos := 0
for pos<expr.len { for pos<expr.len {
mut end_pos := pos mut end_pos := pos
for end_pos<expr.len && expr[end_pos] in NUMERIC_CHAR { for end_pos<expr.len && expr[end_pos] in numeric_char {
end_pos++ end_pos++
} }
if end_pos>pos { if end_pos>pos {
@ -102,7 +102,7 @@ fn eval_rev_pol(rev_pol []string) ?f64 {
fn is_num_string(str string) bool { fn is_num_string(str string) bool {
for c in str { for c in str {
if c !in NUMERIC_CHAR { if c !in numeric_char {
return false return false
} }
} }

View File

@ -6,9 +6,9 @@
import math import math
const ( const (
SolarMass = 39.47841760435743197 //4.0 * math.Pi * math.Pi solar_mass = 39.47841760435743197 //4.0 * math.Pi * math.Pi
DaysPerYear = 365.24 days_per_year = 365.24
N = 5 c_n = 5
) )
struct Position { struct Position {
@ -33,12 +33,12 @@ pub mut:
} }
fn advance(sys mut System, dt f64) { fn advance(sys mut System, dt f64) {
for i in 0..N - 1 { for i in 0..c_n - 1 {
mut _vx := sys.v[i].x mut _vx := sys.v[i].x
mut _vy := sys.v[i].y mut _vy := sys.v[i].y
mut _vz := sys.v[i].z mut _vz := sys.v[i].z
for j := i + 1; j < N; j++ { for j := i + 1; j < c_n; j++ {
dx := sys.s[i].x - sys.s[j].x dx := sys.s[i].x - sys.s[j].x
dy := sys.s[i].y - sys.s[j].y dy := sys.s[i].y - sys.s[j].y
dz := sys.s[i].z - sys.s[j].z dz := sys.s[i].z - sys.s[j].z
@ -61,7 +61,7 @@ fn advance(sys mut System, dt f64) {
sys.v[i].z = _vz sys.v[i].z = _vz
} }
for i in 0..N { for i in 0..c_n {
sys.s[i].x += dt * sys.v[i].x sys.s[i].x += dt * sys.v[i].x
sys.s[i].y += dt * sys.v[i].y sys.s[i].y += dt * sys.v[i].y
sys.s[i].z += dt * sys.v[i].z sys.s[i].z += dt * sys.v[i].z
@ -73,21 +73,21 @@ fn offsetmomentum(sys mut System) {
mut py := f64(0) mut py := f64(0)
mut pz := f64(0) mut pz := f64(0)
for i in 0..N { for i in 0..c_n {
px += sys.v[i].x * sys.v[i].m px += sys.v[i].x * sys.v[i].m
py += sys.v[i].y * sys.v[i].m py += sys.v[i].y * sys.v[i].m
pz += sys.v[i].z * sys.v[i].m pz += sys.v[i].z * sys.v[i].m
} }
sys.v[0].x = -px / SolarMass sys.v[0].x = -px / solar_mass
sys.v[0].y = -py / SolarMass sys.v[0].y = -py / solar_mass
sys.v[0].z = -pz / SolarMass sys.v[0].z = -pz / solar_mass
} }
fn energy(sys System) f64 { fn energy(sys System) f64 {
mut e := f64(0) mut e := f64(0)
for i in 0..N { for i in 0..c_n {
e += 0.5 * sys.v[i].m * (sys.v[i].x * sys.v[i].x + sys.v[i].y * sys.v[i].y + sys.v[i].z * sys.v[i].z) e += 0.5 * sys.v[i].m * (sys.v[i].x * sys.v[i].x + sys.v[i].y * sys.v[i].y + sys.v[i].z * sys.v[i].z)
for j := i + 1; j < N; j++ { for j := i + 1; j < c_n; j++ {
dx := sys.s[i].x - sys.s[j].x dx := sys.s[i].x - sys.s[j].x
dy := sys.s[i].y - sys.s[j].y dy := sys.s[i].y - sys.s[j].y
dz := sys.s[i].z - sys.s[j].z dz := sys.s[i].z - sys.s[j].z
@ -100,11 +100,11 @@ fn energy(sys System) f64 {
fn arr_momentum() []Momentum { fn arr_momentum() []Momentum {
return [ return [
Momentum {0.0, 0.0, 0.0, SolarMass}, Momentum {0.0, 0.0, 0.0, solar_mass},
Momentum {1.66007664274403694e-03 * DaysPerYear, 7.69901118419740425e-03 * DaysPerYear, -6.90460016972063023e-05 * DaysPerYear, 9.54791938424326609e-04 * SolarMass}, Momentum {1.66007664274403694e-03 * days_per_year, 7.69901118419740425e-03 * days_per_year, -6.90460016972063023e-05 * days_per_year, 9.54791938424326609e-04 * solar_mass},
Momentum {-2.76742510726862411e-03 * DaysPerYear, 4.99852801234917238e-03 * DaysPerYear, 2.30417297573763929e-05 * DaysPerYear, 2.85885980666130812e-04 * SolarMass}, Momentum {-2.76742510726862411e-03 * days_per_year, 4.99852801234917238e-03 * days_per_year, 2.30417297573763929e-05 * days_per_year, 2.85885980666130812e-04 * solar_mass},
Momentum {2.96460137564761618e-03 * DaysPerYear, 2.37847173959480950e-03 * DaysPerYear, -2.96589568540237556e-05 * DaysPerYear, 4.36624404335156298e-05 * SolarMass}, Momentum {2.96460137564761618e-03 * days_per_year, 2.37847173959480950e-03 * days_per_year, -2.96589568540237556e-05 * days_per_year, 4.36624404335156298e-05 * solar_mass},
Momentum {2.68067772490389322e-03 * DaysPerYear, 1.62824170038242295e-03 * DaysPerYear, -9.51592254519715870e-05 * DaysPerYear, 5.15138902046611451e-05 * SolarMass}, Momentum {2.68067772490389322e-03 * days_per_year, 1.62824170038242295e-03 * days_per_year, -9.51592254519715870e-05 * days_per_year, 5.15138902046611451e-05 * solar_mass},
] ]
} }

View File

@ -166,7 +166,7 @@ fn (sp Sphere) intersect (r Ray) f64 {
* The sphere fileds are: Sphere{radius, position, emission, color, material} * The sphere fileds are: Sphere{radius, position, emission, color, material}
******************************************************************************/ ******************************************************************************/
const ( const (
Cen = Vec{50, 40.8, -860} // used by scene 1 cen = Vec{50, 40.8, -860} // used by scene 1
spheres = [ spheres = [
[// scene 0 cornnel box [// scene 0 cornnel box
Sphere{rad: 1e+5, p: Vec{ 1e+5 +1,40.8,81.6} , e: Vec{} , c: Vec{.75,.25,.25} , refl: .diff},//Left Sphere{rad: 1e+5, p: Vec{ 1e+5 +1,40.8,81.6} , e: Vec{} , c: Vec{.75,.25,.25} , refl: .diff},//Left
@ -183,7 +183,7 @@ spheres = [
[// scene 1 sunset [// scene 1 sunset
Sphere{rad: 1600, p: Vec{1.0,0.0,2.0}.mult_s(3000), e: Vec{1.0,.9,.8}.mult_s(1.2e+1*1.56*2) , c: Vec{} , refl: .diff}, // sun Sphere{rad: 1600, p: Vec{1.0,0.0,2.0}.mult_s(3000), e: Vec{1.0,.9,.8}.mult_s(1.2e+1*1.56*2) , c: Vec{} , refl: .diff}, // sun
Sphere{rad: 1560, p: Vec{1,0,2}.mult_s(3500) , e: Vec{1.0,.5,.05}.mult_s(4.8e+1*1.56*2) , c: Vec{} , refl: .diff}, // horizon sun2 Sphere{rad: 1560, p: Vec{1,0,2}.mult_s(3500) , e: Vec{1.0,.5,.05}.mult_s(4.8e+1*1.56*2) , c: Vec{} , refl: .diff}, // horizon sun2
Sphere{rad: 10000, p: Cen+Vec{0,0,-200}, e: Vec{0.00063842, 0.02001478, 0.28923243}.mult_s(6e-2*8), c: Vec{.7,.7,1}.mult_s(.25), refl: .diff}, // sky Sphere{rad: 10000, p: cen+Vec{0,0,-200}, e: Vec{0.00063842, 0.02001478, 0.28923243}.mult_s(6e-2*8), c: Vec{.7,.7,1}.mult_s(.25), refl: .diff}, // sky
Sphere{rad: 100000, p: Vec{50, -100000, 0} , e: Vec{} , c: Vec{.3,.3,.3} , refl: .diff}, // grnd Sphere{rad: 100000, p: Vec{50, -100000, 0} , e: Vec{} , c: Vec{.3,.3,.3} , refl: .diff}, // grnd
Sphere{rad: 110000, p: Vec{50, -110048.5, 0} , e: Vec{.9,.5,.05}.mult_s(4) , c: Vec{}, refl: .diff},// horizon brightener Sphere{rad: 110000, p: Vec{50, -110048.5, 0} , e: Vec{.9,.5,.05}.mult_s(4) , c: Vec{}, refl: .diff},// horizon brightener

View File

@ -2,16 +2,16 @@ import time
import rand import rand
const ( const (
LEN = 1000 // how many random numbers to generate gen_len = 1000 // how many random numbers to generate
MAX = 10000 // max of the generated numbers gen_max = 10000 // max of the generated numbers
) )
fn main() { fn main() {
rand.seed(time.now().unix) rand.seed(time.now().unix)
rand.next(MAX) // skip the first rand.next(gen_max) // skip the first
mut arr := []int{} mut arr := []int{}
for _ in 0..LEN { for _ in 0..gen_len {
arr << rand.next(MAX) arr << rand.next(gen_max)
} }
println('length of random array is $arr.len') println('length of random array is $arr.len')
println('before quick sort whether array is sorted: ${is_sorted(arr)}') println('before quick sort whether array is sorted: ${is_sorted(arr)}')

View File

@ -22,26 +22,26 @@ const (
) )
const ( const (
BlockSize = 20 // pixels block_size = 20 // pixels
FieldHeight = 20 // # of blocks field_height = 20 // # of blocks
FieldWidth = 10 field_width = 10
tetro_size = 4 tetro_size = 4
WinWidth = BlockSize * FieldWidth win_width = block_size * field_width
WinHeight = BlockSize * FieldHeight win_height = block_size * field_height
TimerPeriod = 250 // ms timer_period = 250 // ms
TextSize = 12 text_size = 12
LimitThickness = 3 limit_thickness = 3
) )
const ( const (
text_cfg = gx.TextCfg{ text_cfg = gx.TextCfg{
align:gx.align_left align:gx.align_left
size:TextSize size:text_size
color:gx.rgb(0, 0, 0) color:gx.rgb(0, 0, 0)
} }
over_cfg = gx.TextCfg{ over_cfg = gx.TextCfg{
align:gx.align_left align:gx.align_left
size:TextSize size:text_size
color:gx.White color:gx.White
} }
) )
@ -84,7 +84,7 @@ const (
[1111, 9, 1111, 9], [1111, 9, 1111, 9],
] ]
// Each tetro has its unique color // Each tetro has its unique color
Colors = [ colors = [
gx.rgb(0, 0, 0), // unused ? gx.rgb(0, 0, 0), // unused ?
gx.rgb(255, 242, 0), // yellow quad gx.rgb(255, 242, 0), // yellow quad
gx.rgb(174, 0, 255), // purple triple gx.rgb(174, 0, 255), // purple triple
@ -96,8 +96,8 @@ const (
gx.rgb(0, 170, 170), // unused ? gx.rgb(0, 170, 170), // unused ?
] ]
BackgroundColor = gx.White background_color = gx.White
UIColor = gx.Red ui_color = gx.red
) )
// TODO: type Tetro [tetro_size]struct{ x, y int } // TODO: type Tetro [tetro_size]struct{ x, y int }
@ -145,8 +145,8 @@ fn main() {
glfw.init_glfw() glfw.init_glfw()
gconfig := gg.Cfg { gconfig := gg.Cfg {
width: WinWidth width: win_width
height: WinHeight height: win_height
use_ortho: true // This is needed for 2D drawing use_ortho: true // This is needed for 2D drawing
create_window: true create_window: true
window_title: 'V Tetris' window_title: 'V Tetris'
@ -154,8 +154,8 @@ fn main() {
} }
fconfig := gg.Cfg{ fconfig := gg.Cfg{
width: WinWidth width: win_width
height: WinHeight height: win_height
use_ortho: true use_ortho: true
font_path: '../assets/fonts/RobotoMono-Regular.ttf' font_path: '../assets/fonts/RobotoMono-Regular.ttf'
font_size: 18 font_size: 18
@ -170,10 +170,10 @@ fn main() {
game.init_game() game.init_game()
game.gg.window.onkeydown(key_down) game.gg.window.onkeydown(key_down)
go game.run() // Run the game loop in a new thread go game.run() // Run the game loop in a new thread
gg.clear(BackgroundColor) gg.clear(background_color)
game.font_loaded = game.ft != 0 game.font_loaded = game.ft != 0
for { for {
gg.clear(BackgroundColor) gg.clear(background_color)
game.draw_scene() game.draw_scene()
game.gg.render() game.gg.render()
if game.gg.window.should_close() { if game.gg.window.should_close() {
@ -189,15 +189,15 @@ fn (mut g Game) init_game() {
g.generate_tetro() g.generate_tetro()
g.field = [] // TODO: g.field = [][]int g.field = [] // TODO: g.field = [][]int
// Generate the field, fill it with 0's, add -1's on each edge // Generate the field, fill it with 0's, add -1's on each edge
for _ in 0..FieldHeight + 2 { for _ in 0..field_height + 2 {
mut row := [0].repeat(FieldWidth + 2) mut row := [0].repeat(field_width + 2)
row[0] = - 1 row[0] = - 1
row[FieldWidth + 1] = - 1 row[field_width + 1] = - 1
g.field << row g.field << row
} }
mut first_row := g.field[0] mut first_row := g.field[0]
mut last_row := g.field[FieldHeight + 1] mut last_row := g.field[field_height + 1]
for j in 0..FieldWidth + 2 { for j in 0..field_width + 2 {
first_row[j] = - 1 first_row[j] = - 1
last_row[j] = - 1 last_row[j] = - 1
} }
@ -222,7 +222,7 @@ fn (mut g Game) run() {
g.delete_completed_lines() g.delete_completed_lines()
} }
glfw.post_empty_event() // force window redraw glfw.post_empty_event() // force window redraw
time.sleep_ms(TimerPeriod) time.sleep_ms(timer_period)
} }
} }
@ -267,13 +267,13 @@ fn (mut g Game) move_right(dx int) bool {
} }
fn (mut g Game) delete_completed_lines() { fn (mut g Game) delete_completed_lines() {
for y := FieldHeight; y >= 1; y-- { for y := field_height; y >= 1; y-- {
g.delete_completed_line(y) g.delete_completed_line(y)
} }
} }
fn (mut g Game) delete_completed_line(y int) { fn (mut g Game) delete_completed_line(y int) {
for x := 1; x <= FieldWidth; x++ { for x := 1; x <= field_width; x++ {
f := g.field[y] f := g.field[y]
if f[x] == 0 { if f[x] == 0 {
return return
@ -282,7 +282,7 @@ fn (mut g Game) delete_completed_line(y int) {
g.score += 10 g.score += 10
// Move everything down by 1 position // Move everything down by 1 position
for yy := y - 1; yy >= 1; yy-- { for yy := y - 1; yy >= 1; yy-- {
for x := 1; x <= FieldWidth; x++ { for x := 1; x <= field_width; x++ {
mut a := g.field[yy + 1] mut a := g.field[yy + 1]
b := g.field[yy] b := g.field[yy]
a[x] = b[x] a[x] = b[x]
@ -293,7 +293,7 @@ fn (mut g Game) delete_completed_line(y int) {
// Place a new tetro on top // Place a new tetro on top
fn (mut g Game) generate_tetro() { fn (mut g Game) generate_tetro() {
g.pos_y = 0 g.pos_y = 0
g.pos_x = FieldWidth / 2 - tetro_size / 2 g.pos_x = field_width / 2 - tetro_size / 2
g.tetro_idx = rand.next(b_tetros.len) g.tetro_idx = rand.next(b_tetros.len)
g.rotation_idx = 0 g.rotation_idx = 0
g.get_tetro() g.get_tetro()
@ -326,14 +326,14 @@ fn (g &Game) draw_tetro() {
} }
fn (g &Game) draw_block(i, j, color_idx int) { fn (g &Game) draw_block(i, j, color_idx int) {
color := if g.state == .gameover { gx.Gray } else { Colors[color_idx] } color := if g.state == .gameover { gx.gray } else { colors[color_idx] }
g.gg.draw_rect((j - 1) * BlockSize, (i - 1) * BlockSize, g.gg.draw_rect((j - 1) * block_size, (i - 1) * block_size,
BlockSize - 1, BlockSize - 1, color) block_size - 1, block_size - 1, color)
} }
fn (g &Game) draw_field() { fn (g &Game) draw_field() {
for i := 1; i < FieldHeight + 1; i++ { for i := 1; i < field_height + 1; i++ {
for j := 1; j < FieldWidth + 1; j++ { for j := 1; j < field_width + 1; j++ {
f := g.field[i] f := g.field[i]
if f[j] > 0 { if f[j] > 0 {
g.draw_block(i, j, f[j]) g.draw_block(i, j, f[j])
@ -346,18 +346,18 @@ fn (mut g Game) draw_ui() {
if g.font_loaded { if g.font_loaded {
g.ft.draw_text(1, 3, g.score.str(), text_cfg) g.ft.draw_text(1, 3, g.score.str(), text_cfg)
if g.state == .gameover { if g.state == .gameover {
g.gg.draw_rect(0, WinHeight / 2 - TextSize, WinWidth, g.gg.draw_rect(0, win_height / 2 - text_size, win_width,
5 * TextSize, UIColor) 5 * text_size, ui_color)
g.ft.draw_text(1, WinHeight / 2 + 0 * TextSize, 'Game Over', over_cfg) g.ft.draw_text(1, win_height / 2 + 0 * text_size, 'Game Over', over_cfg)
g.ft.draw_text(1, WinHeight / 2 + 2 * TextSize, 'Space to restart', over_cfg) g.ft.draw_text(1, win_height / 2 + 2 * text_size, 'Space to restart', over_cfg)
} else if g.state == .paused { } else if g.state == .paused {
g.gg.draw_rect(0, WinHeight / 2 - TextSize, WinWidth, g.gg.draw_rect(0, win_height / 2 - text_size, win_width,
5 * TextSize, UIColor) 5 * text_size, ui_color)
g.ft.draw_text(1, WinHeight / 2 + 0 * TextSize, 'Game Paused', text_cfg) g.ft.draw_text(1, win_height / 2 + 0 * text_size, 'Game Paused', text_cfg)
g.ft.draw_text(1, WinHeight / 2 + 2 * TextSize, 'SPACE to resume', text_cfg) g.ft.draw_text(1, win_height / 2 + 2 * text_size, 'SPACE to resume', text_cfg)
} }
} }
//g.gg.draw_rect(0, BlockSize, WinWidth, LimitThickness, UIColor) //g.gg.draw_rect(0, block_size, win_width, limit_thickness, ui_color)
} }
fn (mut g Game) draw_scene() { fn (mut g Game) draw_scene() {

View File

@ -2,13 +2,16 @@ import rand
import time import time
import os import os
const (HelpText = ' Usage:\t./VCasino\n const (
Description:\n VCasino is a little game only made to learn V.\n') help_text = ' Usage:\t./VCasino\n
const (GDesc = ' The object of Roulette is to pick the number where the spinning ball will land on the wheel. Description:\n VCasino is a little game only made to learn V.\n'
g_desc = ' The object of Roulette is to pick the number where the spinning ball will land on the wheel.
If your number is the good one, you\'ll get your bet x3. If your number is the good one, you\'ll get your bet x3.
If your number is the same color as the ball one, you\'ll get your bet /2. If your number is the same color as the ball one, you\'ll get your bet /2.
Otherwise, you will lose your bet.\n') Otherwise, you will lose your bet.\n'
const (Odd = 'Red' Even = 'Black') odd = 'red'
even = 'black'
)
struct Options { struct Options {
long_opt string long_opt string
@ -16,7 +19,7 @@ struct Options {
} }
fn display_help() { fn display_help() {
println(HelpText + GDesc) println(help_text + g_desc)
} }
fn option_parser() bool { fn option_parser() bool {
@ -42,7 +45,7 @@ fn str_is_nbr(s string) bool {
fn get_bet_nbr() int { fn get_bet_nbr() int {
mut bet_nbr := -1 mut bet_nbr := -1
for bet_nbr < 0 || bet_nbr > 49 { for bet_nbr < 0 || bet_nbr > 49 {
println('Reminder: Odd numbers are red and even are black.') println('Reminder: odd numbers are red and even are black.')
println('Type the number you want to bet on (between 0 and 49):') println('Type the number you want to bet on (between 0 and 49):')
line := os.get_line().trim_space() line := os.get_line().trim_space()
if line.len < 1 { if line.len < 1 {
@ -93,9 +96,9 @@ fn run_wheel(bet_nbr int, _bet int) int {
winning_nbr := rand.next(50) winning_nbr := rand.next(50)
print('Roulette Wheel spinning... and stops on the number $winning_nbr which is a ') print('Roulette Wheel spinning... and stops on the number $winning_nbr which is a ')
if winning_nbr % 2 == 1 { if winning_nbr % 2 == 1 {
println(Odd) println(odd)
} else { } else {
println(Even) println(even)
} }
if winning_nbr == bet_nbr { if winning_nbr == bet_nbr {
bet *= 3 bet *= 3
@ -129,7 +132,7 @@ fn game_loop() {
mut can_play := true mut can_play := true
mut money := 1000 mut money := 1000
println(GDesc) println(g_desc)
println('You start the game with $money V.\n') println('You start the game with $money V.\n')
for can_play { for can_play {
bet_nbr := get_bet_nbr() bet_nbr := get_bet_nbr()

View File

@ -46,10 +46,10 @@ SPENT 462 ms in code_2
const ( const (
BOK = term.ok_message('OK ') b_ok = term.ok_message('OK ')
BFAIL = term.fail_message('FAIL') b_fail = term.fail_message('FAIL')
BSKIP = term.warn_message('SKIP') b_skip = term.warn_message('SKIP')
BSPENT = term.ok_message('SPENT') b_spent = term.ok_message('SPENT')
) )
pub struct Benchmark { pub struct Benchmark {
@ -148,7 +148,7 @@ pub fn start() Benchmark {
pub fn (mut b Benchmark) measure(label string) i64 { pub fn (mut b Benchmark) measure(label string) i64 {
b.ok() b.ok()
res := b.step_timer.elapsed().microseconds() res := b.step_timer.elapsed().microseconds()
println(b.step_message_with_label(BSPENT, 'in $label')) println(b.step_message_with_label(b_spent, 'in $label'))
b.step() b.step()
return res return res
} }
@ -184,15 +184,15 @@ pub fn (b &Benchmark) step_message(msg string) string {
} }
pub fn (b &Benchmark) step_message_ok(msg string) string { pub fn (b &Benchmark) step_message_ok(msg string) string {
return b.step_message_with_label(BOK, msg) return b.step_message_with_label(b_ok, msg)
} }
pub fn (b &Benchmark) step_message_fail(msg string) string { pub fn (b &Benchmark) step_message_fail(msg string) string {
return b.step_message_with_label(BFAIL, msg) return b.step_message_with_label(b_fail, msg)
} }
pub fn (b &Benchmark) step_message_skip(msg string) string { pub fn (b &Benchmark) step_message_skip(msg string) string {
return b.step_message_with_label(BSKIP, msg) return b.step_message_with_label(b_skip, msg)
} }
pub fn (b &Benchmark) total_message(msg string) string { pub fn (b &Benchmark) total_message(msg string) string {

View File

@ -22,7 +22,7 @@ mut:
// helper functions // helper functions
const ( const (
SLOT_SIZE = 32 slot_size = 32
) )
// public functions // public functions
@ -67,7 +67,7 @@ pub fn (input BitField) str() string {
pub fn new(size int) BitField { pub fn new(size int) BitField {
output := BitField{ output := BitField{
size: size size: size
//field: *u32(calloc(bitnslots(size) * SLOT_SIZE / 8)) //field: *u32(calloc(bitnslots(size) * slot_size / 8))
field: [u32(0)].repeat(bitnslots(size)) field: [u32(0)].repeat(bitnslots(size))
} }
return output return output
@ -84,7 +84,7 @@ pub fn (instance BitField) get_bit(bitnr int) int {
if bitnr >= instance.size { if bitnr >= instance.size {
return 0 return 0
} }
return (instance.field[bitslot(bitnr)] >> (bitnr % SLOT_SIZE)) & u32(1) return (instance.field[bitslot(bitnr)] >> (bitnr % slot_size)) & u32(1)
} }
// set_bit sets bit number 'bit_nr' to 1 (count from 0). // set_bit sets bit number 'bit_nr' to 1 (count from 0).
@ -191,8 +191,8 @@ pub fn join(input1 BitField, input2 BitField) BitField {
} }
// find offset bit and offset slot // find offset bit and offset slot
offset_bit := input1.size % SLOT_SIZE offset_bit := input1.size % slot_size
offset_slot := input1.size / SLOT_SIZE offset_slot := input1.size / slot_size
for i in 0..bitnslots(input2.size) { for i in 0..bitnslots(input2.size) {
output.field[i + offset_slot] |= output.field[i + offset_slot] |=
@ -212,15 +212,15 @@ pub fn join(input1 BitField, input2 BitField) BitField {
* input. * input.
* If offset_bit is zero, no additional copies needed. * If offset_bit is zero, no additional copies needed.
*/ */
if (output_size - 1) % SLOT_SIZE < (input2.size - 1) % SLOT_SIZE { if (output_size - 1) % slot_size < (input2.size - 1) % slot_size {
for i in 0..bitnslots(input2.size) { for i in 0..bitnslots(input2.size) {
output.field[i + offset_slot + 1] |= output.field[i + offset_slot + 1] |=
u32(input2.field[i] >> u32(SLOT_SIZE - offset_bit)) u32(input2.field[i] >> u32(slot_size - offset_bit))
} }
} else if (output_size - 1) % SLOT_SIZE > (input2.size - 1) % SLOT_SIZE { } else if (output_size - 1) % slot_size > (input2.size - 1) % slot_size {
for i in 0..bitnslots(input2.size) - 1 { for i in 0..bitnslots(input2.size) - 1 {
output.field[i + offset_slot + 1] |= output.field[i + offset_slot + 1] |=
u32(input2.field[i] >> u32(SLOT_SIZE - offset_bit)) u32(input2.field[i] >> u32(slot_size - offset_bit))
} }
} }
return output return output
@ -255,10 +255,10 @@ pub fn (instance BitField) cmp(input BitField) bool {
pub fn (instance BitField) pop_count() int { pub fn (instance BitField) pop_count() int {
size := instance.size size := instance.size
bitnslots := bitnslots(size) bitnslots := bitnslots(size)
tail := size % SLOT_SIZE tail := size % slot_size
mut count := 0 mut count := 0
for i in 0..bitnslots - 1 { for i in 0..bitnslots - 1 {
for j in 0..SLOT_SIZE { for j in 0..slot_size {
if u32(instance.field[i] >> u32(j)) & u32(1) == u32(1) { if u32(instance.field[i] >> u32(j)) & u32(1) == u32(1) {
count++ count++
} }
@ -314,10 +314,10 @@ pub fn (input BitField) slice(_start int, _end int) BitField {
} }
mut output := new(end - start) mut output := new(end - start)
start_offset := start % SLOT_SIZE start_offset := start % slot_size
end_offset := (end - 1) % SLOT_SIZE end_offset := (end - 1) % slot_size
start_slot := start / SLOT_SIZE start_slot := start / slot_size
end_slot := (end - 1) / SLOT_SIZE end_slot := (end - 1) / slot_size
output_slots := bitnslots(end - start) output_slots := bitnslots(end - start)
if output_slots > 1 { if output_slots > 1 {
@ -327,7 +327,7 @@ pub fn (input BitField) slice(_start int, _end int) BitField {
u32(input.field[start_slot + i] >> u32(start_offset)) u32(input.field[start_slot + i] >> u32(start_offset))
output.field[i] = output.field[i] | output.field[i] = output.field[i] |
u32(input.field[start_slot + i + 1] << u32(input.field[start_slot + i + 1] <<
u32(SLOT_SIZE - start_offset)) u32(slot_size - start_offset))
} }
} }
else { else {
@ -339,30 +339,30 @@ pub fn (input BitField) slice(_start int, _end int) BitField {
} }
if start_offset > end_offset { if start_offset > end_offset {
output.field[(end - start - 1) / SLOT_SIZE] = output.field[(end - start - 1) / slot_size] =
u32(input.field[end_slot - 1] >> u32(start_offset)) u32(input.field[end_slot - 1] >> u32(start_offset))
mut mask := u32((1 << (end_offset + 1)) - 1) mut mask := u32((1 << (end_offset + 1)) - 1)
mask = input.field[end_slot] & mask mask = input.field[end_slot] & mask
mask = u32(mask << u32(SLOT_SIZE - start_offset)) mask = u32(mask << u32(slot_size - start_offset))
output.field[(end - start - 1) / SLOT_SIZE] |= mask output.field[(end - start - 1) / slot_size] |= mask
} }
else if start_offset == 0 { else if start_offset == 0 {
mut mask := u32(0) mut mask := u32(0)
if end_offset == SLOT_SIZE - 1 { if end_offset == slot_size - 1 {
mask = u32(-1) mask = u32(-1)
} }
else { else {
mask = u32(u32(1) << u32(end_offset + 1)) mask = u32(u32(1) << u32(end_offset + 1))
mask = mask - u32(1) mask = mask - u32(1)
} }
output.field[(end - start - 1) / SLOT_SIZE] = output.field[(end - start - 1) / slot_size] =
(input.field[end_slot] & mask) (input.field[end_slot] & mask)
} }
else { else {
mut mask := u32(((1 << (end_offset - start_offset + 1)) - 1) << start_offset) mut mask := u32(((1 << (end_offset - start_offset + 1)) - 1) << start_offset)
mask = input.field[end_slot] & mask mask = input.field[end_slot] & mask
mask = u32(mask >> u32(start_offset)) mask = u32(mask >> u32(start_offset))
output.field[(end - start - 1) / SLOT_SIZE] |= mask output.field[(end - start - 1) / slot_size] |= mask
} }
return output return output
} }
@ -374,13 +374,13 @@ pub fn (instance BitField) reverse() BitField {
bitnslots := bitnslots(size) bitnslots := bitnslots(size)
mut output := new(size) mut output := new(size)
for i:= 0; i < (bitnslots - 1); i++ { for i:= 0; i < (bitnslots - 1); i++ {
for j in 0..SLOT_SIZE { for j in 0..slot_size {
if u32(instance.field[i] >> u32(j)) & u32(1) == u32(1) { if u32(instance.field[i] >> u32(j)) & u32(1) == u32(1) {
output.set_bit(size - i * SLOT_SIZE - j - 1) output.set_bit(size - i * slot_size - j - 1)
} }
} }
} }
bits_in_last_input_slot := (size - 1) % SLOT_SIZE + 1 bits_in_last_input_slot := (size - 1) % slot_size + 1
for j in 0..bits_in_last_input_slot { for j in 0..bits_in_last_input_slot {
if u32(instance.field[bitnslots - 1] >> u32(j)) & u32(1) == u32(1) { if u32(instance.field[bitnslots - 1] >> u32(j)) & u32(1) == u32(1) {
output.set_bit(bits_in_last_input_slot - j - 1) output.set_bit(bits_in_last_input_slot - j - 1)
@ -400,7 +400,7 @@ pub fn (mut instance BitField) resize(new_size int) {
} }
instance.field = field.clone() instance.field = field.clone()
instance.size = new_size instance.size = new_size
if new_size < old_size && new_size % SLOT_SIZE != 0 { if new_size < old_size && new_size % slot_size != 0 {
instance.clear_tail() instance.clear_tail()
} }
} }
@ -434,7 +434,7 @@ pub fn (instance BitField) rotate(offset int) BitField {
// Internal functions // Internal functions
fn (mut instance BitField) clear_tail() { fn (mut instance BitField) clear_tail() {
tail := instance.size % SLOT_SIZE tail := instance.size % slot_size
if tail != 0 { if tail != 0 {
// create a mask for the tail // create a mask for the tail
mask := u32((1 << tail) - 1) mask := u32((1 << tail) - 1)
@ -444,11 +444,11 @@ fn (mut instance BitField) clear_tail() {
} }
fn bitmask(bitnr int) u32 { fn bitmask(bitnr int) u32 {
return u32(u32(1) << u32(bitnr % SLOT_SIZE)) return u32(u32(1) << u32(bitnr % slot_size))
} }
fn bitslot(size int) int { fn bitslot(size int) int {
return size / SLOT_SIZE return size / slot_size
} }
fn min(input1 int, input2 int) int { fn min(input1 int, input2 int) int {
@ -461,5 +461,5 @@ fn min(input1 int, input2 int) int {
} }
fn bitnslots(length int) int { fn bitnslots(length int) int {
return (length - 1) / SLOT_SIZE + 1 return (length - 1) / slot_size + 1
} }

View File

@ -1,8 +1,3 @@
const (
q = [1, 2, 3]
A = 8
)
fn test_pointer() { fn test_pointer() {
mut arr := []&int{} mut arr := []&int{}
a := 1 a := 1
@ -295,11 +290,11 @@ fn test_reverse() {
} }
const ( const (
N = 5 c_n = 5
) )
struct Foooj { struct Foooj {
a [5]int // N a [5]int // c_n
} }
fn test_fixed() { fn test_fixed() {
@ -312,8 +307,8 @@ fn test_fixed() {
assert nums[3] == 0 assert nums[3] == 0
nums[1] = 7 nums[1] = 7
assert nums[1] == 7 assert nums[1] == 7
nums2 := [5]int // N nums2 := [5]int // c_n
assert nums2[N - 1] == 0 assert nums2[c_n - 1] == 0
} }
fn modify(numbers mut []int) { fn modify(numbers mut []int) {

View File

@ -50,18 +50,18 @@ fn C.SymGetLineFromAddr64(h_process voidptr, address u64, p_displacement voidptr
// Ref - https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-symsetoptions // Ref - https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-symsetoptions
const ( const (
SYMOPT_UNDNAME = 0x00000002 symopt_undname = 0x00000002
SYMOPT_DEFERRED_LOADS = 0x00000004 symopt_deferred_loads = 0x00000004
SYMOPT_NO_CPP = 0x00000008 symopt_no_cpp = 0x00000008
SYMOPT_LOAD_LINES = 0x00000010 symopt_load_lines = 0x00000010
SYMOPT_INCLUDE_32BIT_MODULES = 0x00002000 symopt_include_32bit_modules = 0x00002000
SYMOPT_ALLOW_ZERO_ADDRESS = 0x01000000 symopt_allow_zero_address = 0x01000000
SYMOPT_DEBUG = 0x80000000 symopt_debug = 0x80000000
) )
fn builtin_init() { fn builtin_init() {
if is_atty(1) > 0 { if is_atty(1) > 0 {
C.SetConsoleMode(C.GetStdHandle(C.STD_OUTPUT_HANDLE), C.ENABLE_PROCESSED_OUTPUT | 0x0004) // ENABLE_VIRTUAL_TERMINAL_PROCESSING C.SetConsoleMode(C.GetStdHandle(C.STD_OUTPUT_HANDLE), C.ENABLE_PROCESSED_OUTPUT | 0x0004) // enable_virtual_terminal_processing
C.setbuf(C.stdout, 0) C.setbuf(C.stdout, 0)
} }
} }
@ -92,7 +92,7 @@ $if msvc {
handle := C.GetCurrentProcess() handle := C.GetCurrentProcess()
defer { C.SymCleanup(handle) } defer { C.SymCleanup(handle) }
C.SymSetOptions(SYMOPT_DEBUG | SYMOPT_LOAD_LINES | SYMOPT_UNDNAME) C.SymSetOptions(symopt_debug | symopt_load_lines | symopt_undname)
syminitok := C.SymInitialize( handle, 0, 1) syminitok := C.SymInitialize( handle, 0, 1)
if syminitok != 1 { if syminitok != 1 {

View File

@ -109,15 +109,15 @@ pub fn (_rune string) utf32_code() int {
} }
const ( const (
CP_UTF8 = 65001 cp_utf8 = 65001
) )
pub fn (_str string) to_wide() &u16 { pub fn (_str string) to_wide() &u16 {
$if windows { $if windows {
num_chars := (C.MultiByteToWideChar(CP_UTF8, 0, _str.str, _str.len, 0, 0)) num_chars := (C.MultiByteToWideChar(cp_utf8, 0, _str.str, _str.len, 0, 0))
mut wstr := &u16(malloc((num_chars + 1) * 2)) // sizeof(wchar_t) mut wstr := &u16(malloc((num_chars + 1) * 2)) // sizeof(wchar_t)
if wstr != 0 { if wstr != 0 {
C.MultiByteToWideChar(CP_UTF8, 0, _str.str, _str.len, wstr, num_chars) C.MultiByteToWideChar(cp_utf8, 0, _str.str, _str.len, wstr, num_chars)
C.memset(&byte(wstr) + num_chars * 2, 0, 2) C.memset(&byte(wstr) + num_chars * 2, 0, 2)
} }
return wstr return wstr
@ -137,10 +137,10 @@ pub fn string_from_wide(_wstr &u16) string {
pub fn string_from_wide2(_wstr &u16, len int) string { pub fn string_from_wide2(_wstr &u16, len int) string {
$if windows { $if windows {
num_chars := C.WideCharToMultiByte(CP_UTF8, 0, _wstr, len, 0, 0, 0, 0) num_chars := C.WideCharToMultiByte(cp_utf8, 0, _wstr, len, 0, 0, 0, 0)
mut str_to := malloc(num_chars + 1) mut str_to := malloc(num_chars + 1)
if str_to != 0 { if str_to != 0 {
C.WideCharToMultiByte(CP_UTF8, 0, _wstr, len, str_to, num_chars, 0, 0) C.WideCharToMultiByte(cp_utf8, 0, _wstr, len, str_to, num_chars, 0, 0)
C.memset(str_to + num_chars, 0, 1) C.memset(str_to + num_chars, 0, 1)
} }
return tos2(str_to) return tos2(str_to)
@ -255,4 +255,3 @@ pub fn utf8_getchar() int {
return uc return uc
} }
} }

View File

@ -4,9 +4,9 @@ import term
import strings import strings
const ( const (
BASE_INDENT = 2 c_base_indent = 2
ABBREV_INDENT = 5 c_abbrev_indent = 5
DESCRIPTION_INDENT = 20 c_description_indent = 20
) )
fn help_flag() Flag { fn help_flag() Flag {
@ -45,10 +45,10 @@ fn help_func(help_cmd Command) {
for flag in cmd.flags { for flag in cmd.flags {
mut flag_name := '' mut flag_name := ''
if flag.abbrev != '' { if flag.abbrev != '' {
abbrev_indent := ' '.repeat(max(ABBREV_INDENT-(flag.abbrev.len+1), 1)) abbrev_indent := ' '.repeat(max(c_abbrev_indent-(flag.abbrev.len+1), 1))
flag_name = '-${flag.abbrev}${abbrev_indent}--${flag.name}' flag_name = '-${flag.abbrev}${abbrev_indent}--${flag.name}'
} else { } else {
abbrev_indent := ' '.repeat(max(ABBREV_INDENT-(flag.abbrev.len), 1)) abbrev_indent := ' '.repeat(max(c_abbrev_indent-(flag.abbrev.len), 1))
flag_name = '${abbrev_indent}--${flag.name}' flag_name = '${abbrev_indent}--${flag.name}'
} }
mut required := '' mut required := ''
@ -56,8 +56,8 @@ fn help_func(help_cmd Command) {
required = ' (required)' required = ' (required)'
} }
base_indent := ' '.repeat(BASE_INDENT) base_indent := ' '.repeat(c_base_indent)
description_indent := ' '.repeat(max(DESCRIPTION_INDENT-flag_name.len, 1)) description_indent := ' '.repeat(max(c_description_indent-flag_name.len, 1))
help += '${base_indent}${flag_name}${description_indent}' + help += '${base_indent}${flag_name}${description_indent}' +
pretty_description(flag.description + required) + '\n' pretty_description(flag.description + required) + '\n'
} }
@ -66,8 +66,8 @@ fn help_func(help_cmd Command) {
if cmd.commands.len > 0 { if cmd.commands.len > 0 {
help += 'Commands:\n' help += 'Commands:\n'
for command in cmd.commands { for command in cmd.commands {
base_indent := ' '.repeat(BASE_INDENT) base_indent := ' '.repeat(c_base_indent)
description_indent := ' '.repeat(max(DESCRIPTION_INDENT-command.name.len, 1)) description_indent := ' '.repeat(max(c_description_indent-command.name.len, 1))
help += '${base_indent}${command.name}${description_indent}' + help += '${base_indent}${command.name}${description_indent}' +
pretty_description(command.description) + '\n' pretty_description(command.description) + '\n'
@ -83,11 +83,11 @@ fn help_func(help_cmd Command) {
fn pretty_description(s string) string { fn pretty_description(s string) string {
width, _ := term.get_terminal_size() width, _ := term.get_terminal_size()
// Don't prettify if the terminal is that small, it won't be pretty anyway. // Don't prettify if the terminal is that small, it won't be pretty anyway.
if s.len + DESCRIPTION_INDENT < width || DESCRIPTION_INDENT > width { if s.len + c_description_indent < width || c_description_indent > width {
return s return s
} }
indent := ' '.repeat(DESCRIPTION_INDENT + 1) indent := ' '.repeat(c_description_indent + 1)
chars_per_line := width - DESCRIPTION_INDENT chars_per_line := width - c_description_indent
// Give us enough room, better a little bigger than smaller // Give us enough room, better a little bigger than smaller
mut acc := strings.new_builder(((s.len / chars_per_line) + 1) * (width + 1)) mut acc := strings.new_builder(((s.len / chars_per_line) + 1) * (width + 1))

View File

@ -9,15 +9,15 @@ module rand
#include <bcrypt.h> #include <bcrypt.h>
const ( const (
STATUS_SUCCESS = 0x00000000 status_success = 0x00000000
BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002 bcrypt_use_system_preferred_rng = 0x00000002
) )
pub fn read(bytes_needed int) ?[]byte { pub fn read(bytes_needed int) ?[]byte {
mut buffer := malloc(bytes_needed) mut buffer := malloc(bytes_needed)
// use BCRYPT_USE_SYSTEM_PREFERRED_RNG because we passed null as algo // use bcrypt_use_system_preferred_rng because we passed null as algo
status := C.BCryptGenRandom(0, buffer, bytes_needed, BCRYPT_USE_SYSTEM_PREFERRED_RNG) status := C.BCryptGenRandom(0, buffer, bytes_needed, bcrypt_use_system_preferred_rng)
if status != STATUS_SUCCESS { if status != status_success {
return read_error return read_error
} }
return c_array_to_bytes_tmp(bytes_needed, buffer) return c_array_to_bytes_tmp(bytes_needed, buffer)

View File

@ -3,9 +3,9 @@ module dl
#include <dlfcn.h> #include <dlfcn.h>
pub const ( pub const (
RTLD_NOW = C.RTLD_NOW rtld_now = C.RTLD_NOW
RTLD_LAZY = C.RTLD_LAZY rtld_lazy = C.RTLD_LAZY
DL_EXT = '.so' dl_ext = '.so'
) )
fn C.dlopen(filename charptr, flags int) voidptr fn C.dlopen(filename charptr, flags int) voidptr

View File

@ -18,29 +18,29 @@ fn test_dl() {
fn run_test_invalid_lib_linux() { fn run_test_invalid_lib_linux() {
// ensure a not-existing dl won't be loaded // ensure a not-existing dl won't be loaded
h := dl.open('not-existing-dynamic-link-library', dl.RTLD_NOW) h := dl.open('not-existing-dynamic-link-library', dl.rtld_now)
assert h == 0 assert h == 0
} }
fn run_test_invalid_lib_windows() { fn run_test_invalid_lib_windows() {
// ensure a not-existing dl won't be loaded // ensure a not-existing dl won't be loaded
h := dl.open('not-existing-dynamic-link-library', dl.RTLD_NOW) h := dl.open('not-existing-dynamic-link-library', dl.rtld_now)
assert h == 0 assert h == 0
} }
fn run_test_valid_lib_windows() { fn run_test_valid_lib_windows() {
h := dl.open('shell32', dl.RTLD_NOW) h := dl.open('shell32', dl.rtld_now)
assert h != 0 assert h != 0
} }
fn run_test_invalid_sym_windows() { fn run_test_invalid_sym_windows() {
h := dl.open('shell32', dl.RTLD_NOW) h := dl.open('shell32', dl.rtld_now)
proc := dl.sym(h, 'CommandLineToArgvW2') proc := dl.sym(h, 'CommandLineToArgvW2')
assert proc == 0 assert proc == 0
} }
fn run_test_valid_sym_windows() { fn run_test_valid_sym_windows() {
h := dl.open('shell32', dl.RTLD_NOW) h := dl.open('shell32', dl.rtld_now)
proc := dl.sym(h, 'CommandLineToArgvW') proc := dl.sym(h, 'CommandLineToArgvW')
assert proc != 0 assert proc != 0
} }

View File

@ -1,9 +1,9 @@
module dl module dl
pub const ( pub const (
RTLD_NOW = 0 rtld_now = 0
RTLD_LAZY = 0 rtld_lazy = 0
DL_EXT = '.dll' dl_ext = '.dll'
) )
fn C.LoadLibrary(libfilename C.LPCWSTR) voidptr fn C.LoadLibrary(libfilename C.LPCWSTR) voidptr

View File

@ -89,14 +89,14 @@ pub struct FlagParser {
pub const ( pub const (
// used for formating usage message // used for formating usage message
space = ' ' space = ' '
UNDERLINE = '-----------------------------------------------' underline = '-----------------------------------------------'
MAX_ARGS_NUMBER = 4048 max_args_number = 4048
) )
// create a new flag set for parsing command line arguments // create a new flag set for parsing command line arguments
// TODO use INT_MAX some how // TODO use INT_MAX some how
pub fn new_flag_parser(args []string) &FlagParser { pub fn new_flag_parser(args []string) &FlagParser {
return &FlagParser{args: args.clone(), max_free_args: MAX_ARGS_NUMBER} return &FlagParser{args: args.clone(), max_free_args: max_args_number}
} }
// change the application name to be used in 'usage' output // change the application name to be used in 'usage' output
@ -358,8 +358,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 > 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 $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')
@ -368,8 +368,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 > 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 $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')
@ -396,7 +396,7 @@ pub fn (mut fs FlagParser) arguments_description(description string){
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 != 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]' }
@ -405,7 +405,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 += '$underline\n'
} }
use += 'Usage: ${fs.application_name} [options] $adesc\n' use += 'Usage: ${fs.application_name} [options] $adesc\n'
use += '\n' use += '\n'

View File

@ -286,7 +286,7 @@ fn (mut ctx FreeType) private_draw_text(_x, _y int, utext ustring, cfg gx.TextCf
wx, wy := ctx.text_size(utext.s) wx, wy := ctx.text_size(utext.s)
yoffset := if ctx.scale > 1 { 5 } else { -1 } // 5 hidpi, -1 lowdpi yoffset := if ctx.scale > 1 { 5 } else { -1 } // 5 hidpi, -1 lowdpi
// println('scale=$ctx.scale size=$cfg.size') // println('scale=$ctx.scale size=$cfg.size')
if cfg.align == gx.ALIGN_RIGHT { if cfg.align == gx.align_right {
// width := utext.len * 7 // width := utext.len * 7
width := wx width := wx
x -= width + 10 x -= width + 10
@ -374,7 +374,7 @@ fn (mut ctx FreeType) private_draw_text(_x, _y int, utext ustring, cfg gx.TextCf
pub fn (mut ctx FreeType) draw_text_def(x, y int, text string) { pub fn (mut ctx FreeType) draw_text_def(x, y int, text string) {
cfg := gx.TextCfg{ cfg := gx.TextCfg{
color: gx.Black color: gx.black
size: default_font_size size: default_font_size
align: gx.align_left align: gx.align_left
} }

View File

@ -480,7 +480,7 @@ pub fn (ctx &GG) draw_empty_rounded_rect(x, y, w, h, r f32, color gx.Color) {
/* /*
pub fn (c &GG) draw_gray_line(x, y, x2, y2 f32) { pub fn (c &GG) draw_gray_line(x, y, x2, y2 f32) {
c.draw_line(x, y, x2, y2, gx.Gray) c.draw_line(x, y, x2, y2, gx.gray)
} }
pub fn (c &GG) draw_vertical(x, y, height int) { pub fn (c &GG) draw_vertical(x, y, height int) {

View File

@ -117,7 +117,7 @@ pub fn (gg &GG) draw_text(x, y int, text string, cfg gx.TextCfg) {
pub fn (ctx &GG) draw_text_def(x, y int, text string) { pub fn (ctx &GG) draw_text_def(x, y int, text string) {
cfg := gx.TextCfg { cfg := gx.TextCfg {
color: gx.Black color: gx.black
size: default_font_size size: default_font_size
align: gx.align_left align: gx.align_left
} }

View File

@ -18,7 +18,7 @@ pub fn (s Shader) str() string {
} }
pub const ( pub const (
TEXT_VERT = '#version 330 core text_vert = '#version 330 core
layout (location = 0) in vec4 vertex; // <vec2 pos, vec2 tex> layout (location = 0) in vec4 vertex; // <vec2 pos, vec2 tex>
out vec2 TexCoords; out vec2 TexCoords;
@ -29,7 +29,7 @@ void main()
gl_Position = projection * vec4(vertex.xy, 0.0, 1.0); gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);
TexCoords = vertex.zw; TexCoords = vertex.zw;
} ' } '
TEXT_FRAG = '#version 330 core text_frag = '#version 330 core
in vec2 TexCoords; in vec2 TexCoords;
out vec4 color; out vec4 color;
@ -41,7 +41,7 @@ void main()
vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r); vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r);
color = vec4(textColor, 1.0) * sampled; color = vec4(textColor, 1.0) * sampled;
} ' } '
SIMPLE_VERT = ' #version 330 core simple_vert = ' #version 330 core
layout (location = 0) in vec3 aPos; layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor; layout (location = 1) in vec3 aColor;
@ -62,7 +62,7 @@ void main() {
TexCoord = aTexCoord; TexCoord = aTexCoord;
} }
' '
SIMPLE_FRAG = '#version 330 core simple_frag = '#version 330 core
out vec4 FragColor; out vec4 FragColor;
uniform vec3 color; uniform vec3 color;
@ -119,14 +119,14 @@ pub fn new_shader(name string) Shader {
mut vertex_src := '' mut vertex_src := ''
mut fragment_src := '' mut fragment_src := ''
if name == 'text' { if name == 'text' {
vertex_src = TEXT_VERT vertex_src = text_vert
fragment_src = TEXT_FRAG fragment_src = text_frag
} }
else if name == 'simple' { else if name == 'simple' {
// println('new shader simple!!!') // println('new shader simple!!!')
// println(SIMPLE_VERT) // println(simple_vert)
vertex_src = SIMPLE_VERT vertex_src = simple_vert
fragment_src = SIMPLE_FRAG fragment_src = simple_frag
} }
// //////////////////////////////////////// // ////////////////////////////////////////
vertex_shader := gl.create_shader(C.GL_VERTEX_SHADER) vertex_shader := gl.create_shader(C.GL_VERTEX_SHADER)
@ -200,4 +200,3 @@ pub fn (s Shader) set_int(str string, n int) {
pub fn (s Shader) set_color(str string, c gx.Color) { pub fn (s Shader) set_color(str string, c gx.Color) {
C.glUniform3f(s.uni_location(str), f32(c.r) / 255.0, f32(c.g) / 255.0, f32(c.b) / 255.0) C.glUniform3f(s.uni_location(str), f32(c.r) / 255.0, f32(c.g) / 255.0, f32(c.b) / 255.0)
} }

View File

@ -34,8 +34,8 @@ import gl
// #flag darwin -framework CoreVideo // #flag darwin -framework CoreVideo
// #flag darwin -framework IOKit // #flag darwin -framework IOKit
pub const ( pub const (
RESIZABLE = 1 resizable = 1
DECORATED = 2 decorated = 2
) )
pub const ( pub const (

View File

@ -12,7 +12,7 @@ import live
pub fn new_live_reload_info(original string, vexe string, vopts string, live_fn_mutex voidptr, live_linkfn live.FNLinkLiveSymbols) &live.LiveReloadInfo { pub fn new_live_reload_info(original string, vexe string, vopts string, live_fn_mutex voidptr, live_linkfn live.FNLinkLiveSymbols) &live.LiveReloadInfo {
file_base := os.file_name(original).replace('.v', '') file_base := os.file_name(original).replace('.v', '')
so_dir := os.cache_dir() so_dir := os.cache_dir()
so_extension := dl.DL_EXT so_extension := dl.dl_ext
/* $if msvc { so_extension = '.dll' } $else { so_extension = '.so' } */ /* $if msvc { so_extension = '.dll' } $else { so_extension = '.so' } */
return &live.LiveReloadInfo{ return &live.LiveReloadInfo{
original: original original: original
@ -113,14 +113,14 @@ fn protected_load_lib(r mut live.LiveReloadInfo, new_lib_path string) {
dl.close( r.live_lib ) dl.close( r.live_lib )
r.live_lib = 0 r.live_lib = 0
} }
r.live_lib = dl.open(new_lib_path, dl.RTLD_LAZY) r.live_lib = dl.open(new_lib_path, dl.rtld_lazy)
if r.live_lib == 0 { if r.live_lib == 0 {
eprintln('opening $new_lib_path failed') eprintln('opening $new_lib_path failed')
exit(1) exit(1)
} }
r.live_linkfn( r.live_lib ) r.live_linkfn( r.live_lib )
elog(r,'> load_lib OK, new live_lib: $r.live_lib') elog(r,'> load_lib OK, new live_lib: $r.live_lib')
// removing the .so file from the filesystem after dlopen-ing // removing the .so file from the filesystem after dlopen-ing
// it is safe, since it will still be mapped in memory // it is safe, since it will still be mapped in memory
os.rm( new_lib_path ) os.rm( new_lib_path )
} }

View File

@ -57,7 +57,7 @@ fn log_factorial_asymptotic_expansion(n int) f64 {
mut i := 0 mut i := 0
for i = 0; i < m; i++ { for i = 0; i < m; i++ {
term << B[i] / xj term << b_numbers[i] / xj
xj *= xx xj *= xx
} }

View File

@ -5,9 +5,9 @@
module factorial module factorial
const ( const (
log_sqrt_2pi = 9.18938533204672741780329736e-1 log_sqrt_2pi = 9.18938533204672741780329736e-1
B = [ b_numbers = [
/* Bernoulli numbers B(2),B(4),B(6),...,B(20). Only B(2),...,B(10) currently /* Bernoulli numbers B(2),B(4),B(6),...,B(20). Only B(2),...,B(10) currently
* used. * used.
*/ */

View File

@ -3,29 +3,29 @@ module mysql
/* MYSQL CONNECT FLAGS */ /* MYSQL CONNECT FLAGS */
pub const ( pub const (
// CAN_HANDLE_EXPIRED_PASSWORDS = C.CAN_HANDLE_EXPIRED_PASSWORDS // CAN_HANDLE_EXPIRED_PASSWORDS = C.CAN_HANDLE_EXPIRED_PASSWORDS
CLIENT_COMPRESS = C.CLIENT_COMPRESS client_compress = C.CLIENT_COMPRESS
CLIENT_FOUND_ROWS = C.CLIENT_FOUND_ROWS client_found_rows = C.CLIENT_FOUND_ROWS
CLIENT_IGNORE_SIGPIPE = C.CLIENT_IGNORE_SIGPIPE client_ignore_sigpipe = C.CLIENT_IGNORE_SIGPIPE
CLIENT_IGNORE_SPACE = C.CLIENT_IGNORE_SPACE client_ignore_space = C.CLIENT_IGNORE_SPACE
CLIENT_INTERACTIVE = C.CLIENT_INTERACTIVE client_interactive = C.CLIENT_INTERACTIVE
CLIENT_LOCAL_FILES = C.CLIENT_LOCAL_FILES client_local_files = C.CLIENT_LOCAL_FILES
CLIENT_MULTI_RESULTS = C.CLIENT_MULTI_RESULTS client_multi_results = C.CLIENT_MULTI_RESULTS
CLIENT_MULTI_STATEMENTS = C.CLIENT_MULTI_STATEMENTS client_multi_statements = C.CLIENT_MULTI_STATEMENTS
CLIENT_NO_SCHEMA = C.CLIENT_NO_SCHEMA client_no_schema = C.CLIENT_NO_SCHEMA
CLIENT_ODBC = C.CLIENT_ODBC client_odbc = C.CLIENT_ODBC
// CLIENT_OPTIONAL_RESULTSET_METADATA = C.CLIENT_OPTIONAL_RESULTSET_METADATA // client_optional_resultset_metadata = C.CLIENT_OPTIONAL_RESULTSET_METADATA
CLIENT_SSL = C.CLIENT_SSL client_ssl = C.CLIENT_SSL
CLIENT_REMEMBER_OPTIONS = C.CLIENT_REMEMBER_OPTIONS client_remember_options = C.CLIENT_REMEMBER_OPTIONS
) )
/* MYSQL REFRESH FLAGS */ /* MYSQL REFRESH FLAGS */
pub const ( pub const (
REFRESH_GRANT = u32(C.REFRESH_GRANT) refresh_grant = u32(C.REFRESH_GRANT)
REFRESH_LOG = u32(C.REFRESH_LOG) refresh_log = u32(C.REFRESH_LOG)
REFRESH_TABLES = u32(C.REFRESH_TABLES) refresh_tables = u32(C.REFRESH_TABLES)
REFRESH_HOSTS = u32(C.REFRESH_HOSTS) refresh_hosts = u32(C.REFRESH_HOSTS)
REFRESH_STATUS = u32(C.REFRESH_STATUS) refresh_status = u32(C.REFRESH_STATUS)
REFRESH_THREADS = u32(C.REFRESH_THREADS) refresh_threads = u32(C.REFRESH_THREADS)
REFRESH_SLAVE = u32(C.REFRESH_SLAVE) refresh_slave = u32(C.REFRESH_SLAVE)
REFRESH_MASTER = u32(C.REFRESH_MASTER) refresh_master = u32(C.REFRESH_MASTER)
) )

View File

@ -10,8 +10,7 @@ fn error_code() int {
} }
pub const ( pub const (
MSG_NOSIGNAL = 0x4000 msg_nosignal = 0x4000
) )
#flag solaris -lsocket #flag solaris -lsocket

View File

@ -17,12 +17,12 @@ mut:
const ( const (
WSA_V22 = 0x202 // C.MAKEWORD(2, 2) wsa_v22 = 0x202 // C.MAKEWORD(2, 2)
) )
fn init() { fn init() {
mut wsadata := C.WSAData{} mut wsadata := C.WSAData{}
res := C.WSAStartup(WSA_V22, &wsadata) res := C.WSAStartup(wsa_v22, &wsadata)
if res != 0 { if res != 0 {
panic('socket: WSAStartup failed') panic('socket: WSAStartup failed')
} }
@ -33,5 +33,5 @@ fn error_code() int {
} }
pub const ( pub const (
MSG_NOSIGNAL = 0 msg_nosignal = 0
) )

View File

@ -227,7 +227,7 @@ pub fn (s Socket) send(buf byteptr, len int) ?int {
mut dptr := buf mut dptr := buf
mut dlen := len mut dlen := len
for { for {
sbytes := C.send(s.sockfd, dptr, dlen, MSG_NOSIGNAL) sbytes := C.send(s.sockfd, dptr, dlen, msg_nosignal)
if sbytes < 0 { if sbytes < 0 {
return error('net.send: failed with $sbytes') return error('net.send: failed with $sbytes')
} }
@ -300,7 +300,7 @@ pub const (
// write - write a string with CRLF after it over the socket s // write - write a string with CRLF after it over the socket s
pub fn (s Socket) write(str string) ?int { pub fn (s Socket) write(str string) ?int {
line := '$str$CRLF' line := '$str$CRLF'
res := C.send(s.sockfd, line.str, line.len, MSG_NOSIGNAL) res := C.send(s.sockfd, line.str, line.len, msg_nosignal)
if res < 0 { if res < 0 {
return error('net.write: failed with $res') return error('net.write: failed with $res')
} }

View File

@ -3,17 +3,16 @@ module os
// ref: http://www.ccfit.nsu.ru/~deviv/courses/unix/unix/ng7c229.html // ref: http://www.ccfit.nsu.ru/~deviv/courses/unix/unix/ng7c229.html
const ( const (
S_IFMT = 0xF000 // type of file s_ifmt = 0xF000 // type of file
S_IFDIR = 0x4000 // directory s_ifdir = 0x4000 // directory
S_IFLNK = 0xa000 // link s_iflnk = 0xa000 // link
S_IXUSR = 0o100 // is executable by the owner s_ixusr = 0o100 // is executable by the owner
S_IXGRP = 0o010 // is executable by group s_ixgrp = 0o010 // is executable by group
S_IXOTH = 0o001 // is executable by others s_ixoth = 0o001 // is executable by others
) )
const ( const (
STD_INPUT_HANDLE = -10 std_input_handle = -10
STD_OUTPUT_HANDLE = -11 std_output_handle = -11
STD_ERROR_HANDLE = -12 std_error_handle = -12
) )

View File

@ -2,14 +2,14 @@ module os
// File modes // File modes
const ( const (
O_RDONLY = 000000000 // open the file read-only. o_rdonly = 000000000 // open the file read-only.
O_WRONLY = 000000001 // open the file write-only. o_wronly = 000000001 // open the file write-only.
O_RDWR = 000000002 // open the file read-write. o_rdwr = 000000002 // open the file read-write.
O_CREATE = 000000100 // create a new file if none exists. o_create = 000000100 // create a new file if none exists.
O_EXCL = 000000200 // used with O_CREATE, file must not exist. o_excl = 000000200 // used with o_create, file must not exist.
O_NOCTTY = 000000400 // if file is terminal, don't make it the controller terminal o_noctty = 000000400 // if file is terminal, don't make it the controller terminal
O_TRUNC = 000001000 // truncate regular writable file when opened. o_trunc = 000001000 // truncate regular writable file when opened.
O_APPEND = 000002000 // append data to the file when writing. o_append = 000002000 // append data to the file when writing.
O_NONBLOCK = 000004000 // prevents blocking when opening files o_nonblock = 000004000 // prevents blocking when opening files
O_SYNC = 000010000 // open for synchronous I/O. o_sync = 000010000 // open for synchronous I/O.
) )

View File

@ -3,102 +3,102 @@ module os
// Ref - winnt.h // Ref - winnt.h
const ( const (
success = 0 // ERROR_SUCCESS success = 0 // ERROR_SUCCESS
ERROR_INSUFFICIENT_BUFFER = 130 error_insufficient_buffer = 130
) )
const ( const (
FILE_SHARE_READ = 1 file_share_read = 1
FILE_SHARE_WRITE = 2 file_share_write = 2
FILE_SHARE_DELETE = 4 file_share_delete = 4
) )
const ( const (
FILE_NOTIFY_CHANGE_FILE_NAME = 1 file_notify_change_file_name = 1
FILE_NOTIFY_CHANGE_DIR_NAME = 2 file_notify_change_dir_name = 2
FILE_NOTIFY_CHANGE_ATTRIBUTES = 4 file_notify_change_attributes = 4
FILE_NOTIFY_CHANGE_SIZE = 8 file_notify_change_size = 8
FILE_NOTIFY_CHANGE_LAST_WRITE = 16 file_notify_change_last_write = 16
FILE_NOTIFY_CHANGE_LAST_ACCESS = 32 file_notify_change_last_access = 32
FILE_NOTIFY_CHANGE_CREATION = 64 file_notify_change_creation = 64
FILE_NOTIFY_CHANGE_SECURITY = 128 file_notify_change_security = 128
) )
const ( const (
FILE_ACTION_ADDED = 1 file_action_added = 1
FILE_ACTION_REMOVED = 2 file_action_removed = 2
FILE_ACTION_MODIFIED = 3 file_action_modified = 3
FILE_ACTION_RENAMED_OLD_NAME = 4 file_action_renamed_old_name = 4
FILE_ACTION_RENAMED_NEW_NAME = 5 file_action_renamed_new_name = 5
) )
const ( const (
FILE_ATTR_READONLY = 0x1 file_attr_readonly = 0x1
FILE_ATTR_HIDDEN = 0x2 file_attr_hidden = 0x2
FILE_ATTR_SYSTEM = 0x4 file_attr_system = 0x4
FILE_ATTR_DIRECTORY = 0x10 file_attr_directory = 0x10
FILE_ATTR_ARCHIVE = 0x20 file_attr_archive = 0x20
FILE_ATTR_DEVICE = 0x40 file_attr_device = 0x40
FILE_ATTR_NORMAL = 0x80 file_attr_normal = 0x80
FILE_ATTR_TEMPORARY = 0x100 file_attr_temporary = 0x100
FILE_ATTR_SPARSE_FILE = 0x200 file_attr_sparse_file = 0x200
FILE_ATTR_REPARSE_POINT = 0x400 file_attr_reparse_point = 0x400
FILE_ATTR_COMPRESSED = 0x800 file_attr_compressed = 0x800
FILE_ATTR_OFFLINE = 0x1000 file_attr_offline = 0x1000
FILE_ATTR_NOT_CONTENT_INDEXED = 0x2000 file_attr_not_content_indexed = 0x2000
FILE_ATTR_ENCRYPTED = 0x4000 file_attr_encrypted = 0x4000
FILE_ATTR_INTEGRITY_STREAM = 0x8000 file_attr_integrity_stream = 0x8000
FILE_ATTR_VIRTUAL = 0x10000 file_attr_virtual = 0x10000
FILE_ATTR_NO_SCRUB_DATA = 0x20000 file_attr_no_scrub_data = 0x20000
// FILE_ATTR_RECALL_ON_OPEN = u32(0x...) // file_attr_recall_on_open = u32(0x...)
// FILE_ATTR_RECALL_ON_DATA_ACCESS = u32(0x...) // file_attr_recall_on_data_access = u32(0x...)
) )
const ( const (
FILE_TYPE_DISK = 0x1 file_type_disk = 0x1
FILE_TYPE_CHAR = 0x2 file_type_char = 0x2
FILE_TYPE_PIPE = 0x3 file_type_pipe = 0x3
FILE_TYPE_UNKNOWN = 0x0 file_type_unknown = 0x0
) )
const ( const (
FILE_INVALID_FILE_ID = (-1) file_invalid_file_id = (-1)
) )
const( const(
INVALID_HANDLE_VALUE = voidptr(-1) invalid_handle_value = voidptr(-1)
) )
// https://docs.microsoft.com/en-us/windows/console/setconsolemode // https://docs.microsoft.com/en-us/windows/console/setconsolemode
const ( const (
// Input Buffer // Input Buffer
ENABLE_ECHO_INPUT = 0x0004 enable_echo_input = 0x0004
ENABLE_EXTENDED_FLAGS = 0x0080 enable_extended_flags = 0x0080
ENABLE_INSERT_MODE = 0x0020 enable_insert_mode = 0x0020
ENABLE_LINE_INPUT = 0x0002 enable_line_input = 0x0002
ENABLE_MOUSE_INPUT = 0x0010 enable_mouse_input = 0x0010
ENABLE_PROCESSED_INPUT = 0x0001 enable_processed_input = 0x0001
ENABLE_QUICK_EDIT_MODE = 0x0040 enable_quick_edit_mode = 0x0040
ENABLE_WINDOW_INPUT = 0x0008 enable_window_input = 0x0008
ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 enable_virtual_terminal_input = 0x0200
// Output Screen Buffer // Output Screen Buffer
ENABLE_PROCESSED_OUTPUT = 0x0001 enable_processed_output = 0x0001
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 enable_wrap_at_eol_output = 0x0002
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 enable_virtual_terminal_processing = 0x0004
DISABLE_NEWLINE_AUTO_RETURN = 0x0008 disable_newline_auto_return = 0x0008
ENABLE_LVB_GRID_WORLDWIDE = 0x0010 enable_lvb_grid_worldwide = 0x0010
) )
// File modes // File modes
const ( const (
O_RDONLY = 0 // open the file read-only. o_rdonly = 0 // open the file read-only.
O_WRONLY = 1 // open the file write-only. o_wronly = 1 // open the file write-only.
O_RDWR = 2 // open the file read-write. o_rdwr = 2 // open the file read-write.
O_APPEND = 0x0008 // append data to the file when writing. o_append = 0x0008 // append data to the file when writing.
O_CREATE = 0x0100 // create a new file if none exists. o_create = 0x0100 // create a new file if none exists.
O_TRUNC = 0x0200 // truncate regular writable file when opened. o_trunc = 0x0200 // truncate regular writable file when opened.
O_EXCL = 0x0400 // used with O_CREATE, file must not exist. o_excl = 0x0400 // used with o_create, file must not exist.
O_SYNC = 0 // open for synchronous I/O (ignored on Windows) o_sync = 0 // open for synchronous I/O (ignored on Windows)
O_NOCTTY = 0 // make file non-controlling tty (ignored on Windows) o_noctty = 0 // make file non-controlling tty (ignored on Windows)
O_NONBLOCK = 0 // don't block on opening file (ignored on Windows) o_nonblock = 0 // don't block on opening file (ignored on Windows)
) )

View File

@ -24,7 +24,7 @@ fn C.readdir(voidptr) C.dirent
pub const ( pub const (
args = []string{} args = []string{}
MAX_PATH = 4096 max_path_len = 4096
) )
pub struct File { pub struct File {
@ -352,13 +352,13 @@ pub fn open_file(path string, mode string, options ...int) ?File {
mut flags := 0 mut flags := 0
for m in mode { for m in mode {
match m { match m {
`r` { flags |= O_RDONLY } `r` { flags |= o_rdonly }
`w` { flags |= O_CREATE | O_TRUNC } `w` { flags |= o_create | o_trunc }
`a` { flags |= O_CREATE | O_APPEND } `a` { flags |= o_create | o_append }
`s` { flags |= O_SYNC } `s` { flags |= o_sync }
`n` { flags |= O_NONBLOCK } `n` { flags |= o_nonblock }
`c` { flags |= O_NOCTTY } `c` { flags |= o_noctty }
`+` { flags |= O_RDWR } `+` { flags |= o_rdwr }
else {} else {}
} }
} }
@ -570,19 +570,19 @@ pub fn sigint_to_signal_name(si int) string {
} }
const ( const (
F_OK = 0 f_ok = 0
X_OK = 1 x_ok = 1
W_OK = 2 w_ok = 2
R_OK = 4 r_ok = 4
) )
// exists returns true if `path` exists. // exists returns true if `path` exists.
pub fn exists(path string) bool { pub fn exists(path string) bool {
$if windows { $if windows {
p := path.replace('/', '\\') p := path.replace('/', '\\')
return C._waccess(p.to_wide(), F_OK) != -1 return C._waccess(p.to_wide(), f_ok) != -1
} $else { } $else {
return C.access(path.str, F_OK) != -1 return C.access(path.str, f_ok) != -1
} }
} }
@ -603,9 +603,9 @@ pub fn is_executable(path string) bool {
if C.stat(path.str, &statbuf) != 0 { if C.stat(path.str, &statbuf) != 0 {
return false return false
} }
return (int(statbuf.st_mode) & ( S_IXUSR | S_IXGRP | S_IXOTH )) != 0 return (int(statbuf.st_mode) & ( s_ixusr | s_ixgrp | s_ixoth )) != 0
} }
return C.access(path.str, X_OK) != -1 return C.access(path.str, x_ok) != -1
} }
// `is_writable_folder` - `folder` exists and is writable to the process // `is_writable_folder` - `folder` exists and is writable to the process
@ -629,9 +629,9 @@ pub fn is_writable_folder(folder string) ?bool {
pub fn is_writable(path string) bool { pub fn is_writable(path string) bool {
$if windows { $if windows {
p := path.replace('/', '\\') p := path.replace('/', '\\')
return C._waccess(p.to_wide(), W_OK) != -1 return C._waccess(p.to_wide(), w_ok) != -1
} $else { } $else {
return C.access(path.str, W_OK) != -1 return C.access(path.str, w_ok) != -1
} }
} }
@ -639,9 +639,9 @@ pub fn is_writable(path string) bool {
pub fn is_readable(path string) bool { pub fn is_readable(path string) bool {
$if windows { $if windows {
p := path.replace('/', '\\') p := path.replace('/', '\\')
return C._waccess(p.to_wide(), R_OK) != -1 return C._waccess(p.to_wide(), r_ok) != -1
} $else { } $else {
return C.access(path.str, R_OK) != -1 return C.access(path.str, r_ok) != -1
} }
} }
@ -748,7 +748,7 @@ pub fn get_raw_line() string {
unsafe { unsafe {
max_line_chars := 256 max_line_chars := 256
buf := malloc(max_line_chars * 2) buf := malloc(max_line_chars * 2)
h_input := C.GetStdHandle(STD_INPUT_HANDLE) h_input := C.GetStdHandle(std_input_handle)
mut bytes_read := 0 mut bytes_read := 0
if is_atty(0) > 0 { if is_atty(0) > 0 {
C.ReadConsole(h_input, buf, max_line_chars * 2, &bytes_read, 0) C.ReadConsole(h_input, buf, max_line_chars * 2, &bytes_read, 0)
@ -903,8 +903,8 @@ fn C.readlink() int
// process. // process.
pub fn executable() string { pub fn executable() string {
$if linux { $if linux {
mut result := vcalloc(MAX_PATH) mut result := vcalloc(max_path_len)
count := C.readlink('/proc/self/exe', result, MAX_PATH) count := C.readlink('/proc/self/exe', result, max_path_len)
if count < 0 { if count < 0 {
eprintln('os.executable() failed at reading /proc/self/exe to get exe path') eprintln('os.executable() failed at reading /proc/self/exe to get exe path')
return executable_fallback() return executable_fallback()
@ -913,14 +913,14 @@ pub fn executable() string {
} }
$if windows { $if windows {
max := 512 max := 512
mut result := &u16(vcalloc(max * 2)) // MAX_PATH * sizeof(wchar_t) mut result := &u16(vcalloc(max * 2)) // max_path_len * sizeof(wchar_t)
len := C.GetModuleFileName(0, result, max) len := C.GetModuleFileName(0, result, max)
return string_from_wide2(result, len) return string_from_wide2(result, len)
} }
$if macos { $if macos {
mut result := vcalloc(MAX_PATH) mut result := vcalloc(max_path_len)
pid := C.getpid() pid := C.getpid()
ret := proc_pidpath(pid, result, MAX_PATH) ret := proc_pidpath(pid, result, max_path_len)
if ret <= 0 { if ret <= 0 {
eprintln('os.executable() failed at calling proc_pidpath with pid: $pid . proc_pidpath returned $ret ') eprintln('os.executable() failed at calling proc_pidpath with pid: $pid . proc_pidpath returned $ret ')
return executable_fallback() return executable_fallback()
@ -928,9 +928,9 @@ pub fn executable() string {
return string(result) return string(result)
} }
$if freebsd { $if freebsd {
mut result := vcalloc(MAX_PATH) mut result := vcalloc(max_path_len)
mib := [1/* CTL_KERN */, 14/* KERN_PROC */, 12/* KERN_PROC_PATHNAME */, -1] mib := [1/* CTL_KERN */, 14/* KERN_PROC */, 12/* KERN_PROC_PATHNAME */, -1]
size := MAX_PATH size := max_path_len
C.sysctl(mib.data, 4, result, &size, 0, 0) C.sysctl(mib.data, 4, result, &size, 0, 0)
return string(result) return string(result)
} }
@ -939,8 +939,8 @@ pub fn executable() string {
$if solaris {} $if solaris {}
$if haiku {} $if haiku {}
$if netbsd { $if netbsd {
mut result := vcalloc(MAX_PATH) mut result := vcalloc(max_path_len)
count := C.readlink('/proc/curproc/exe', result, MAX_PATH) count := C.readlink('/proc/curproc/exe', result, max_path_len)
if count < 0 { if count < 0 {
eprintln('os.executable() failed at reading /proc/curproc/exe to get exe path') eprintln('os.executable() failed at reading /proc/curproc/exe to get exe path')
return executable_fallback() return executable_fallback()
@ -948,8 +948,8 @@ pub fn executable() string {
return string(result,count) return string(result,count)
} }
$if dragonfly { $if dragonfly {
mut result := vcalloc(MAX_PATH) mut result := vcalloc(max_path_len)
count := C.readlink('/proc/curproc/file', result, MAX_PATH) count := C.readlink('/proc/curproc/file', result, max_path_len)
if count < 0 { if count < 0 {
eprintln('os.executable() failed at reading /proc/curproc/file to get exe path') eprintln('os.executable() failed at reading /proc/curproc/file to get exe path')
return executable_fallback() return executable_fallback()
@ -1036,8 +1036,8 @@ pub fn is_dir(path string) bool {
return false return false
} }
// ref: https://code.woboq.org/gcc/include/sys/stat.h.html // ref: https://code.woboq.org/gcc/include/sys/stat.h.html
val:= int(statbuf.st_mode) & S_IFMT val:= int(statbuf.st_mode) & os.s_ifmt
return val == S_IFDIR return val == s_ifdir
} }
} }
@ -1050,7 +1050,7 @@ pub fn is_link(path string) bool {
if C.lstat(path.str, &statbuf) != 0 { if C.lstat(path.str, &statbuf) != 0 {
return false return false
} }
return int(statbuf.st_mode) & S_IFMT == S_IFLNK return int(statbuf.st_mode) & s_ifmt == s_iflnk
} }
} }
@ -1066,7 +1066,7 @@ pub fn chdir(path string) {
// getwd returns the absolute path name of the current directory. // getwd returns the absolute path name of the current directory.
pub fn getwd() string { pub fn getwd() string {
$if windows { $if windows {
max := 512 // MAX_PATH * sizeof(wchar_t) max := 512 // max_path_len * sizeof(wchar_t)
buf := &u16(vcalloc(max * 2)) buf := &u16(vcalloc(max * 2))
if C._wgetcwd(buf, max) == 0 { if C._wgetcwd(buf, max) == 0 {
return '' return ''
@ -1087,10 +1087,10 @@ pub fn getwd() string {
// and https://insanecoding.blogspot.com/2007/11/implementing-realpath-in-c.html // and https://insanecoding.blogspot.com/2007/11/implementing-realpath-in-c.html
// NB: this particular rabbit hole is *deep* ... // NB: this particular rabbit hole is *deep* ...
pub fn real_path(fpath string) string { pub fn real_path(fpath string) string {
mut fullpath := vcalloc(MAX_PATH) mut fullpath := vcalloc(max_path_len)
mut ret := charptr(0) mut ret := charptr(0)
$if windows { $if windows {
ret = C._fullpath(fullpath, fpath.str, MAX_PATH) ret = C._fullpath(fullpath, fpath.str, max_path_len)
if ret == 0 { if ret == 0 {
return fpath return fpath
} }

View File

@ -5,11 +5,11 @@
module os module os
const ( const (
PROT_READ = 1 prot_read = 1
PROT_WRITE = 2 prot_write = 2
MAP_PRIVATE = 0x02 map_private = 0x02
MAP_ANONYMOUS = 0x20 map_anonymous = 0x20
) )
pub const ( pub const (
@ -45,13 +45,11 @@ fn mmap(start voidptr, len, prot, flags, fd, off int) byteptr {
pub fn malloc(n int) byteptr { pub fn malloc(n int) byteptr {
println('malloc($n)') println('malloc($n)')
return mmap(0, n, 3, 4098, //PROT_READ|PROT_WRITE, return mmap(0, n, 3, 4098, //prot_read|prot_write,
-1,0) //MAP_PRIVATE|MAP_ANONYMOUS, -1,0) //map_private|map_anonymous,
} }
pub fn free(b byteptr) { pub fn free(b byteptr) {
} }
*/ */

View File

@ -32,7 +32,7 @@ mut:
n_file_size_low u32 n_file_size_low u32
dw_reserved0 u32 dw_reserved0 u32
dw_reserved1 u32 dw_reserved1 u32
c_file_name [260]u16 // MAX_PATH = 260 c_file_name [260]u16 // max_path_len = 260
c_alternate_file_name [14]u16 // 14 c_alternate_file_name [14]u16 // 14
dw_file_type u32 dw_file_type u32
dw_creator_type u32 dw_creator_type u32
@ -89,7 +89,7 @@ pub fn ls(path string) ?[]string {
mut dir_files := []string{} mut dir_files := []string{}
// We can also check if the handle is valid. but using is_dir instead // We can also check if the handle is valid. but using is_dir instead
// h_find_dir := C.FindFirstFile(path.str, &find_file_data) // h_find_dir := C.FindFirstFile(path.str, &find_file_data)
// if (INVALID_HANDLE_VALUE == h_find_dir) { // if (invalid_handle_value == h_find_dir) {
// return dir_files // return dir_files
// } // }
// C.FindClose(h_find_dir) // C.FindClose(h_find_dir)
@ -146,7 +146,7 @@ pub fn mkdir(path string) ?bool {
pub fn get_file_handle(path string) HANDLE { pub fn get_file_handle(path string) HANDLE {
cfile := vfopen(path, 'rb') cfile := vfopen(path, 'rb')
if cfile == 0 { if cfile == 0 {
return HANDLE(INVALID_HANDLE_VALUE) return HANDLE(invalid_handle_value)
} }
handle := HANDLE(C._get_osfhandle(fileno(cfile))) // CreateFile? - hah, no -_- handle := HANDLE(C._get_osfhandle(fileno(cfile))) // CreateFile? - hah, no -_-
return handle return handle
@ -177,24 +177,24 @@ pub fn get_module_filename(handle HANDLE) ?string {
// Ref - https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessagea#parameters // Ref - https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessagea#parameters
const ( const (
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100 format_message_allocate_buffer = 0x00000100
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000 format_message_argument_array = 0x00002000
FORMAT_MESSAGE_FROM_HMODULE = 0x00000800 format_message_from_hmodule = 0x00000800
FORMAT_MESSAGE_FROM_STRING = 0x00000400 format_message_from_string = 0x00000400
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000 format_message_from_system = 0x00001000
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200 format_message_ignore_inserts = 0x00000200
) )
// Ref - winnt.h // Ref - winnt.h
const ( const (
SUBLANG_NEUTRAL = 0x00 sublang_neutral = 0x00
SUBLANG_DEFAULT = 0x01 sublang_default = 0x01
LANG_NEUTRAL = (SUBLANG_NEUTRAL) lang_neutral = (sublang_neutral)
) )
// Ref - https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--12000-15999- // Ref - https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--12000-15999-
const ( const (
MAX_ERROR_CODE = 15841 // ERROR_API_UNAVAILABLE max_error_code = 15841 // ERROR_API_UNAVAILABLE
) )
// ptr_win_get_error_msg return string (voidptr) // ptr_win_get_error_msg return string (voidptr)
@ -202,14 +202,14 @@ 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(max_error_code) {
return buf return buf
} }
C.FormatMessage( C.FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER format_message_allocate_buffer
| FORMAT_MESSAGE_FROM_SYSTEM | format_message_from_system
| FORMAT_MESSAGE_IGNORE_INSERTS, | format_message_ignore_inserts,
0, code, C.MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), voidptr(&buf), 0, 0) 0, code, C.MAKELANGID(lang_neutral, sublang_default), voidptr(&buf), 0, 0)
return buf return buf
} }

View File

@ -2000,7 +2000,7 @@ pub fn (mut re RE) match_base(in_txt byteptr, in_txt_len int ) (int,int) {
continue continue
} }
else if rep==0 && rep < re.prog[tmp_pc].rep_min { else if rep==0 && rep < re.prog[tmp_pc].rep_min {
//println("ist_quant_ng ZERO UNDER THE MINIMUM g.i: $group_index") //println("ist_quant_ng c_zero UNDER THE MINIMUM g.i: $group_index")
if group_index > 0{ if group_index > 0{
group_index-- group_index--
@ -2071,7 +2071,7 @@ pub fn (mut re RE) match_base(in_txt byteptr, in_txt_len int ) (int,int) {
// zero quantifier * or ? // zero quantifier * or ?
if rep == 0 && re.prog[pc].rep_min == 0 { if rep == 0 && re.prog[pc].rep_min == 0 {
//println("ist_quant_n ZERO RANGE MIN") //println("ist_quant_n c_zero RANGE MIN")
m_state = .ist_next // go to next ist m_state = .ist_next // go to next ist
continue continue
} }

View File

@ -100,11 +100,11 @@ const (
// //
// f64 constants // f64 constants
// //
DIGITS = 18 digits = 18
DOUBLE_PLUS_ZERO = u64(0x0000000000000000) double_plus_zero = u64(0x0000000000000000)
DOUBLE_MINUS_ZERO = u64(0x8000000000000000) double_minus_zero = u64(0x8000000000000000)
DOUBLE_PLUS_INFINITY = u64(0x7FF0000000000000) double_plus_infinity = u64(0x7FF0000000000000)
DOUBLE_MINUS_INFINITY = u64(0xFFF0000000000000) double_minus_infinity = u64(0xFFF0000000000000)
// //
// parser state machine states // parser state machine states
// //
@ -117,7 +117,7 @@ const (
fsm_g = 6 fsm_g = 6
fsm_h = 7 fsm_h = 7
fsm_i = 8 fsm_i = 8
FSM_STOP = 9 fsm_stop = 9
// //
// Possible parser return values. // Possible parser return values.
// //
@ -130,12 +130,12 @@ const (
// char constants // char constants
// Note: Modify these if working with non-ASCII encoding // Note: Modify these if working with non-ASCII encoding
// //
DPOINT = `.` c_dpoint = `.`
PLUS = `+` c_plus = `+`
MINUS = `-` c_minus = `-`
ZERO = `0` c_zero = `0`
NINE = `9` c_nine = `9`
TEN = u32(10) c_ten = u32(10)
) )
/********************************************************************** /**********************************************************************
* *
@ -145,7 +145,7 @@ const (
// NOTE: Modify these if working with non-ASCII encoding // NOTE: Modify these if working with non-ASCII encoding
fn is_digit(x byte) bool { fn is_digit(x byte) bool {
return (x >= ZERO && x <= NINE) == true return (x >= c_zero && x <= c_nine) == true
} }
fn is_space(x byte) bool { fn is_space(x byte) bool {
@ -187,7 +187,7 @@ fn parser(s string) (int,PrepNumber) {
mut i := 0 mut i := 0
mut pn := PrepNumber{ mut pn := PrepNumber{
} }
for state != FSM_STOP { for state != fsm_stop {
match state { match state {
// skip starting spaces // skip starting spaces
fsm_a { fsm_a {
@ -201,28 +201,28 @@ fn parser(s string) (int,PrepNumber) {
// check for the sign or point // check for the sign or point
fsm_b { fsm_b {
state = fsm_c state = fsm_c
if c == PLUS { if c == c_plus {
c = s[i++] c = s[i++]
//i++ //i++
} }
else if c == MINUS { else if c == c_minus {
pn.negative = true pn.negative = true
c = s[i++] c = s[i++]
} }
else if is_digit(c) { else if is_digit(c) {
} }
else if c == DPOINT { else if c == c_dpoint {
} }
else { else {
state = FSM_STOP state = fsm_stop
} }
} }
// skip the inital zeros // skip the inital zeros
fsm_c { fsm_c {
if c == ZERO { if c == c_zero {
c = s[i++] c = s[i++]
} }
else if c == DPOINT { else if c == c_dpoint {
c = s[i++] c = s[i++]
state = fsm_d state = fsm_d
} }
@ -232,7 +232,7 @@ fn parser(s string) (int,PrepNumber) {
} }
// reading leading zeros in the fractional part of mantissa // reading leading zeros in the fractional part of mantissa
fsm_d { fsm_d {
if c == ZERO { if c == c_zero {
c = s[i++] c = s[i++]
if pn.exponent > -2147483647 { if pn.exponent > -2147483647 {
pn.exponent-- pn.exponent--
@ -245,9 +245,9 @@ fn parser(s string) (int,PrepNumber) {
// reading integer part of mantissa // reading integer part of mantissa
fsm_e { fsm_e {
if is_digit(c) { if is_digit(c) {
if digx < DIGITS { if digx < digits {
pn.mantissa *= 10 pn.mantissa *= 10
pn.mantissa += u64(c - ZERO) pn.mantissa += u64(c - c_zero)
digx++ digx++
} }
else if pn.exponent < 2147483647 { else if pn.exponent < 2147483647 {
@ -255,7 +255,7 @@ fn parser(s string) (int,PrepNumber) {
} }
c = s[i++] c = s[i++]
} }
else if c == DPOINT { else if c == c_dpoint {
c = s[i++] c = s[i++]
state = fsm_f state = fsm_f
} }
@ -266,9 +266,9 @@ fn parser(s string) (int,PrepNumber) {
// reading fractional part of mantissa // reading fractional part of mantissa
fsm_f { fsm_f {
if is_digit(c) { if is_digit(c) {
if digx < DIGITS { if digx < digits {
pn.mantissa *= 10 pn.mantissa *= 10
pn.mantissa += u64(c - ZERO) pn.mantissa += u64(c - c_zero)
pn.exponent-- pn.exponent--
digx++ digx++
} }
@ -284,10 +284,10 @@ fn parser(s string) (int,PrepNumber) {
} }
// reading sign of exponent // reading sign of exponent
fsm_g { fsm_g {
if c == PLUS { if c == c_plus {
c = s[i++] c = s[i++]
} }
else if c == MINUS { else if c == c_minus {
expneg = true expneg = true
c = s[i++] c = s[i++]
} }
@ -295,7 +295,7 @@ fn parser(s string) (int,PrepNumber) {
} }
// skipping leading zeros of exponent // skipping leading zeros of exponent
fsm_h { fsm_h {
if c == ZERO { if c == c_zero {
c = s[i++] c = s[i++]
} }
else { else {
@ -307,19 +307,19 @@ fn parser(s string) (int,PrepNumber) {
if is_digit(c) { if is_digit(c) {
if expexp < 214748364 { if expexp < 214748364 {
expexp *= 10 expexp *= 10
expexp += int(c - ZERO) expexp += int(c - c_zero)
} }
c = s[i++] c = s[i++]
} }
else { else {
state = FSM_STOP state = fsm_stop
} }
} }
else { else {
}} }}
// C.printf("len: %d i: %d str: %s \n",s.len,i,s[..i]) // C.printf("len: %d i: %d str: %s \n",s.len,i,s[..i])
if i >= s.len { if i >= s.len {
state = FSM_STOP state = fsm_stop
} }
} }
if expneg { if expneg {
@ -400,18 +400,18 @@ fn converter(pn mut PrepNumber) u64 {
s1 = q1 s1 = q1
s0 = q0 s0 = q0
} }
q2 = s2 / TEN q2 = s2 / c_ten
r1 = s2 % TEN r1 = s2 % c_ten
r2 = (s1>>8) | (r1<<24) r2 = (s1>>8) | (r1<<24)
q1 = r2 / TEN q1 = r2 / c_ten
r1 = r2 % TEN r1 = r2 % c_ten
r2 = ((s1 & u32(0xFF))<<16) | (s0>>16) | (r1<<24) r2 = ((s1 & u32(0xFF))<<16) | (s0>>16) | (r1<<24)
r0 = r2 / TEN r0 = r2 / c_ten
r1 = r2 % TEN r1 = r2 % c_ten
q1 = (q1<<8) | ((r0 & u32(0x00FF0000))>>16) q1 = (q1<<8) | ((r0 & u32(0x00FF0000))>>16)
q0 = r0<<16 q0 = r0<<16
r2 = (s0 & u32(0xFFFF)) | (r1<<16) r2 = (s0 & u32(0xFFFF)) | (r1<<16)
q0 |= r2 / TEN q0 |= r2 / c_ten
s2 = q2 s2 = q2
s1 = q1 s1 = q1
s0 = q0 s0 = q0
@ -496,18 +496,18 @@ fn converter(pn mut PrepNumber) u64 {
binexp += 1023 binexp += 1023
if binexp > 2046 { if binexp > 2046 {
if pn.negative { if pn.negative {
result = DOUBLE_MINUS_INFINITY result = double_minus_infinity
} }
else { else {
result = DOUBLE_PLUS_INFINITY result = double_plus_infinity
} }
} }
else if binexp < 1 { else if binexp < 1 {
if pn.negative { if pn.negative {
result = DOUBLE_MINUS_ZERO result = double_minus_zero
} }
else { else {
result = DOUBLE_PLUS_ZERO result = double_plus_zero
} }
} }
else if s2 != 0 { else if s2 != 0 {
@ -542,21 +542,18 @@ pub fn atof64(s string) f64 {
res.u = converter(mut pn) res.u = converter(mut pn)
} }
parser_pzero { parser_pzero {
res.u = DOUBLE_PLUS_ZERO res.u = double_plus_zero
} }
parser_mzero { parser_mzero {
res.u = DOUBLE_MINUS_ZERO res.u = double_minus_zero
} }
parser_pinf { parser_pinf {
res.u = DOUBLE_PLUS_INFINITY res.u = double_plus_infinity
} }
parser_minf { parser_minf {
res.u = DOUBLE_MINUS_INFINITY res.u = double_minus_infinity
} }
else { else {
}} }}
return res.f return res.f
} }

View File

@ -66,10 +66,10 @@ fn test_atof() {
mut ptr := &u64(&f1) mut ptr := &u64(&f1)
ptr = &u64(&f1) ptr = &u64(&f1)
// DOUBLE_PLUS_ZERO // double_plus_zero
f1=0.0 f1=0.0
assert *ptr == u64(0x0000000000000000) assert *ptr == u64(0x0000000000000000)
// DOUBLE_MINUS_ZERO // double_minus_zero
f1=-0.0 f1=-0.0
assert *ptr == u64(0x8000000000000000) assert *ptr == u64(0x8000000000000000)
println("DONE!") println("DONE!")

View File

@ -20,10 +20,10 @@ module atofq
// same used in atof, here only for references // same used in atof, here only for references
const( const(
DOUBLE_PLUS_ZERO = u64(0x0000000000000000) double_plus_zero = u64(0x0000000000000000)
DOUBLE_MINUS_ZERO = u64(0x8000000000000000) double_minus_zero = u64(0x8000000000000000)
DOUBLE_PLUS_INFINITY = u64(0x7FF0000000000000) double_plus_infinity = u64(0x7FF0000000000000)
DOUBLE_MINUS_INFINITY = u64(0xFFF0000000000000) double_minus_infinity = u64(0xFFF0000000000000)
) )
union Float64u { union Float64u {
@ -54,10 +54,10 @@ pub fn atof_quick(s string) f64 {
// infinite // infinite
if s[i] == `i` && i + 2 < s.len && s[i + 1] == `n` && s[i + 2] == `f` { if s[i] == `i` && i + 2 < s.len && s[i + 1] == `n` && s[i + 2] == `f` {
if sign > 0.0 { if sign > 0.0 {
f.u = DOUBLE_PLUS_INFINITY f.u = double_plus_infinity
} }
else { else {
f.u = DOUBLE_MINUS_INFINITY f.u = double_minus_infinity
} }
return f.f return f.f
} }
@ -67,10 +67,10 @@ pub fn atof_quick(s string) f64 {
// we have a zero, manage it // we have a zero, manage it
if i >= s.len { if i >= s.len {
if sign > 0.0 { if sign > 0.0 {
f.u = DOUBLE_PLUS_ZERO f.u = double_plus_zero
} }
else { else {
f.u = DOUBLE_MINUS_ZERO f.u = double_minus_zero
} }
return f.f return f.f
} }
@ -118,10 +118,10 @@ pub fn atof_quick(s string) f64 {
if exp_sign == 1 { if exp_sign == 1 {
if exp > pos_exp.len { if exp > pos_exp.len {
if sign > 0 { if sign > 0 {
f.u = DOUBLE_PLUS_INFINITY f.u = double_plus_infinity
} }
else { else {
f.u = DOUBLE_MINUS_INFINITY f.u = double_minus_infinity
} }
return f.f return f.f
} }
@ -132,10 +132,10 @@ pub fn atof_quick(s string) f64 {
else { else {
if exp > neg_exp.len { if exp > neg_exp.len {
if sign > 0 { if sign > 0 {
f.u = DOUBLE_PLUS_ZERO f.u = double_plus_zero
} }
else { else {
f.u = DOUBLE_MINUS_ZERO f.u = double_minus_zero
} }
return f.f return f.f
} }

View File

@ -10,23 +10,23 @@ type zip_ptr &zip
// Ref - miniz.h // Ref - miniz.h
const ( const (
NO_COMPRESSION = 0 no_compression = 0
BEST_SPEED = 1 best_speed = 1
BEST_COMPRESSION = 9 best_compression = 9
UBER_COMPRESSION = 10 uber_compression = 10
DEFAULT_LEVEL = 6 default_level = 6
DEFAULT_COMPRESSION = -1 default_compression = -1
) )
// Ref - zip.h // Ref - zip.h
const ( const (
DEFAULT_COMPRESSION_LEVEL = (DEFAULT_LEVEL) default_compression_level = (default_level)
) )
const ( const (
M_WRITE = 'w' m_write = 'w'
M_RONLY = 'r' m_ronly = 'r'
M_APPEND = 'a' m_append = 'a'
) )
/** /**
@ -43,14 +43,14 @@ const (
*/ */
pub fn open(name string, level int, mode string) ?zip_ptr { pub fn open(name string, level int, mode string) ?zip_ptr {
mut _nlevel := level mut _nlevel := level
if (_nlevel & 0xF) > UBER_COMPRESSION { if (_nlevel & 0xF) > uber_compression {
_nlevel = DEFAULT_COMPRESSION_LEVEL _nlevel = default_compression_level
} }
n := name.len n := name.len
if n == 0 { if n == 0 {
return error('szip: name of file empty') return error('szip: name of file empty')
} }
if mode != M_WRITE && mode != M_RONLY && mode != M_APPEND { if mode != m_write && mode != m_ronly && mode != m_append {
return error('szip: invalid provided open mode') return error('szip: invalid provided open mode')
} }
/* struct zip_t* */_p_zip := zip_ptr(C.zip_open(name.str, /* struct zip_t* */_p_zip := zip_ptr(C.zip_open(name.str,

View File

@ -9,7 +9,7 @@ module term
// Support for Windows // Support for Windows
// https://en.wikipedia.org/wiki/ANSI.SYS // https://en.wikipedia.org/wiki/ANSI.SYS
// #include <windows.h> // #include <windows.h>
// C.SetConsoleMode(ENABLE_VIRTUAL_TERMINAL_INPUT) // C.SetConsoleMode(C.ENABLE_VIRTUAL_TERMINAL_INPUT)
// Setting cursor to the given position // Setting cursor to the given position
// x is the x coordinate // x is the x coordinate
// y is the y coordinate // y is the y coordinate

View File

@ -64,9 +64,9 @@ fn supports_escape_sequences(fd int) bool {
vcolors_override := os.getenv('VCOLORS') vcolors_override := os.getenv('VCOLORS')
if vcolors_override == 'always' { if vcolors_override == 'always' {
return true return true
} }
$if windows { $if windows {
return (is_atty(fd) & 0x0004) > 0 && os.getenv('TERM') != 'dumb' // ENABLE_VIRTUAL_TERMINAL_PROCESSING return (is_atty(fd) & 0x0004) > 0 && os.getenv('TERM') != 'dumb' // enable_virtual_terminal_processing
} $else { } $else {
return is_atty(fd) > 0 && os.getenv('TERM') != 'dumb' return is_atty(fd) > 0 && os.getenv('TERM') != 'dumb'
} }

View File

@ -7,6 +7,7 @@ import v.cflag
#flag windows -l shell32 #flag windows -l shell32
#flag windows -l dbghelp #flag windows -l dbghelp
#flag windows -l advapi32 #flag windows -l advapi32
struct MsvcResult { struct MsvcResult {
full_cl_exe_path string full_cl_exe_path string
exe_path string exe_path string
@ -25,10 +26,10 @@ type RegKey voidptr
// Taken from the windows SDK // Taken from the windows SDK
const ( const (
HKEY_LOCAL_MACHINE = RegKey(0x80000002) hkey_local_machine = RegKey(0x80000002)
KEY_QUERY_VALUE = (0x0001) key_query_value = (0x0001)
KEY_WOW64_32KEY = (0x0200) key_wow64_32key = (0x0200)
KEY_ENUMERATE_SUB_KEYS = (0x0008) key_enumerate_sub_keys = (0x0008)
) )
// Given a root key look for one of the subkeys in 'versions' and get the path // Given a root key look for one of the subkeys in 'versions' and get the path
@ -79,8 +80,8 @@ 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 | rc := C.RegOpenKeyEx(hkey_local_machine, path.to_wide(), 0, key_query_value | key_wow64_32key |
KEY_ENUMERATE_SUB_KEYS, &root_key) key_enumerate_sub_keys, &root_key)
defer { defer {
C.RegCloseKey(root_key) C.RegCloseKey(root_key)
} }

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/const_field_name_snake_case.v:2:2: warning: const names cannot contain uppercase letters, use snake_case instead
1 | const (
2 | Red = 1
| ~~~
3 | )
4 | fn main() { println(Red) }

View File

@ -0,0 +1,4 @@
const (
Red = 1
)
fn main() { println(Red) }

View File

@ -29,8 +29,8 @@ const (
const ( const (
segment_start = 0x400000 segment_start = 0x400000
PLACEHOLDER = 0 placeholder = 0
SEVENS = 0x77777777 sevens = 0x77777777
) )
pub fn (mut g Gen) generate_elf_header() { pub fn (mut g Gen) generate_elf_header() {
@ -74,7 +74,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 = g.buf.len g.code_start_pos = 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(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')
} }

View File

@ -223,7 +223,7 @@ fn (mut g Gen) inc_var(var_name string) {
fn (mut g Gen) jne() int { fn (mut g Gen) jne() int {
g.write16(0x850f) g.write16(0x850f)
pos := g.pos() pos := g.pos()
g.write32(PLACEHOLDER) g.write32(placeholder)
g.println('jne') g.println('jne')
return pos return pos
} }
@ -231,7 +231,7 @@ fn (mut g Gen) jne() int {
fn (mut g Gen) jge() int { fn (mut g Gen) jge() int {
g.write16(0x8d0f) g.write16(0x8d0f)
pos := g.pos() pos := g.pos()
g.write32(PLACEHOLDER) g.write32(placeholder)
g.println('jne') g.println('jne')
return pos return pos
} }
@ -428,7 +428,7 @@ pub fn (mut g Gen) gen_print(s string) {
g.mov(.edi, 1) g.mov(.edi, 1)
str_pos := g.buf.len + 2 str_pos := g.buf.len + 2
g.str_pos << str_pos g.str_pos << str_pos
g.mov64(.rsi, 0) // segment_start + 0x9f) // str pos // PLACEHOLDER g.mov64(.rsi, 0) // segment_start + 0x9f) // str pos // placeholder
g.mov(.edx, s.len) // len g.mov(.edx, s.len) // len
g.syscall() g.syscall()
} }

View File

@ -1232,13 +1232,17 @@ fn (mut p Parser) const_decl() ast.ConstDecl {
comment = p.comment() comment = p.comment()
} }
pos := p.tok.position() pos := p.tok.position()
name := p.prepend_mod(p.check_name()) name := p.check_name()
if util.contains_capital(name) {
p.warn_with_pos('const names cannot contain uppercase letters, use snake_case instead', pos)
}
full_name := p.prepend_mod(name)
// name := p.check_name() // name := p.check_name()
// println('!!const: $name') // println('!!const: $name')
p.check(.assign) p.check(.assign)
expr := p.expr(0) expr := p.expr(0)
field := ast.ConstField{ field := ast.ConstField{
name: name name: full_name
expr: expr expr: expr
pos: pos pos: pos
comment: comment comment: comment

View File

@ -11,7 +11,7 @@ struct TestAliasInStruct {
fn test_import() { fn test_import() {
info := l.Level.info info := l.Level.info
assert os.O_RDONLY == os.O_RDONLY && t.month_days[0] == t.month_days[0] && sha256.size == assert os.o_rdonly == os.o_rdonly && t.month_days[0] == t.month_days[0] && sha256.size ==
sha256.size && math.pi == math.pi && info == .info && sha512.size == sha512.size sha256.size && math.pi == math.pi && info == .info && sha512.size == sha512.size
} }

View File

@ -125,9 +125,9 @@ fn (mut mcache ModFileCacher) mark_folders_as_vmod_free( folders_so_far []string
} }
} }
const ( MOD_FILE_STOP_PATHS = ['.git', '.hg', '.svn', '.v.mod.stop' ] ) const ( mod_file_stop_paths = ['.git', '.hg', '.svn', '.v.mod.stop' ] )
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 mod_file_stop_paths {
if i in files { if i in files {
return true return true
} }

View File

@ -8,7 +8,7 @@ import time
import crypto.md5 import crypto.md5
const ( const (
UnknownAssetTypeError = 'vweb.assets: unknown asset type' unknown_asset_type_error = 'vweb.assets: unknown asset type'
) )
struct AssetManager { struct AssetManager {
@ -164,7 +164,7 @@ fn (mut am AssetManager) add(asset_type, file string) bool {
} else if asset_type == 'js' { } else if asset_type == 'js' {
am.js << asset am.js << asset
} else { } else {
panic('$UnknownAssetTypeError ($asset_type).') panic('$unknown_asset_type_error ($asset_type).')
} }
return true return true
} }
@ -181,7 +181,7 @@ fn (am AssetManager) exists(asset_type, 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('$UnknownAssetTypeError ($asset_type).') panic('$unknown_asset_type_error ($asset_type).')
} }
assets := if asset_type == 'css' { assets := if asset_type == 'css' {
am.css am.css

View File

@ -7,8 +7,8 @@ import os
import strings import strings
const ( const (
STR_START = "sb.write(\'" str_start = "sb.write(\'"
STR_END = "\' ) " str_end = "\' ) "
) )
pub fn compile_template(path string) string { pub fn compile_template(path string) string {
@ -33,7 +33,7 @@ header := \' \' // TODO remove
_ = header _ = header
//footer := \'footer\' //footer := \'footer\'
") ")
s.writeln(STR_START) s.writeln(str_start)
mut in_css := true // false mut in_css := true // false
for _line in lines { for _line in lines {
line := _line.trim_space() line := _line.trim_space()
@ -44,30 +44,30 @@ _ = header
// in_css = false // in_css = false
} }
if line.contains('@if ') { if line.contains('@if ') {
s.writeln(STR_END) s.writeln(str_end)
pos := line.index('@if') or { pos := line.index('@if') or {
continue continue
} }
s.writeln('if ' + line[pos + 4..] + '{') s.writeln('if ' + line[pos + 4..] + '{')
s.writeln(STR_START) s.writeln(str_start)
} }
else if line.contains('@end') { else if line.contains('@end') {
s.writeln(STR_END) s.writeln(str_end)
s.writeln('}') s.writeln('}')
s.writeln(STR_START) s.writeln(str_start)
} }
else if line.contains('@else') { else if line.contains('@else') {
s.writeln(STR_END) s.writeln(str_end)
s.writeln(' } else { ') s.writeln(' } else { ')
s.writeln(STR_START) s.writeln(str_start)
} }
else if line.contains('@for') { else if line.contains('@for') {
s.writeln(STR_END) s.writeln(str_end)
pos := line.index('@for') or { pos := line.index('@for') or {
continue continue
} }
s.writeln('for ' + line[pos + 4..] + '{') s.writeln('for ' + line[pos + 4..] + '{')
s.writeln(STR_START) s.writeln(str_start)
} }
else if !in_css && line.contains('.') && line.ends_with('{') { else if !in_css && line.contains('.') && line.ends_with('{') {
class := line.find_between('.', '{') class := line.find_between('.', '{')
@ -81,8 +81,7 @@ _ = header
s.writeln(line.replace('@', '\x24').replace("'", '"')) s.writeln(line.replace('@', '\x24').replace("'", '"'))
} }
} }
s.writeln(STR_END) s.writeln(str_end)
s.writeln('tmpl_res := sb.str() }') s.writeln('tmpl_res := sb.str() }')
return s.str() return s.str()
} }

View File

@ -13,11 +13,11 @@ import strings
pub const ( pub const (
methods_with_form = ['POST', 'PUT', 'PATCH'] methods_with_form = ['POST', 'PUT', 'PATCH']
method_all = ['GET','POST','PUT','PATCH','DELETE'] method_all = ['GET','POST','PUT','PATCH','DELETE']
HEADER_SERVER = 'Server: VWeb\r\n' header_server = 'Server: VWeb\r\n'
HEADER_CONNECTION_CLOSE = 'Connection: close\r\n' header_connection_close = 'Connection: close\r\n'
HEADERS_CLOSE = '${HEADER_SERVER}${HEADER_CONNECTION_CLOSE}\r\n' headers_close = '${header_server}${header_connection_close}\r\n'
HTTP_404 = 'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n${HEADERS_CLOSE}404 Not Found' http_404 = 'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n${headers_close}404 Not Found'
HTTP_500 = 'HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n${HEADERS_CLOSE}500 Internal Server Error' http_500 = 'HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n${headers_close}500 Internal Server Error'
mime_types = { mime_types = {
'.css': 'text/css; charset=utf-8', '.css': 'text/css; charset=utf-8',
'.gif': 'image/gif', '.gif': 'image/gif',
@ -31,8 +31,8 @@ pub const (
'.svg': 'image/svg+xml', '.svg': 'image/svg+xml',
'.xml': 'text/xml; charset=utf-8' '.xml': 'text/xml; charset=utf-8'
} }
MAX_HTTP_POST_SIZE = 1024 * 1024 max_http_post_size = 1024 * 1024
Default_Port = 8080 default_port = 8080
) )
pub struct Context { pub struct Context {
@ -56,7 +56,7 @@ fn (mut ctx Context) send_response_to_client(mimetype string, res string) bool {
sb.write('\r\nContent-Length: ') sb.write(res.len.str()) sb.write('\r\nContent-Length: ') sb.write(res.len.str())
sb.write(ctx.headers) sb.write(ctx.headers)
sb.write('\r\n') sb.write('\r\n')
sb.write(HEADERS_CLOSE) sb.write(headers_close)
sb.write(res) sb.write(res)
ctx.conn.send_string(sb.str()) or { return false } ctx.conn.send_string(sb.str()) or { return false }
sb.free() sb.free()
@ -78,13 +78,13 @@ pub fn (mut ctx Context) json(s string) {
pub fn (mut ctx Context) redirect(url string) { pub fn (mut ctx Context) redirect(url string) {
if ctx.done { return } if ctx.done { return }
ctx.done = true ctx.done = true
ctx.conn.send_string('HTTP/1.1 302 Found\r\nLocation: ${url}${ctx.headers}\r\n${HEADERS_CLOSE}') or { return } ctx.conn.send_string('HTTP/1.1 302 Found\r\nLocation: ${url}${ctx.headers}\r\n${headers_close}') or { return }
} }
pub fn (mut ctx Context) not_found(s string) { pub fn (mut ctx Context) not_found(s string) {
if ctx.done { return } if ctx.done { return }
ctx.done = true ctx.done = true
ctx.conn.send_string(HTTP_404) or { return } ctx.conn.send_string(http_404) or { return }
} }
pub fn (mut ctx Context) set_cookie(key, val string) { pub fn (mut ctx Context) set_cookie(key, val string) {
@ -147,9 +147,9 @@ pub fn run<T>(port int) {
//message := readall(conn) //message := readall(conn)
//println(message) //println(message)
/* /*
if message.len > MAX_HTTP_POST_SIZE { if message.len > max_http_post_size {
println('message.len = $message.len > MAX_HTTP_POST_SIZE') println('message.len = $message.len > max_http_post_size')
conn.send_string(HTTP_500) or {} conn.send_string(http_500) or {}
conn.close() or {} conn.close() or {}
continue continue
} }
@ -160,7 +160,7 @@ pub fn run<T>(port int) {
/* /*
if lines.len < 2 { if lines.len < 2 {
conn.send_string(HTTP_500) or {} conn.send_string(http_500) or {}
conn.close() or {} conn.close() or {}
continue continue
} }
@ -179,7 +179,7 @@ fn handle_conn<T>(conn net.Socket, app mut 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')
conn.send_string(HTTP_500) or {} conn.send_string(http_500) or {}
conn.close() or {} conn.close() or {}
return return
//continue //continue
@ -272,7 +272,7 @@ fn handle_conn<T>(conn net.Socket, app mut T) {
if static_file != '' && mime_type != '' { if static_file != '' && mime_type != '' {
data := os.read_file(static_file) or { data := os.read_file(static_file) or {
conn.send_string(HTTP_404) or {} conn.send_string(http_404) or {}
return return
} }
app.vweb.send_response_to_client(mime_type, data) app.vweb.send_response_to_client(mime_type, data)
@ -284,7 +284,7 @@ fn handle_conn<T>(conn net.Socket, app mut T) {
println('action=$action') println('action=$action')
} }
app.$action() or { app.$action() or {
conn.send_string(HTTP_404) or {} conn.send_string(http_404) or {}
} }
conn.close() or {} conn.close() or {}
app.reset() app.reset()
@ -374,7 +374,7 @@ fn readall(conn net.Socket) string {
n := C.recv(conn.sockfd, buf, 1024, 0) n := C.recv(conn.sockfd, buf, 1024, 0)
m := conn.crecv(buf, 1024) m := conn.crecv(buf, 1024)
message += string( byteptr(buf), m ) message += string( byteptr(buf), m )
if message.len > MAX_HTTP_POST_SIZE { break } if message.len > max_http_post_size { break }
if n == m { break } if n == m { break }
} }
return message return message