string: change `tos_lit` to `_SLIT` (#7079)

pull/7113/head
yuyi 2020-12-03 23:02:48 +08:00 committed by GitHub
parent b8bb034f91
commit 06eaded6ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 123 additions and 145 deletions

View File

@ -4,6 +4,7 @@
module builtin
import strconv
/*
NB: A V string should be/is immutable from the point of view of
V user programs after it is first created. A V string is
@ -40,15 +41,14 @@ NB: A V string should be/is immutable from the point of view of
time, when used with pure V functions, but fail in strange ways,
when used with modules using C functions (for example os and so on).
*/
pub struct string {
pub:
str byteptr // points to a C style 0 terminated string of bytes.
len int // the length of the .str field, excluding the ending 0 byte. It is always equal to strlen(.str).
str byteptr // points to a C style 0 terminated string of bytes.
len int // the length of the .str field, excluding the ending 0 byte. It is always equal to strlen(.str).
mut:
is_lit int
}
// mut:
// hash_cache int
//
@ -56,9 +56,8 @@ mut:
// .is_lit == 0 => a fresh string, should be freed by autofree
// .is_lit == 1 => a literal string from .rodata, should NOT be freed
// .is_lit == -98761234 => already freed string, protects against double frees.
// ^^^^^^^^^ calling free on these is a bug.
// ^^^^^^^^^ calling free on these is a bug.
// Any other value means that the string has been corrupted.
pub struct ustring {
pub mut:
s string
@ -180,7 +179,6 @@ pub fn (s string) cstr() byteptr {
return clone.str
}
*/
// cstring_to_vstring creates a copy of cstr and turns it into a v string
[unsafe]
pub fn cstring_to_vstring(cstr byteptr) string {
@ -201,10 +199,8 @@ pub fn (s string) replace(rep string, with string) string {
// TODO PERF Allocating ints is expensive. Should be a stack array
// Get locations of all reps within this string
mut idxs := []int{}
defer {
unsafe {
idxs.free()
}
defer {
unsafe {idxs.free()}
}
mut idx := 0
for {
@ -229,7 +225,7 @@ pub fn (s string) replace(rep string, with string) string {
for i := 0; i < s.len; i++ {
if i == cur_idx {
// Reached the location of rep, replace it with "with"
for j in 0..with.len {
for j in 0 .. with.len {
unsafe {
b[b_i] = with[j]
}
@ -242,8 +238,7 @@ pub fn (s string) replace(rep string, with string) string {
if idx_pos < idxs.len {
cur_idx = idxs[idx_pos]
}
}
else {
} else {
// Rep doesnt start here, just copy
unsafe {
b[b_i] = s[i]
@ -272,7 +267,6 @@ fn compare_rep_index(a &RepIndex, b &RepIndex) int {
return 0
}
fn (mut a []RepIndex) sort2() {
a.sort_with_compare(compare_rep_index)
}
@ -283,8 +277,6 @@ fn (a RepIndex) < (b RepIndex) bool {
return a.idx < b.idx
}
*/
pub fn (s string) replace_each(vals []string) string {
if s.len == 0 || vals.len == 0 {
return s
@ -311,9 +303,9 @@ pub fn (s string) replace_each(vals []string) string {
}
// We need to remember both the position in the string,
// and which rep/with pair it refers to.
idxs << RepIndex {
idx:idx
val_idx:rep_i
idxs << RepIndex{
idx: idx
val_idx: rep_i
}
idx += rep.len
new_len += with.len - rep.len
@ -334,7 +326,7 @@ pub fn (s string) replace_each(vals []string) string {
// Reached the location of rep, replace it with "with"
rep := vals[cur_idx.val_idx]
with := vals[cur_idx.val_idx + 1]
for j in 0..with.len {
for j in 0 .. with.len {
unsafe {
b[b_i] = with[j]
}
@ -347,8 +339,7 @@ pub fn (s string) replace_each(vals []string) string {
if idx_pos < idxs.len {
cur_idx = idxs[idx_pos]
}
}
else {
} else {
// Rep doesnt start here, just copy
unsafe {
b[b_i] = s.str[i]
@ -425,11 +416,10 @@ fn (s string) ne(a string) bool {
// s < a
fn (s string) lt(a string) bool {
for i in 0..s.len {
for i in 0 .. s.len {
if i >= a.len || s[i] > a[i] {
return false
}
else if s[i] < a[i] {
} else if s[i] < a[i] {
return true
}
}
@ -461,12 +451,12 @@ fn (s string) add(a string) string {
str: malloc(new_len + 1)
len: new_len
}
for j in 0..s.len {
for j in 0 .. s.len {
unsafe {
res.str[j] = s.str[j]
}
}
for j in 0..a.len {
for j in 0 .. a.len {
unsafe {
res.str[s.len + j] = a.str[j]
}
@ -520,13 +510,11 @@ pub fn (s string) split_nth(delim string, nth int) []string {
if val.starts_with(delim) {
val = val.right(delim.len)
}
was_last := nth > 0 && res.len == nth_1
if was_last {
res << s.right(start)
break
}
res << val
start = i + delim.len
}
@ -548,24 +536,16 @@ pub fn (s string) split_into_lines() []string {
is_lf := unsafe {s.str[i]} == `\n`
is_crlf := i != s.len - 1 && unsafe {s.str[i] == `\r` && s.str[i + 1] == `\n`}
is_eol := is_lf || is_crlf
is_last := if is_crlf {
i == s.len - 2
} else {
i == s.len - 1
}
is_last := if is_crlf { i == s.len - 2 } else { i == s.len - 1 }
if is_eol || is_last {
if is_last && !is_eol {
i++
}
line := s.substr(start, i)
res << line
if is_crlf {
i++
}
start = i + 1
}
}
@ -595,7 +575,7 @@ fn (s string) substr2(start int, _end int, end_max bool) string {
}
pub fn (s string) substr(start int, end int) string {
$if !no_bounds_checking? {
$if !no_bounds_checking ? {
if start > end || start > s.len || end > s.len || start < 0 || end < 0 {
panic('substr($start, $end) out of bounds (len=$s.len)')
}
@ -605,7 +585,7 @@ pub fn (s string) substr(start int, end int) string {
str: malloc(len + 1)
len: len
}
for i in 0..len {
for i in 0 .. len {
unsafe {
res.str[i] = s.str[start + i]
}
@ -618,7 +598,7 @@ pub fn (s string) substr(start int, end int) string {
str: s.str + start
len: len
}
*/
*/
return res
}
@ -663,7 +643,7 @@ fn (s string) index_kmp(p string) int {
if p.len > s.len {
return -1
}
mut prefix := []int{len:p.len}
mut prefix := []int{len: p.len}
mut j := 0
for i := 1; i < p.len; i++ {
for unsafe {p.str[j] != p.str[i]} && j > 0 {
@ -675,7 +655,7 @@ fn (s string) index_kmp(p string) int {
prefix[i] = j
}
j = 0
for i in 0..s.len {
for i in 0 .. s.len {
for unsafe {p.str[j] != s.str[i]} && j > 0 {
j = prefix[j - 1]
}
@ -745,7 +725,7 @@ pub fn (s string) index_after(p string, start int) int {
}
pub fn (s string) index_byte(c byte) int {
for i in 0..s.len {
for i in 0 .. s.len {
if unsafe {s.str[i]} == c {
return i
}
@ -818,7 +798,7 @@ pub fn (s string) starts_with(p string) bool {
if p.len > s.len {
return false
}
for i in 0..p.len {
for i in 0 .. p.len {
if unsafe {s.str[i] != p.str[i]} {
return false
}
@ -830,7 +810,7 @@ pub fn (s string) ends_with(p string) bool {
if p.len > s.len {
return false
}
for i in 0..p.len {
for i in 0 .. p.len {
if p[i] != s[s.len - p.len + i] {
return false
}
@ -842,7 +822,7 @@ pub fn (s string) ends_with(p string) bool {
pub fn (s string) to_lower() string {
unsafe {
mut b := malloc(s.len + 1)
for i in 0..s.len {
for i in 0 .. s.len {
b[i] = byte(C.tolower(s.str[i]))
}
return tos(b, s.len)
@ -850,7 +830,7 @@ pub fn (s string) to_lower() string {
}
pub fn (s string) is_lower() bool {
for i in 0..s.len {
for i in 0 .. s.len {
if s[i] >= `A` && s[i] <= `Z` {
return false
}
@ -861,7 +841,7 @@ pub fn (s string) is_lower() bool {
pub fn (s string) to_upper() string {
unsafe {
mut b := malloc(s.len + 1)
for i in 0..s.len {
for i in 0 .. s.len {
b[i] = byte(C.toupper(s.str[i]))
}
return tos(b, s.len)
@ -869,7 +849,7 @@ pub fn (s string) to_upper() string {
}
pub fn (s string) is_upper() bool {
for i in 0..s.len {
for i in 0 .. s.len {
if s[i] >= `a` && s[i] <= `z` {
return false
}
@ -882,16 +862,16 @@ pub fn (s string) capitalize() string {
return ''
}
return s[0].str().to_upper() + s[1..]
//sl := s.to_lower()
//cap := sl[0].str().to_upper() + sl.right(1)
//return cap
// sl := s.to_lower()
// cap := sl[0].str().to_upper() + sl.right(1)
// return cap
}
pub fn (s string) is_capital() bool {
if s.len == 0 || !(s[0] >= `A` && s[0] <= `Z`) {
return false
}
for i in 1..s.len {
for i in 1 .. s.len {
if s[i] >= `A` && s[i] <= `Z` {
return false
}
@ -953,7 +933,6 @@ pub fn (a []string) to_c() voidptr {
return res
}
*/
pub fn (c byte) is_space() bool {
// 0x0085 is NEXT LINE (NEL)
// 0x00a0 is NO-BREAK SPACE
@ -1010,7 +989,11 @@ pub fn (s string) trim_right(cutset string) string {
for pos >= 0 && s[pos] in cs_arr {
pos--
}
return if pos < 0 { '' } else { s.left(pos + 1) }
return if pos < 0 {
''
} else {
s.left(pos + 1)
}
}
pub fn (s string) trim_prefix(str string) string {
@ -1022,7 +1005,7 @@ pub fn (s string) trim_prefix(str string) string {
pub fn (s string) trim_suffix(str string) string {
if s.ends_with(str) {
return s[..s.len-str.len]
return s[..s.len - str.len]
}
return s
}
@ -1080,15 +1063,13 @@ pub fn (s string) str() string {
}
pub fn (s ustring) str() string {
return s.s
return s.s
}
pub fn (s string) ustring() ustring {
mut res := ustring{
s: s
// runes will have at least s.len elements, save reallocations
// TODO use VLA for small strings?
s: s // runes will have at least s.len elements, save reallocations
// TODO use VLA for small strings?
runes: __new_array(0, s.len, int(sizeof(int)))
}
for i := 0; i < s.len; i++ {
@ -1224,7 +1205,7 @@ pub fn (u ustring) count(substr ustring) int {
}
pub fn (u ustring) substr(_start int, _end int) string {
$if !no_bounds_checking? {
$if !no_bounds_checking ? {
if _start > _end || _start > u.len || _end > u.len || _start < 0 || _end < 0 {
panic('substr($_start, $_end) out of bounds (len=$u.len)')
}
@ -1248,7 +1229,7 @@ pub fn (u ustring) right(pos int) string {
}
fn (s string) at(idx int) byte {
$if !no_bounds_checking? {
$if !no_bounds_checking ? {
if idx < 0 || idx >= s.len {
panic('string index out of range: $idx / $s.len')
}
@ -1259,7 +1240,7 @@ fn (s string) at(idx int) byte {
}
pub fn (u ustring) at(idx int) string {
$if !no_bounds_checking? {
$if !no_bounds_checking ? {
if idx < 0 || idx >= u.len {
panic('string index out of range: $idx / $u.runes.len')
}
@ -1357,8 +1338,7 @@ pub fn (s string) after_char(dot byte) string {
if pos == 0 {
return s
}
return s.right(pos+1)
return s.right(pos + 1)
}
// fn (s []string) substr(a, b int) string {
@ -1380,7 +1360,7 @@ pub fn (a []string) join(del string) string {
mut idx := 0
// Go thru every string and copy its every char one by one
for i, val in a {
for j in 0..val.len {
for j in 0 .. val.len {
unsafe {
res.str[idx] = val.str[j]
}
@ -1388,7 +1368,7 @@ pub fn (a []string) join(del string) string {
}
// Add del if it's not last
if i != a.len - 1 {
for k in 0..del.len {
for k in 0 .. del.len {
unsafe {
res.str[idx] = del.str[k]
}
@ -1455,10 +1435,8 @@ pub fn (s string) bytes() []byte {
if s.len == 0 {
return []
}
mut buf := []byte{ len:s.len }
unsafe {
C.memcpy(buf.data, s.str, s.len)
}
mut buf := []byte{len: s.len}
unsafe {C.memcpy(buf.data, s.str, s.len)}
return buf
}
@ -1498,20 +1476,21 @@ pub fn (s string) fields() []string {
//
// Example:
// st := 'Hello there,
// |this is a string,
// | Everything before the first | is removed'.strip_margin()
// |this is a string,
// | Everything before the first | is removed'.strip_margin()
// Returns:
// Hello there,
// this is a string,
// Everything before the first | is removed
// Everything before the first | is removed
pub fn (s string) strip_margin() string {
return s.strip_margin_custom(`|`)
return s.strip_margin_custom(`|`)
}
pub fn (s string) strip_margin_custom(del byte) string {
mut sep := del
if sep.is_space() {
eprintln("Warning: `strip_margin` cannot use white-space as a delimiter")
eprintln(" Defaulting to `|`")
eprintln('Warning: `strip_margin` cannot use white-space as a delimiter')
eprintln(' Defaulting to `|`')
sep = `|`
}
// don't know how much space the resulting string will be, but the max it
@ -1525,14 +1504,13 @@ pub fn (s string) strip_margin_custom(del byte) string {
}
count++
// CRLF
if s[i] == `\r` && i < s.len - 1 && s[i+1] == `\n` {
if s[i] == `\r` && i < s.len - 1 && s[i + 1] == `\n` {
unsafe {
ret[count] = s[i+1]
ret[count] = s[i + 1]
}
count++
i++
}
for s[i] != sep {
i++
if i >= s.len {

View File

@ -92,7 +92,7 @@ fn (mut g Gen) gen_str_for_option(typ table.Type, styp string, str_fn_name strin
g.auto_str_funcs.writeln('string indent_${str_fn_name}($styp it, int indent_count) {')
g.auto_str_funcs.writeln('\tstring res;')
g.auto_str_funcs.writeln('\tif (it.is_none) {')
g.auto_str_funcs.writeln('\t\tres = tos_lit("none");')
g.auto_str_funcs.writeln('\t\tres = _SLIT("none");')
g.auto_str_funcs.writeln('\t} else if (it.ok) {')
if typ.is_string() {
g.auto_str_funcs.writeln('\t\tres = _STR("\'%.*s\\000\'", 2, ${parent_str_fn_name}(*($sym_name*)it.data));')
@ -120,9 +120,9 @@ fn (mut g Gen) gen_str_for_alias(info table.Alias, styp string, str_fn_name stri
g.auto_str_funcs.writeln('static string ${str_fn_name}($styp it) { return indent_${str_fn_name}(it, 0); }')
g.type_definitions.writeln('static string indent_${str_fn_name}($styp it, int indent_count); // auto')
g.auto_str_funcs.writeln('static string indent_${str_fn_name}($styp it, int indent_count) {')
g.auto_str_funcs.writeln('\tstring indents = tos_lit("");')
g.auto_str_funcs.writeln('\tstring indents = _SLIT("");')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < indent_count; ++i) {')
g.auto_str_funcs.writeln('\t\tindents = string_add(indents, tos_lit(" "));')
g.auto_str_funcs.writeln('\t\tindents = string_add(indents, _SLIT(" "));')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\treturn _STR("%.*s\\000${clean_type_v_type_name}(%.*s\\000)", 3, indents, ${parent_str_fn_name}(it));')
g.auto_str_funcs.writeln('}')
@ -156,7 +156,7 @@ fn (mut g Gen) gen_str_for_array(info table.Array, styp string, str_fn_name stri
g.type_definitions.writeln('static string indent_${str_fn_name}($styp a, int indent_count); // auto')
g.auto_str_funcs.writeln('static string indent_${str_fn_name}($styp a, int indent_count) {')
g.auto_str_funcs.writeln('\tstrings__Builder sb = strings__new_builder(a.len * 10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("["));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("["));')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < a.len; ++i) {')
g.auto_str_funcs.writeln('\t\t$field_styp it = (*($field_styp*)array_get(a, i));')
if sym.kind == .struct_ && !sym_has_str_method {
@ -185,10 +185,10 @@ fn (mut g Gen) gen_str_for_array(info table.Array, styp string, str_fn_name stri
g.auto_str_funcs.writeln('\t\tstring_free(&x);')
}
g.auto_str_funcs.writeln('\t\tif (i < a.len-1) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, tos_lit(", "));')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _SLIT(", "));')
g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("]"));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("]"));')
g.auto_str_funcs.writeln('\tstring res = strings__Builder_str(&sb);')
g.auto_str_funcs.writeln('\tstrings__Builder_free(&sb);')
// g.auto_str_funcs.writeln('\treturn strings__Builder_str(&sb);')
@ -221,7 +221,7 @@ fn (mut g Gen) gen_str_for_array_fixed(info table.ArrayFixed, styp string, str_f
g.type_definitions.writeln('static string indent_${str_fn_name}($styp a, int indent_count); // auto')
g.auto_str_funcs.writeln('static string indent_${str_fn_name}($styp a, int indent_count) {')
g.auto_str_funcs.writeln('\tstrings__Builder sb = strings__new_builder($info.size * 10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("["));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("["));')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < $info.size; ++i) {')
if sym.kind == .struct_ && !sym_has_str_method {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}(a[i], indent_count));')
@ -239,10 +239,10 @@ fn (mut g Gen) gen_str_for_array_fixed(info table.ArrayFixed, styp string, str_f
}
}
g.auto_str_funcs.writeln('\t\tif (i < ${info.size - 1}) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, tos_lit(", "));')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _SLIT(", "));')
g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("]"));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("]"));')
g.auto_str_funcs.writeln('\treturn strings__Builder_str(&sb);')
g.auto_str_funcs.writeln('}')
}
@ -264,12 +264,12 @@ fn (mut g Gen) gen_str_for_map(info table.Map, styp string, str_fn_name string)
g.type_definitions.writeln('static string indent_${str_fn_name}($styp m, int indent_count); // auto')
g.auto_str_funcs.writeln('static string indent_${str_fn_name}($styp m, int indent_count) { /* gen_str_for_map */')
g.auto_str_funcs.writeln('\tstrings__Builder sb = strings__new_builder(m.key_values.len*10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("{"));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("{"));')
g.auto_str_funcs.writeln('\tfor (unsigned int i = 0; i < m.key_values.len; ++i) {')
g.auto_str_funcs.writeln('\t\tif (m.key_values.keys[i].str == 0) { continue; }')
g.auto_str_funcs.writeln('\t\tstring key = (*(string*)DenseArray_get(m.key_values, i));')
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("\'%.*s\\000\'", 2, key));')
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, tos_lit(": "));')
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _SLIT(": "));')
g.auto_str_funcs.write('\t$val_styp it = (*($val_styp*)map_get(')
g.auto_str_funcs.write('m, (*(string*)DenseArray_get(m.key_values, i))')
g.auto_str_funcs.write(', ')
@ -284,10 +284,10 @@ fn (mut g Gen) gen_str_for_map(info table.Map, styp string, str_fn_name string)
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}(it));')
}
g.auto_str_funcs.writeln('\t\tif (i != m.key_values.len-1) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, tos_lit(", "));')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _SLIT(", "));')
g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("}"));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("}"));')
g.auto_str_funcs.writeln('\treturn strings__Builder_str(&sb);')
g.auto_str_funcs.writeln('}')
}
@ -296,14 +296,14 @@ fn (mut g Gen) gen_str_for_varg(styp string, str_fn_name string, has_str_method
g.definitions.writeln('static string varg_${str_fn_name}(varg_$styp it); // auto')
g.auto_str_funcs.writeln('static string varg_${str_fn_name}(varg_$styp it) {')
g.auto_str_funcs.writeln('\tstrings__Builder sb = strings__new_builder(it.len);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("["));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("["));')
g.auto_str_funcs.writeln('\tfor(int i=0; i<it.len; ++i) {')
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${str_fn_name}(it.args[i]));')
g.auto_str_funcs.writeln('\t\tif (i < it.len-1) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, tos_lit(", "));')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _SLIT(", "));')
g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("]"));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("]"));')
g.auto_str_funcs.writeln('\treturn strings__Builder_str(&sb);')
g.auto_str_funcs.writeln('}')
}
@ -318,7 +318,7 @@ fn (mut g Gen) gen_str_for_multi_return(info table.MultiReturn, styp string, str
g.type_definitions.writeln('static string ${str_fn_name}($styp a); // auto')
g.auto_str_funcs.writeln('static string ${str_fn_name}($styp a) {')
g.auto_str_funcs.writeln('\tstrings__Builder sb = strings__new_builder($info.types.len * 10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit("("));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("("));')
for i, typ in info.types {
sym := g.table.get_type_symbol(typ)
field_styp := g.typ(typ)
@ -347,10 +347,10 @@ fn (mut g Gen) gen_str_for_multi_return(info table.MultiReturn, styp string, str
}
}
if i != info.types.len - 1 {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit(", "));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT(", "));')
}
}
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos_lit(")"));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT(")"));')
g.auto_str_funcs.writeln('\treturn strings__Builder_str(&sb);')
g.auto_str_funcs.writeln('}')
}
@ -387,9 +387,9 @@ fn (mut g Gen) gen_str_for_struct(info table.Struct, styp string, str_fn_name st
}
clean_struct_v_type_name = util.strip_main_name(clean_struct_v_type_name)
// generate ident / indent length = 4 spaces
g.auto_str_funcs.writeln('\tstring indents = tos_lit("");')
g.auto_str_funcs.writeln('\tstring indents = _SLIT("");')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < indent_count; ++i) {')
g.auto_str_funcs.writeln('\t\tindents = string_add(indents, tos_lit(" "));')
g.auto_str_funcs.writeln('\t\tindents = string_add(indents, _SLIT(" "));')
g.auto_str_funcs.writeln('\t}')
if info.fields.len == 0 {
g.auto_str_funcs.write('\treturn _SLIT("$clean_struct_v_type_name{}");')
@ -481,9 +481,9 @@ fn (mut g Gen) gen_str_for_enum(info table.Enum, styp string, str_fn_name string
} else if info.is_multi_allowed {
seen << val
}
g.auto_str_funcs.writeln('\t\tcase ${s}_$val: return tos_lit("$val");')
g.auto_str_funcs.writeln('\t\tcase ${s}_$val: return _SLIT("$val");')
}
g.auto_str_funcs.writeln('\t\tdefault: return tos_lit("unknown enum value");')
g.auto_str_funcs.writeln('\t\tdefault: return _SLIT("unknown enum value");')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('}')
}
@ -526,7 +526,7 @@ fn (mut g Gen) gen_str_for_union_sum_type(info table.SumType, styp string, str_f
}
g.auto_str_funcs.writeln('));')
}
g.auto_str_funcs.writeln('\t\tdefault: return tos_lit("unknown sum type value");')
g.auto_str_funcs.writeln('\t\tdefault: return _SLIT("unknown sum type value");')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('}')
}

View File

@ -509,7 +509,7 @@ fn (mut g Gen) register_chan_pop_optional_call(opt_el_type string, styp string)
static inline $opt_el_type __Option_${styp}_popval($styp ch) {
$opt_el_type _tmp;
if (sync__Channel_try_pop_priv(ch, _tmp.data, false)) {
Option _tmp2 = v_error(tos_lit("channel closed"));
Option _tmp2 = v_error(_SLIT("channel closed"));
return *($opt_el_type*)&_tmp2;
}
_tmp.ok = true; _tmp.is_none = false; _tmp.v_error = (string){.str=(byteptr)""}; _tmp.ecode = 0;
@ -1369,9 +1369,9 @@ fn cestring(s string) string {
return s.replace('\\', '\\\\').replace('"', "\'")
}
// ctoslit returns a 'tos_lit("$s")' call, where s is properly escaped.
// ctoslit returns a '_SLIT("$s")' call, where s is properly escaped.
fn ctoslit(s string) string {
return 'tos_lit("' + cestring(s) + '")'
return '_SLIT("' + cestring(s) + '")'
}
fn (mut g Gen) gen_attrs(attrs []table.Attr) {
@ -1414,7 +1414,7 @@ fn (mut g Gen) gen_assert_stmt(original_assert_statement ast.AssertStmt) {
g.writeln(' {} else {')
metaname_panic := g.gen_assert_metainfo(a)
g.writeln('\t__print_assert_failure(&$metaname_panic);')
g.writeln('\tv_panic(tos_lit("Assertion failed..."));')
g.writeln('\tv_panic(_SLIT("Assertion failed..."));')
g.writeln('\texit(1);')
g.writeln('}')
}
@ -1449,7 +1449,7 @@ fn (mut g Gen) gen_assert_metainfo(a ast.AssertStmt) string {
g.writeln(';')
}
ast.CallExpr {
g.writeln('\t${metaname}.op = tos_lit("call");')
g.writeln('\t${metaname}.op = _SLIT("call");')
}
else {}
}
@ -2648,7 +2648,7 @@ fn (mut g Gen) type_name(type_ table.Type) {
typ = g.cur_generic_type
}
s := g.table.type_to_str(typ)
g.write('tos_lit("${util.strip_main_name(s)}")')
g.write('_SLIT("${util.strip_main_name(s)}")')
}
fn (mut g Gen) typeof_expr(node ast.TypeOf) {
@ -2663,7 +2663,7 @@ fn (mut g Gen) typeof_expr(node ast.TypeOf) {
} else if sym.kind == .array_fixed {
fixed_info := sym.info as table.ArrayFixed
typ_name := g.table.get_type_name(fixed_info.elem_type)
g.write('tos_lit("[$fixed_info.size]${util.strip_main_name(typ_name)}")')
g.write('_SLIT("[$fixed_info.size]${util.strip_main_name(typ_name)}")')
} else if sym.kind == .function {
info := sym.info as table.FnType
fn_info := info.func
@ -2678,11 +2678,11 @@ fn (mut g Gen) typeof_expr(node ast.TypeOf) {
if fn_info.return_type != table.void_type {
repr += ' ${util.strip_main_name(g.table.get_type_name(fn_info.return_type))}'
}
g.write('tos_lit("$repr")')
g.write('_SLIT("$repr")')
} else if node.expr_type.has_flag(.variadic) {
g.write('tos_lit("...${util.strip_main_name(sym.name)}")')
g.write('_SLIT("...${util.strip_main_name(sym.name)}")')
} else {
g.write('tos_lit("${util.strip_main_name(sym.name)}")')
g.write('_SLIT("${util.strip_main_name(sym.name)}")')
}
}
@ -4450,7 +4450,7 @@ fn (mut g Gen) gen_map_equality_fn(left table.Type) string {
g.definitions.writeln('\t\t$value_typ v = (*($value_typ*)map_get(a, k, &($value_typ[]){ 0 }));')
}
match value_sym.kind {
.string { g.definitions.writeln('\t\tif (!map_exists(b, k) || string_ne((*($value_typ*)map_get(b, k, &($value_typ[]){tos_lit("")})), v)) {') }
.string { g.definitions.writeln('\t\tif (!map_exists(b, k) || string_ne((*($value_typ*)map_get(b, k, &($value_typ[]){_SLIT("")})), v)) {') }
.function { g.definitions.writeln('\t\tif (!map_exists(b, k) || (*(voidptr*)map_get(b, k, &(voidptr[]){ 0 })) != v) {') }
else { g.definitions.writeln('\t\tif (!map_exists(b, k) || (*($value_typ*)map_get(b, k, &($value_typ[]){ 0 })) != v) {') }
}
@ -5336,7 +5336,7 @@ fn (mut g Gen) type_default(typ_ table.Type) string {
/*
return match typ {
'bool', 'i8', 'i16', 'i64', 'u16', 'u32', 'u64', 'byte', 'int', 'rune', 'byteptr', 'voidptr' {'0'}
'string'{ 'tos_lit("")'}
'string'{ '_SLIT("")'}
'f32'{ '0.0'}
'f64'{ '0.0'}
else { '{0} '}
@ -5543,11 +5543,11 @@ fn (mut g Gen) gen_str_default(sym table.TypeSymbol, styp string, str_fn_name st
g.type_definitions.writeln('string ${str_fn_name}($styp it); // auto')
g.auto_str_funcs.writeln('string ${str_fn_name}($styp it) {')
if convertor == 'bool' {
g.auto_str_funcs.writeln('\tstring tmp1 = string_add(tos_lit("${styp}("), ($convertor)it ? tos_lit("true") : tos_lit("false"));')
g.auto_str_funcs.writeln('\tstring tmp1 = string_add(_SLIT("${styp}("), ($convertor)it ? _SLIT("true") : _SLIT("false"));')
} else {
g.auto_str_funcs.writeln('\tstring tmp1 = string_add(tos_lit("${styp}("), tos3(${typename_}_str(($convertor)it).str));')
g.auto_str_funcs.writeln('\tstring tmp1 = string_add(_SLIT("${styp}("), tos3(${typename_}_str(($convertor)it).str));')
}
g.auto_str_funcs.writeln('\tstring tmp2 = string_add(tmp1, tos_lit(")"));')
g.auto_str_funcs.writeln('\tstring tmp2 = string_add(tmp1, _SLIT(")"));')
g.auto_str_funcs.writeln('\tstring_free(&tmp1);')
g.auto_str_funcs.writeln('\treturn tmp2;')
g.auto_str_funcs.writeln('}')
@ -5773,7 +5773,7 @@ fn (mut g Gen) array_init(it ast.ArrayInit) {
g.write('})')
} else if it.has_len && it.elem_type == table.string_type {
g.write('&($elem_type_str[]){')
g.write('tos_lit("")')
g.write('_SLIT("")')
g.write('})')
} else {
g.write('0)')

View File

@ -267,7 +267,7 @@ static void* g_live_info = NULL;
//============================== HELPER C MACROS =============================*/
//#define tos4(s, slen) ((string){.str=(s), .len=(slen)})
#define _SLIT(s) ((string){.str=(byteptr)(s), .len=(strlen(s))})
#define _SLIT(s) ((string){.str=(byteptr)(s), .len=(strlen(s)), .is_lit=1})
#define _PUSH_MANY(arr, val, tmp, tmp_typ) {tmp_typ tmp = (val); array_push_many(arr, tmp.data, tmp.len);}
#define _IN(typ, val, arr) array_##typ##_contains(arr, val)
#define _IN_MAP(val, m) map_exists(m, val)

View File

@ -149,12 +149,12 @@ pub fn (mut g Gen) write_tests_main() {
g.writeln('')
all_tfuncs := g.get_all_test_function_names()
if g.pref.is_stats {
g.writeln('\tmain__BenchedTests bt = main__start_testing($all_tfuncs.len, tos_lit("$g.pref.path"));')
g.writeln('\tmain__BenchedTests bt = main__start_testing($all_tfuncs.len, _SLIT("$g.pref.path"));')
}
for t in all_tfuncs {
g.writeln('')
if g.pref.is_stats {
g.writeln('\tmain__BenchedTests_testing_step_start(&bt, tos_lit("$t"));')
g.writeln('\tmain__BenchedTests_testing_step_start(&bt, _SLIT("$t"));')
}
g.writeln('\tif (!setjmp(g_jump_buffer)) ${t}();')
if g.pref.is_stats {

View File

@ -89,7 +89,7 @@ fn (mut g Gen) comptime_call(node ast.ComptimeCall) {
if j > 0 {
g.write(' else ')
}
g.write('if (string_eq($node.method_name, tos_lit("$method.name"))) ')
g.write('if (string_eq($node.method_name, _SLIT("$method.name"))) ')
g.write('${util.no_dots(node.sym.name)}_${method.name}($amp ')
g.expr(node.left)
g.writeln(');')
@ -105,7 +105,7 @@ fn cgen_attrs(attrs []table.Attr) []string {
if attr.arg.len > 0 {
s += ': $attr.arg'
}
res << 'tos_lit("$s")'
res << '_SLIT("$s")'
}
return res
}
@ -113,10 +113,10 @@ fn cgen_attrs(attrs []table.Attr) []string {
fn (mut g Gen) comp_at(node ast.AtExpr) {
if node.kind == .vmod_file {
val := cnewlines(node.val.replace('\r', '')).replace('\\', '\\\\')
g.write('tos_lit("$val")')
g.write('_SLIT("$val")')
} else {
val := node.val.replace('\\', '\\\\')
g.write('tos_lit("$val")')
g.write('_SLIT("$val")')
}
}
@ -232,7 +232,7 @@ fn (mut g Gen) comp_for(node ast.CompFor) {
g.writeln('{ // 2comptime: \$for $node.val_var in ${sym.name}($node.kind.str()) {')
// vweb_result_type := table.new_type(g.table.find_type_idx('vweb.Result'))
mut i := 0
// g.writeln('string method = tos_lit("");')
// g.writeln('string method = _SLIT("");')
if node.kind == .methods {
mut methods := sym.methods.filter(it.attrs.len == 0) // methods without attrs first
methods_with_attrs := sym.methods.filter(it.attrs.len > 0) // methods with attrs second
@ -249,7 +249,7 @@ fn (mut g Gen) comp_for(node ast.CompFor) {
*/
g.comp_for_method = method.name
g.writeln('\t// method $i')
g.writeln('\t${node.val_var}.name = tos_lit("$method.name");')
g.writeln('\t${node.val_var}.name = _SLIT("$method.name");')
if method.attrs.len == 0 {
g.writeln('\t${node.val_var}.attrs = __new_array_with_default(0, 0, sizeof(string), 0);')
} else {
@ -317,7 +317,7 @@ fn (mut g Gen) comp_for(node ast.CompFor) {
}
for field in fields {
g.writeln('\t// field $i')
g.writeln('\t${node.val_var}.name = tos_lit("$field.name");')
g.writeln('\t${node.val_var}.name = _SLIT("$field.name");')
if field.attrs.len == 0 {
g.writeln('\t${node.val_var}.attrs = __new_array_with_default(0, 0, sizeof(string), 0);')
} else {
@ -326,7 +326,7 @@ fn (mut g Gen) comp_for(node ast.CompFor) {
attrs.join(', ') + '}));')
}
// field_sym := g.table.get_type_symbol(field.typ)
// g.writeln('\t${node.val_var}.typ = tos_lit("$field_sym.name");')
// g.writeln('\t${node.val_var}.typ = _SLIT("$field_sym.name");')
styp := field.typ
g.writeln('\t${node.val_var}.typ = $styp;')
g.writeln('\t${node.val_var}.is_pub = $field.is_pub;')

View File

@ -173,7 +173,7 @@ fn (mut g Gen) decode_array(value_type table.Type) string {
}
return '
if(!cJSON_IsArray(root)) {
Option err = v_error( string_add(tos_lit("Json element is not an array: "), tos2(cJSON_PrintUnformatted(root))) );
Option err = v_error( string_add(_SLIT("Json element is not an array: "), tos2(cJSON_PrintUnformatted(root))) );
return *(Option_array_$styp *)&err;
}
res = __new_array(0, 0, sizeof($styp));
@ -216,7 +216,7 @@ fn (mut g Gen) decode_map(key_type table.Type, value_type table.Type) string {
}
return '
if(!cJSON_IsObject(root)) {
Option err = v_error( string_add(tos_lit("Json element is not an object: "), tos2(cJSON_PrintUnformatted(root))) );
Option err = v_error( string_add(_SLIT("Json element is not an object: "), tos2(cJSON_PrintUnformatted(root))) );
return *(Option_map_${styp}_$styp_v *)&err;
}
res = new_map_1(sizeof($styp_v));

View File

@ -25,7 +25,7 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) {
g.write('${dbtype}__DB $db_name = ')
g.expr(node.db_expr)
g.writeln(';')
g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt($db_name, tos_lit("')
g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt($db_name, _SLIT("')
if node.kind == .insert {
g.write('INSERT INTO `${util.strip_mod_name(node.table_name)}` (')
} else if node.kind == .update {
@ -124,7 +124,7 @@ fn (mut g Gen) sql_select_expr(node ast.SqlExpr) {
if node.has_where {
sql_query += ' WHERE '
}
// g.write('${dbtype}__DB_q_int(*(${dbtype}__DB*)${node.db_var_name}.data, tos_lit("$sql_query')
// g.write('${dbtype}__DB_q_int(*(${dbtype}__DB*)${node.db_var_name}.data, _SLIT("$sql_query')
g.sql_stmt_name = g.new_tmp_var()
db_name := g.new_tmp_var()
g.writeln('\n\t// sql select')
@ -132,8 +132,8 @@ fn (mut g Gen) sql_select_expr(node ast.SqlExpr) {
g.write('${dbtype}__DB $db_name = ') // $node.db_var_name;')
g.expr(node.db_expr)
g.writeln(';')
// g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt(*(${dbtype}__DB*)${node.db_var_name}.data, tos_lit("$sql_query')
g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt($db_name, tos_lit("')
// g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt(*(${dbtype}__DB*)${node.db_var_name}.data, _SLIT("$sql_query')
g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt($db_name, _SLIT("')
g.write(sql_query)
if node.has_where && node.where_expr is ast.InfixExpr {
g.expr_to_sql(node.where_expr)

View File

@ -120,7 +120,7 @@ string _STR_TMP(const char *fmt, ...) {
fn (mut g Gen) string_literal(node ast.StringLiteral) {
if node.is_raw {
escaped_val := util.smart_quote(node.val, true)
g.write('tos_lit("$escaped_val")')
g.write('_SLIT("$escaped_val")')
return
}
escaped_val := util.smart_quote(node.val, false)
@ -135,7 +135,7 @@ fn (mut g Gen) string_literal(node ast.StringLiteral) {
// g.write('tos4("$escaped_val", strlen("$escaped_val"))')
// g.write('tos4("$escaped_val", $it.val.len)')
// g.write('_SLIT("$escaped_val")')
g.write('tos_lit("$escaped_val")')
g.write('_SLIT("$escaped_val")')
}
}
@ -157,7 +157,7 @@ fn (mut g Gen) string_inter_literal_sb_optimized(call_expr ast.CallExpr) {
// }
g.write('strings__Builder_write(&')
g.expr(call_expr.left)
g.write(', tos_lit("')
g.write(', _SLIT("')
g.write(escaped_val)
g.writeln('"));')
//

View File

@ -1,6 +1,6 @@
num := 1 string := 'Hello'
num := 1 str := 'Hello'
num
string
str
===output===
1
Hello