all: add strings.Builder.write_string and use write_string instead of write (#8892)

pull/8899/head
zakuro 2021-02-22 20:18:11 +09:00 committed by GitHub
parent 36a6bc270c
commit f54c1a5cc2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 402 additions and 397 deletions

View File

@ -49,27 +49,27 @@ fn (context Context) footer() string {
fn (context Context) file2v(bname string, fbytes []byte, bn_max int) string { fn (context Context) file2v(bname string, fbytes []byte, bn_max int) string {
mut sb := strings.new_builder(1000) mut sb := strings.new_builder(1000)
bn_diff_len := bn_max - bname.len bn_diff_len := bn_max - bname.len
sb.write('\t${bname}_len' + ' '.repeat(bn_diff_len - 4) + ' = $fbytes.len\n') sb.write_string('\t${bname}_len' + ' '.repeat(bn_diff_len - 4) + ' = $fbytes.len\n')
fbyte := fbytes[0] fbyte := fbytes[0]
bnmae_line := '\t$bname' + ' '.repeat(bn_diff_len) + ' = [byte($fbyte), ' bnmae_line := '\t$bname' + ' '.repeat(bn_diff_len) + ' = [byte($fbyte), '
sb.write(bnmae_line) sb.write_string(bnmae_line)
mut line_len := bnmae_line.len + 3 mut line_len := bnmae_line.len + 3
for i := 1; i < fbytes.len; i++ { for i := 1; i < fbytes.len; i++ {
b := int(fbytes[i]).str() b := int(fbytes[i]).str()
if line_len > 94 { if line_len > 94 {
sb.go_back(1) sb.go_back(1)
sb.write('\n\t\t') sb.write_string('\n\t\t')
line_len = 8 line_len = 8
} }
if i == fbytes.len - 1 { if i == fbytes.len - 1 {
sb.write(b) sb.write_string(b)
line_len += b.len line_len += b.len
} else { } else {
sb.write('$b, ') sb.write_string('$b, ')
line_len += b.len + 2 line_len += b.len + 2
} }
} }
sb.write(']!\n') sb.write_string(']!\n')
return sb.str() return sb.str()
} }

View File

@ -490,17 +490,17 @@ pub fn (a &array) free() {
// => '["a", "b", "c"]'. // => '["a", "b", "c"]'.
pub fn (a []string) str() string { pub fn (a []string) str() string {
mut sb := strings.new_builder(a.len * 3) mut sb := strings.new_builder(a.len * 3)
sb.write('[') sb.write_string('[')
for i in 0 .. a.len { for i in 0 .. a.len {
val := a[i] val := a[i]
sb.write("'") sb.write_string("'")
sb.write(val) sb.write_string(val)
sb.write("'") sb.write_string("'")
if i < a.len - 1 { if i < a.len - 1 {
sb.write(', ') sb.write_string(', ')
} }
} }
sb.write(']') sb.write_string(']')
return sb.str() return sb.str()
} }

View File

@ -142,7 +142,7 @@ fn pretty_description(s string, indent_len int) string {
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))
for k, line in s.split('\n') { for k, line in s.split('\n') {
if k != 0 { if k != 0 {
acc.write('\n$indent') acc.write_string('\n$indent')
} }
mut i := chars_per_line - 2 mut i := chars_per_line - 2
mut j := 0 mut j := 0
@ -152,16 +152,16 @@ fn pretty_description(s string, indent_len int) string {
} }
// indent was already done the first iteration // indent was already done the first iteration
if j != 0 { if j != 0 {
acc.write(indent) acc.write_string(indent)
} }
acc.writeln(line[j..i].trim_space()) acc.writeln(line[j..i].trim_space())
j = i j = i
} }
// We need this even though it should never happen // We need this even though it should never happen
if j != 0 { if j != 0 {
acc.write(indent) acc.write_string(indent)
} }
acc.write(line[j..].trim_space()) acc.write_string(line[j..].trim_space())
} }
return acc.str() return acc.str()
} }

View File

@ -4,12 +4,12 @@ import strings
fn generate_temp_html() string { fn generate_temp_html() string {
mut temp_html := strings.new_builder(200) mut temp_html := strings.new_builder(200)
temp_html.write('<!doctype html><html><head><title>Giant String</title></head><body>') temp_html.write_string('<!doctype html><html><head><title>Giant String</title></head><body>')
for counter := 0; counter < 4; counter++ { for counter := 0; counter < 4; counter++ {
temp_html.write("<div id='name_$counter' ") temp_html.write_string("<div id='name_$counter' ")
temp_html.write("class='several-$counter'>Look at $counter</div>") temp_html.write_string("class='several-$counter'>Look at $counter</div>")
} }
temp_html.write('</body></html>') temp_html.write_string('</body></html>')
return temp_html.str() return temp_html.str()
} }

View File

@ -23,11 +23,11 @@ fn test_split_parse() {
fn test_giant_string() { fn test_giant_string() {
mut temp_html := strings.new_builder(200) mut temp_html := strings.new_builder(200)
mut parser := Parser{} mut parser := Parser{}
temp_html.write('<!doctype html><html><head><title>Giant String</title></head><body>') temp_html.write_string('<!doctype html><html><head><title>Giant String</title></head><body>')
for counter := 0; counter < 2000; counter++ { for counter := 0; counter < 2000; counter++ {
temp_html.write("<div id='name_$counter' class='several-$counter'>Look at $counter</div>") temp_html.write_string("<div id='name_$counter' class='several-$counter'>Look at $counter</div>")
} }
temp_html.write('</body></html>') temp_html.write_string('</body></html>')
parser.parse_html(temp_html.str()) parser.parse_html(temp_html.str())
assert parser.tags.len == 4009 assert parser.tags.len == 4009
} }

View File

@ -38,35 +38,35 @@ pub fn (tag Tag) text() string {
return '\n' return '\n'
} }
mut text_str := strings.new_builder(200) mut text_str := strings.new_builder(200)
text_str.write(tag.content.replace('\n', '')) text_str.write_string(tag.content.replace('\n', ''))
for child in tag.children { for child in tag.children {
text_str.write(child.text()) text_str.write_string(child.text())
} }
return text_str.str() return text_str.str()
} }
pub fn (tag &Tag) str() string { pub fn (tag &Tag) str() string {
mut html_str := strings.new_builder(200) mut html_str := strings.new_builder(200)
html_str.write('<$tag.name') html_str.write_string('<$tag.name')
for key, value in tag.attributes { for key, value in tag.attributes {
html_str.write(' $key') html_str.write_string(' $key')
if value.len > 0 { if value.len > 0 {
html_str.write('="$value"') html_str.write_string('="$value"')
} }
} }
html_str.write(if tag.closed && tag.close_type == .in_name { html_str.write_string(if tag.closed && tag.close_type == .in_name {
'/>' '/>'
} else { } else {
'>' '>'
}) })
html_str.write(tag.content) html_str.write_string(tag.content)
if tag.children.len > 0 { if tag.children.len > 0 {
for child in tag.children { for child in tag.children {
html_str.write(child.str()) html_str.write_string(child.str())
} }
} }
if !tag.closed || tag.close_type == .new_tag { if !tag.closed || tag.close_type == .new_tag {
html_str.write('</$tag.name>') html_str.write_string('</$tag.name>')
} }
return html_str.str() return html_str.str()
} }

View File

@ -65,7 +65,7 @@ pub fn decode(text string) string {
break break
} }
cscanner.skip_crlf() cscanner.skip_crlf()
sb.write(cscanner.read_chunk(csize)) sb.write_string(cscanner.read_chunk(csize))
cscanner.skip_crlf() cscanner.skip_crlf()
} }
cscanner.skip_crlf() cscanner.skip_crlf()

View File

@ -204,12 +204,12 @@ pub fn (c &Cookie) str() string {
// see RFC 6265 Sec 4.1. // see RFC 6265 Sec 4.1.
extra_cookie_length := 110 extra_cookie_length := 110
mut b := strings.new_builder(c.name.len + c.value.len + c.domain.len + c.path.len + extra_cookie_length) mut b := strings.new_builder(c.name.len + c.value.len + c.domain.len + c.path.len + extra_cookie_length)
b.write(c.name) b.write_string(c.name)
b.write('=') b.write_string('=')
b.write(sanitize_cookie_value(c.value)) b.write_string(sanitize_cookie_value(c.value))
if c.path.len > 0 { if c.path.len > 0 {
b.write('; path=') b.write_string('; path=')
b.write(sanitize_cookie_path(c.path)) b.write_string(sanitize_cookie_path(c.path))
} }
if c.domain.len > 0 { if c.domain.len > 0 {
if valid_cookie_domain(c.domain) { if valid_cookie_domain(c.domain) {
@ -221,8 +221,8 @@ pub fn (c &Cookie) str() string {
if d[0] == `.` { if d[0] == `.` {
d = d.substr(1, d.len) d = d.substr(1, d.len)
} }
b.write('; domain=') b.write_string('; domain=')
b.write(d) b.write_string(d)
} else { } else {
// TODO: Log invalid cookie domain warning // TODO: Log invalid cookie domain warning
} }
@ -230,35 +230,35 @@ pub fn (c &Cookie) str() string {
if c.expires.year > 1600 { if c.expires.year > 1600 {
e := c.expires e := c.expires
time_str := '${e.weekday_str()}, ${e.day.str()} ${e.smonth()} ${e.year} ${e.hhmmss()} GMT' time_str := '${e.weekday_str()}, ${e.day.str()} ${e.smonth()} ${e.year} ${e.hhmmss()} GMT'
b.write('; expires=') b.write_string('; expires=')
b.write(time_str) b.write_string(time_str)
} }
// TODO: Fix this. Techically a max age of 0 or less should be 0 // TODO: Fix this. Techically a max age of 0 or less should be 0
// We need a way to not have a max age. // We need a way to not have a max age.
if c.max_age > 0 { if c.max_age > 0 {
b.write('; Max-Age=') b.write_string('; Max-Age=')
b.write(c.max_age.str()) b.write_string(c.max_age.str())
} else if c.max_age < 0 { } else if c.max_age < 0 {
b.write('; Max-Age=0') b.write_string('; Max-Age=0')
} }
if c.http_only { if c.http_only {
b.write('; HttpOnly') b.write_string('; HttpOnly')
} }
if c.secure { if c.secure {
b.write('; Secure') b.write_string('; Secure')
} }
match c.same_site { match c.same_site {
.same_site_default_mode { .same_site_default_mode {
b.write('; SameSite') b.write_string('; SameSite')
} }
.same_site_none_mode { .same_site_none_mode {
b.write('; SameSite=None') b.write_string('; SameSite=None')
} }
.same_site_lax_mode { .same_site_lax_mode {
b.write('; SameSite=Lax') b.write_string('; SameSite=Lax')
} }
.same_site_strict_mode { .same_site_strict_mode {
b.write('; SameSite=Strict') b.write_string('; SameSite=Strict')
} }
} }
return b.str() return b.str()

View File

@ -145,9 +145,9 @@ fn (mut c Client) send_auth() ? {
} }
mut sb := strings.new_builder(100) mut sb := strings.new_builder(100)
sb.write_b(0) sb.write_b(0)
sb.write(c.username) sb.write_string(c.username)
sb.write_b(0) sb.write_b(0)
sb.write(c.password) sb.write_string(c.password)
a := sb.str() a := sb.str()
auth := 'AUTH PLAIN ${base64.encode(a)}\r\n' auth := 'AUTH PLAIN ${base64.encode(a)}\r\n'
c.send_str(auth) ? c.send_str(auth) ?
@ -173,18 +173,18 @@ fn (mut c Client) send_body(cfg Mail) ? {
is_html := cfg.body_type == .html is_html := cfg.body_type == .html
date := cfg.date.utc_string().trim_right(' UTC') // TODO date := cfg.date.utc_string().trim_right(' UTC') // TODO
mut sb := strings.new_builder(200) mut sb := strings.new_builder(200)
sb.write('From: $cfg.from\r\n') sb.write_string('From: $cfg.from\r\n')
sb.write('To: <$cfg.to>\r\n') sb.write_string('To: <$cfg.to>\r\n')
sb.write('Cc: <$cfg.cc>\r\n') sb.write_string('Cc: <$cfg.cc>\r\n')
sb.write('Bcc: <$cfg.bcc>\r\n') sb.write_string('Bcc: <$cfg.bcc>\r\n')
sb.write('Date: $date\r\n') sb.write_string('Date: $date\r\n')
sb.write('Subject: $cfg.subject\r\n') sb.write_string('Subject: $cfg.subject\r\n')
if is_html { if is_html {
sb.write('Content-Type: text/html; charset=ISO-8859-1') sb.write_string('Content-Type: text/html; charset=ISO-8859-1')
} }
sb.write('\r\n\r\n') sb.write_string('\r\n\r\n')
sb.write(cfg.body) sb.write_string(cfg.body)
sb.write('\r\n.\r\n') sb.write_string('\r\n.\r\n')
c.send_str(sb.str()) ? c.send_str(sb.str()) ?
c.expect_reply(.action_ok) ? c.expect_reply(.action_ok) ?
} }

View File

@ -209,18 +209,18 @@ fn unescape(s_ string, mode EncodingMode) ?string {
x := s[i] x := s[i]
match x { match x {
`%` { `%` {
t.write(((unhex(s[i + 1]) << byte(4)) | unhex(s[i + 2])).ascii_str()) t.write_string(((unhex(s[i + 1]) << byte(4)) | unhex(s[i + 2])).ascii_str())
i += 2 i += 2
} }
`+` { `+` {
if mode == .encode_query_component { if mode == .encode_query_component {
t.write(' ') t.write_string(' ')
} else { } else {
t.write('+') t.write_string('+')
} }
} }
else { else {
t.write(s[i].ascii_str()) t.write_string(s[i].ascii_str())
} }
} }
} }
@ -715,27 +715,27 @@ fn valid_optional_port(port string) bool {
pub fn (u URL) str() string { pub fn (u URL) str() string {
mut buf := strings.new_builder(200) mut buf := strings.new_builder(200)
if u.scheme != '' { if u.scheme != '' {
buf.write(u.scheme) buf.write_string(u.scheme)
buf.write(':') buf.write_string(':')
} }
if u.opaque != '' { if u.opaque != '' {
buf.write(u.opaque) buf.write_string(u.opaque)
} else { } else {
if u.scheme != '' || u.host != '' || (u.user != 0 && !u.user.empty()) { if u.scheme != '' || u.host != '' || (u.user != 0 && !u.user.empty()) {
if u.host != '' || u.path != '' || !u.user.empty() { if u.host != '' || u.path != '' || !u.user.empty() {
buf.write('//') buf.write_string('//')
} }
if !u.user.empty() { if !u.user.empty() {
buf.write(u.user.str()) buf.write_string(u.user.str())
buf.write('@') buf.write_string('@')
} }
if u.host != '' { if u.host != '' {
buf.write(escape(u.host, .encode_host)) buf.write_string(escape(u.host, .encode_host))
} }
} }
path := u.escaped_path() path := u.escaped_path()
if path != '' && path[0] != `/` && u.host != '' { if path != '' && path[0] != `/` && u.host != '' {
buf.write('/') buf.write_string('/')
} }
if buf.len == 0 { if buf.len == 0 {
// RFC 3986 §4.2 // RFC 3986 §4.2
@ -746,18 +746,18 @@ pub fn (u URL) str() string {
// path reference. // path reference.
i := path.index_byte(`:`) i := path.index_byte(`:`)
if i > -1 && path[..i].index_byte(`/`) == -1 { if i > -1 && path[..i].index_byte(`/`) == -1 {
buf.write('./') buf.write_string('./')
} }
} }
buf.write(path) buf.write_string(path)
} }
if u.force_query || u.raw_query != '' { if u.force_query || u.raw_query != '' {
buf.write('?') buf.write_string('?')
buf.write(u.raw_query) buf.write_string(u.raw_query)
} }
if u.fragment != '' { if u.fragment != '' {
buf.write('#') buf.write_string('#')
buf.write(escape(u.fragment, .encode_fragment)) buf.write_string(escape(u.fragment, .encode_fragment))
} }
return buf.str() return buf.str()
} }
@ -845,11 +845,11 @@ pub fn (v Values) encode() string {
key_kscaped := query_escape(k) key_kscaped := query_escape(k)
for _, val in vs.data { for _, val in vs.data {
if buf.len > 0 { if buf.len > 0 {
buf.write('&') buf.write_string('&')
} }
buf.write(key_kscaped) buf.write_string(key_kscaped)
buf.write('=') buf.write_string('=')
buf.write(query_escape(val)) buf.write_string(query_escape(val))
} }
} }
return buf.str() return buf.str()

View File

@ -1294,73 +1294,73 @@ fn (mut re RE) impl_compile(in_txt string) (int,int) {
pub fn (re RE) get_code() string { pub fn (re RE) get_code() string {
mut pc1 := 0 mut pc1 := 0
mut res := strings.new_builder(re.cc.len*2*re.prog.len) mut res := strings.new_builder(re.cc.len*2*re.prog.len)
res.write("========================================\nv RegEx compiler v $v_regex_version output:\n") res.write_string("========================================\nv RegEx compiler v $v_regex_version output:\n")
mut stop_flag := false mut stop_flag := false
for pc1 <= re.prog.len { for pc1 <= re.prog.len {
tk := re.prog[pc1] tk := re.prog[pc1]
res.write("PC:${pc1:3d}") res.write_string("PC:${pc1:3d}")
res.write(" ist: ") res.write_string(" ist: ")
res.write("${tk.ist:8x}".replace(" ","0") ) res.write_string("${tk.ist:8x}".replace(" ","0") )
res.write(" ") res.write_string(" ")
ist :=tk.ist ist :=tk.ist
if ist == ist_bsls_char { if ist == ist_bsls_char {
res.write("[\\${tk.ch:1c}] BSLS") res.write_string("[\\${tk.ch:1c}] BSLS")
} else if ist == ist_prog_end { } else if ist == ist_prog_end {
res.write("PROG_END") res.write_string("PROG_END")
stop_flag = true stop_flag = true
} else if ist == ist_or_branch { } else if ist == ist_or_branch {
res.write("OR ") res.write_string("OR ")
} else if ist == ist_char_class_pos { } else if ist == ist_char_class_pos {
res.write("[${re.get_char_class(pc1)}] CHAR_CLASS_POS") res.write_string("[${re.get_char_class(pc1)}] CHAR_CLASS_POS")
} else if ist == ist_char_class_neg { } else if ist == ist_char_class_neg {
res.write("[^${re.get_char_class(pc1)}] CHAR_CLASS_NEG") res.write_string("[^${re.get_char_class(pc1)}] CHAR_CLASS_NEG")
} else if ist == ist_dot_char { } else if ist == ist_dot_char {
res.write(". DOT_CHAR nx chk: ${tk.dot_check_pc}") res.write_string(". DOT_CHAR nx chk: ${tk.dot_check_pc}")
if tk.last_dot_flag == true { if tk.last_dot_flag == true {
res.write(" last!") res.write_string(" last!")
} }
} else if ist == ist_group_start { } else if ist == ist_group_start {
res.write("( GROUP_START #:${tk.group_id}") res.write_string("( GROUP_START #:${tk.group_id}")
if tk.group_id == -1 { if tk.group_id == -1 {
res.write(" ?:") res.write_string(" ?:")
} else { } else {
for x in re.group_map.keys() { for x in re.group_map.keys() {
if re.group_map[x] == (tk.group_id+1) { if re.group_map[x] == (tk.group_id+1) {
res.write(" ?P<${x}>") res.write_string(" ?P<${x}>")
break break
} }
} }
} }
} else if ist == ist_group_end { } else if ist == ist_group_end {
res.write(") GROUP_END #:${tk.group_id}") res.write_string(") GROUP_END #:${tk.group_id}")
} else if ist == ist_simple_char { } else if ist == ist_simple_char {
res.write("[${tk.ch:1c}] query_ch") res.write_string("[${tk.ch:1c}] query_ch")
} }
if tk.rep_max == max_quantifier { if tk.rep_max == max_quantifier {
res.write(" {${tk.rep_min:3d},MAX}") res.write_string(" {${tk.rep_min:3d},MAX}")
}else{ }else{
if ist == ist_or_branch { if ist == ist_or_branch {
res.write(" if false go: ${tk.rep_min:3d} if true go: ${tk.rep_max:3d}") res.write_string(" if false go: ${tk.rep_min:3d} if true go: ${tk.rep_max:3d}")
} else { } else {
res.write(" {${tk.rep_min:3d},${tk.rep_max:3d}}") res.write_string(" {${tk.rep_min:3d},${tk.rep_max:3d}}")
} }
if tk.greedy == true { if tk.greedy == true {
res.write("?") res.write_string("?")
} }
} }
res.write("\n") res.write_string("\n")
if stop_flag { if stop_flag {
break break
} }
pc1++ pc1++
} }
res.write("========================================\n") res.write_string("========================================\n")
return res.str() return res.str()
} }
@ -1369,7 +1369,7 @@ pub fn (re RE) get_query() string {
mut res := strings.new_builder(re.query.len*2) mut res := strings.new_builder(re.query.len*2)
if (re.flag & f_ms) != 0 { if (re.flag & f_ms) != 0 {
res.write("^") res.write_string("^")
} }
mut i := 0 mut i := 0
@ -1380,18 +1380,18 @@ pub fn (re RE) get_query() string {
// GROUP start // GROUP start
if ch == ist_group_start { if ch == ist_group_start {
if re.debug == 0 { if re.debug == 0 {
res.write("(") res.write_string("(")
} else { } else {
if tk.group_id == -1 { if tk.group_id == -1 {
res.write("(?:") // non capturing group res.write_string("(?:") // non capturing group
} else { } else {
res.write("#${tk.group_id}(") res.write_string("#${tk.group_id}(")
} }
} }
for x in re.group_map.keys() { for x in re.group_map.keys() {
if re.group_map[x] == (tk.group_id+1) { if re.group_map[x] == (tk.group_id+1) {
res.write("?P<${x}>") res.write_string("?P<${x}>")
break break
} }
} }
@ -1402,14 +1402,14 @@ pub fn (re RE) get_query() string {
// GROUP end // GROUP end
if ch == ist_group_end { if ch == ist_group_end {
res.write(")") res.write_string(")")
} }
// OR branch // OR branch
if ch == ist_or_branch { if ch == ist_or_branch {
res.write("|") res.write_string("|")
if re.debug > 0 { if re.debug > 0 {
res.write("{${tk.rep_min},${tk.rep_max}}") res.write_string("{${tk.rep_min},${tk.rep_max}}")
} }
i++ i++
continue continue
@ -1417,55 +1417,55 @@ pub fn (re RE) get_query() string {
// char class // char class
if ch == ist_char_class_neg || ch == ist_char_class_pos { if ch == ist_char_class_neg || ch == ist_char_class_pos {
res.write("[") res.write_string("[")
if ch == ist_char_class_neg { if ch == ist_char_class_neg {
res.write("^") res.write_string("^")
} }
res.write("${re.get_char_class(i)}") res.write_string("${re.get_char_class(i)}")
res.write("]") res.write_string("]")
} }
// bsls char // bsls char
if ch == ist_bsls_char { if ch == ist_bsls_char {
res.write("\\${tk.ch:1c}") res.write_string("\\${tk.ch:1c}")
} }
// ist_dot_char // ist_dot_char
if ch == ist_dot_char { if ch == ist_dot_char {
res.write(".") res.write_string(".")
} }
// char alone // char alone
if ch == ist_simple_char { if ch == ist_simple_char {
if byte(ch) in bsls_escape_list { if byte(ch) in bsls_escape_list {
res.write("\\") res.write_string("\\")
} }
res.write("${tk.ch:c}") res.write_string("${tk.ch:c}")
} }
// quantifier // quantifier
if !(tk.rep_min == 1 && tk.rep_max == 1) { if !(tk.rep_min == 1 && tk.rep_max == 1) {
if tk.rep_min == 0 && tk.rep_max == 1 { if tk.rep_min == 0 && tk.rep_max == 1 {
res.write("?") res.write_string("?")
} else if tk.rep_min == 1 && tk.rep_max == max_quantifier { } else if tk.rep_min == 1 && tk.rep_max == max_quantifier {
res.write("+") res.write_string("+")
} else if tk.rep_min == 0 && tk.rep_max == max_quantifier { } else if tk.rep_min == 0 && tk.rep_max == max_quantifier {
res.write("*") res.write_string("*")
} else { } else {
if tk.rep_max == max_quantifier { if tk.rep_max == max_quantifier {
res.write("{${tk.rep_min},MAX}") res.write_string("{${tk.rep_min},MAX}")
} else { } else {
res.write("{${tk.rep_min},${tk.rep_max}}") res.write_string("{${tk.rep_min},${tk.rep_max}}")
} }
if tk.greedy == true { if tk.greedy == true {
res.write("?") res.write_string("?")
} }
} }
} }
i++ i++
} }
if (re.flag & f_me) != 0 { if (re.flag & f_me) != 0 {
res.write("$") res.write_string("$")
} }
return res.str() return res.str()
@ -1582,9 +1582,9 @@ pub fn (mut re RE) match_base(in_txt byteptr, in_txt_len int ) (int,int) {
if re.debug>0 { if re.debug>0 {
// print header // print header
mut h_buf := strings.new_builder(32) mut h_buf := strings.new_builder(32)
h_buf.write("flags: ") h_buf.write_string("flags: ")
h_buf.write("${re.flag:8x}".replace(" ","0")) h_buf.write_string("${re.flag:8x}".replace(" ","0"))
h_buf.write("\n") h_buf.write_string("\n")
sss := h_buf.str() sss := h_buf.str()
re.log_func(sss) re.log_func(sss)
} }
@ -1608,7 +1608,7 @@ pub fn (mut re RE) match_base(in_txt byteptr, in_txt_len int ) (int,int) {
// end of the input text // end of the input text
if state.i >= in_txt_len { if state.i >= in_txt_len {
buf2.write("# ${step_count:3d} END OF INPUT TEXT\n") buf2.write_string("# ${step_count:3d} END OF INPUT TEXT\n")
sss := buf2.str() sss := buf2.str()
re.log_func(sss) re.log_func(sss)
}else{ }else{
@ -1618,55 +1618,55 @@ pub fn (mut re RE) match_base(in_txt byteptr, in_txt_len int ) (int,int) {
re.debug == 2 re.debug == 2
{ {
if ist == ist_prog_end { if ist == ist_prog_end {
buf2.write("# ${step_count:3d} PROG_END\n") buf2.write_string("# ${step_count:3d} PROG_END\n")
} }
else if ist == 0 || m_state in [.start,.ist_next,.stop] { else if ist == 0 || m_state in [.start,.ist_next,.stop] {
buf2.write("# ${step_count:3d} s: ${state_str(m_state):12s} PC: NA\n") buf2.write_string("# ${step_count:3d} s: ${state_str(m_state):12s} PC: NA\n")
}else{ }else{
ch, char_len = re.get_charb(in_txt, state.i) ch, char_len = re.get_charb(in_txt, state.i)
buf2.write("# ${step_count:3d} s: ${state_str(m_state):12s} PC: ${state.pc:3d}=>") buf2.write_string("# ${step_count:3d} s: ${state_str(m_state):12s} PC: ${state.pc:3d}=>")
buf2.write("${ist:8x}".replace(" ","0")) buf2.write_string("${ist:8x}".replace(" ","0"))
buf2.write(" i,ch,len:[${state.i:3d},'${utf8_str(ch)}',${char_len}] f.m:[${state.first_match:3d},${state.match_index:3d}] ") buf2.write_string(" i,ch,len:[${state.i:3d},'${utf8_str(ch)}',${char_len}] f.m:[${state.first_match:3d},${state.match_index:3d}] ")
if ist == ist_simple_char { if ist == ist_simple_char {
buf2.write("query_ch: [${re.prog[state.pc].ch:1c}]") buf2.write_string("query_ch: [${re.prog[state.pc].ch:1c}]")
} else { } else {
if ist == ist_bsls_char { if ist == ist_bsls_char {
buf2.write("BSLS [\\${re.prog[state.pc].ch:1c}]") buf2.write_string("BSLS [\\${re.prog[state.pc].ch:1c}]")
} else if ist == ist_prog_end { } else if ist == ist_prog_end {
buf2.write("PROG_END") buf2.write_string("PROG_END")
} else if ist == ist_or_branch { } else if ist == ist_or_branch {
buf2.write("OR") buf2.write_string("OR")
} else if ist == ist_char_class_pos { } else if ist == ist_char_class_pos {
buf2.write("CHAR_CLASS_POS[${re.get_char_class(state.pc)}]") buf2.write_string("CHAR_CLASS_POS[${re.get_char_class(state.pc)}]")
} else if ist == ist_char_class_neg { } else if ist == ist_char_class_neg {
buf2.write("CHAR_CLASS_NEG[${re.get_char_class(state.pc)}]") buf2.write_string("CHAR_CLASS_NEG[${re.get_char_class(state.pc)}]")
} else if ist == ist_dot_char { } else if ist == ist_dot_char {
buf2.write("DOT_CHAR") buf2.write_string("DOT_CHAR")
} else if ist == ist_group_start { } else if ist == ist_group_start {
tmp_gi :=re.prog[state.pc].group_id tmp_gi :=re.prog[state.pc].group_id
tmp_gr := re.prog[re.prog[state.pc].goto_pc].group_rep tmp_gr := re.prog[re.prog[state.pc].goto_pc].group_rep
buf2.write("GROUP_START #:${tmp_gi} rep:${tmp_gr} ") buf2.write_string("GROUP_START #:${tmp_gi} rep:${tmp_gr} ")
} else if ist == ist_group_end { } else if ist == ist_group_end {
buf2.write("GROUP_END #:${re.prog[state.pc].group_id} deep:${state.group_index}") buf2.write_string("GROUP_END #:${re.prog[state.pc].group_id} deep:${state.group_index}")
} }
} }
if re.prog[state.pc].rep_max == max_quantifier { if re.prog[state.pc].rep_max == max_quantifier {
buf2.write("{${re.prog[state.pc].rep_min},MAX}:${re.prog[state.pc].rep}") buf2.write_string("{${re.prog[state.pc].rep_min},MAX}:${re.prog[state.pc].rep}")
} else { } else {
buf2.write("{${re.prog[state.pc].rep_min},${re.prog[state.pc].rep_max}}:${re.prog[state.pc].rep}") buf2.write_string("{${re.prog[state.pc].rep_min},${re.prog[state.pc].rep_max}}:${re.prog[state.pc].rep}")
} }
if re.prog[state.pc].greedy == true { if re.prog[state.pc].greedy == true {
buf2.write("?") buf2.write_string("?")
} }
buf2.write(" (#${state.group_index})") buf2.write_string(" (#${state.group_index})")
if ist == ist_dot_char { if ist == ist_dot_char {
buf2.write(" last!") buf2.write_string(" last!")
} }
buf2.write("\n") buf2.write_string("\n")
} }
sss2 := buf2.str() sss2 := buf2.str()
re.log_func( sss2 ) re.log_func( sss2 )

View File

@ -7,11 +7,11 @@ pub fn (mut re RE) compile_opt(pattern string) ? {
if re_err != compile_ok { if re_err != compile_ok {
mut err_msg := strings.new_builder(300) mut err_msg := strings.new_builder(300)
err_msg.write("\nquery: $pattern\n") err_msg.write_string("\nquery: $pattern\n")
line := "-".repeat(err_pos) line := "-".repeat(err_pos)
err_msg.write("err : ${line}^\n") err_msg.write_string("err : ${line}^\n")
err_str := re.get_parse_error_string(re_err) err_str := re.get_parse_error_string(re_err)
err_msg.write("ERROR: $err_str\n") err_msg.write_string("ERROR: $err_str\n")
return error_with_code(err_msg.str(), re_err) return error_with_code(err_msg.str(), re_err)
} }
} }

View File

@ -224,7 +224,7 @@ pub fn format_str(s string, p BF_param) string {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
} }
} }
res.write(s) res.write_string(s)
if p.allign == .left { if p.allign == .left {
for i1 :=0; i1 < dif; i1++ { for i1 :=0; i1 < dif; i1++ {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
@ -267,7 +267,7 @@ pub fn format_dec(d u64, p BF_param) string {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
} }
} }
res.write(s) res.write_string(s)
if p.allign == .left { if p.allign == .left {
for i1 :=0; i1 < dif; i1++ { for i1 :=0; i1 < dif; i1++ {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
@ -321,7 +321,7 @@ pub fn format_fl(f f64, p BF_param) string {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
} }
} }
res.write(s) res.write_string(s)
if p.allign == .left { if p.allign == .left {
for i1 :=0; i1 < dif; i1++ { for i1 :=0; i1 < dif; i1++ {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
@ -369,7 +369,7 @@ pub fn format_es(f f64, p BF_param) string {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
} }
} }
res.write(s) res.write_string(s)
if p.allign == .left { if p.allign == .left {
for i1 :=0; i1 < dif; i1++ { for i1 :=0; i1 < dif; i1++ {
res.write_b(p.pad_ch) res.write_b(p.pad_ch)
@ -484,8 +484,8 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
// pointer, manage it here // pointer, manage it here
if ch == `p` && status == .field_char { if ch == `p` && status == .field_char {
v_sprintf_panic(p_index, pt.len) v_sprintf_panic(p_index, pt.len)
res.write("0x") res.write_string("0x")
res.write(ptr_str(unsafe {pt[p_index]})) res.write_string(ptr_str(unsafe {pt[p_index]}))
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++
@ -532,7 +532,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
mut s := unsafe {*(&string(pt[p_index]))} mut s := unsafe {*(&string(pt[p_index]))}
s = s[..len] s = s[..len]
p_index++ p_index++
res.write(s) res.write_string(s)
status = .reset_params status = .reset_params
i += 3 i += 3
continue continue
@ -672,7 +672,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
} }
} }
res.write(format_dec(d1,{pad_ch: pad_ch, len0: len0, len1: 0, positive: positive, sign_flag: sign, allign: allign})) res.write_string(format_dec(d1,{pad_ch: pad_ch, len0: len0, len1: 0, positive: positive, sign_flag: sign, allign: allign}))
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++
@ -715,7 +715,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
} }
} }
res.write(format_dec(d1,{pad_ch: pad_ch, len0: len0, len1: 0, positive: positive, sign_flag: sign, allign: allign})) res.write_string(format_dec(d1,{pad_ch: pad_ch, len0: len0, len1: 0, positive: positive, sign_flag: sign, allign: allign}))
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++
@ -764,7 +764,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
s = s.to_upper() s = s.to_upper()
} }
res.write(format_str(s,{pad_ch: pad_ch, len0: len0, len1: 0, positive: true, sign_flag: false, allign: allign})) res.write_string(format_str(s,{pad_ch: pad_ch, len0: len0, len1: 0, positive: true, sign_flag: false, allign: allign}))
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++
@ -778,7 +778,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
positive := x >= f64(0.0) positive := x >= f64(0.0)
len1 = if len1 >= 0 { len1 } else { def_len1 } len1 = if len1 >= 0 { len1 } else { def_len1 }
s := format_fl(f64(x), {pad_ch: pad_ch, len0: len0, len1: len1, positive: positive, sign_flag: sign, allign: allign}) s := format_fl(f64(x), {pad_ch: pad_ch, len0: len0, len1: len1, positive: positive, sign_flag: sign, allign: allign})
res.write(if ch == `F` {s.to_upper()} else {s}) res.write_string(if ch == `F` {s.to_upper()} else {s})
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++
@ -790,7 +790,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
positive := x >= f64(0.0) positive := x >= f64(0.0)
len1 = if len1 >= 0 { len1 } else { def_len1 } len1 = if len1 >= 0 { len1 } else { def_len1 }
s := format_es(f64(x), {pad_ch: pad_ch, len0: len0, len1: len1, positive: positive, sign_flag: sign, allign: allign}) s := format_es(f64(x), {pad_ch: pad_ch, len0: len0, len1: len1, positive: positive, sign_flag: sign, allign: allign})
res.write(if ch == `E` {s.to_upper()} else {s}) res.write_string(if ch == `E` {s.to_upper()} else {s})
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++
@ -810,7 +810,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
len1 = if len1 >= 0 { len1+1 } else { def_len1 } len1 = if len1 >= 0 { len1+1 } else { def_len1 }
s = format_es(x, {pad_ch: pad_ch, len0: len0, len1: len1, positive: positive, sign_flag: sign, allign: allign, rm_tail_zero: true}) s = format_es(x, {pad_ch: pad_ch, len0: len0, len1: len1, positive: positive, sign_flag: sign, allign: allign, rm_tail_zero: true})
} }
res.write(if ch == `G` {s.to_upper()} else {s}) res.write_string(if ch == `G` {s.to_upper()} else {s})
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++
@ -822,7 +822,7 @@ pub fn v_sprintf(str string, pt ... voidptr) string{
v_sprintf_panic(p_index, pt.len) v_sprintf_panic(p_index, pt.len)
s1 := unsafe{*(&string(pt[p_index]))} s1 := unsafe{*(&string(pt[p_index]))}
pad_ch = ` ` pad_ch = ` `
res.write(format_str(s1, {pad_ch: pad_ch, len0: len0, len1: 0, positive: true, sign_flag: false, allign: allign})) res.write_string(format_str(s1, {pad_ch: pad_ch, len0: len0, len1: 0, positive: true, sign_flag: false, allign: allign}))
status = .reset_params status = .reset_params
p_index++ p_index++
i++ i++

View File

@ -23,7 +23,7 @@ pub fn (mut b Builder) write_b(data byte) {
b.len++ b.len++
} }
pub fn (mut b Builder) write(s string) { pub fn (mut b Builder) write_string(s string) {
b.buf.push_many(s.str, s.len) b.buf.push_many(s.str, s.len)
// b.buf << []byte(s) // TODO // b.buf << []byte(s) // TODO
b.len += s.len b.len += s.len

View File

@ -37,9 +37,14 @@ pub fn (mut b Builder) write_b(data byte) {
b.len++ b.len++
} }
[deprecated: 'write(string) will be changed to write([]byte)']
pub fn (mut b Builder) write(s string) {
b.write_string(s)
}
// write appends the string `s` to the buffer // write appends the string `s` to the buffer
[inline] [inline]
pub fn (mut b Builder) write(s string) { pub fn (mut b Builder) write_string(s string) {
if s == '' { if s == '' {
return return
} }

View File

@ -4,17 +4,17 @@ type MyInt = int
fn test_sb() { fn test_sb() {
mut sb := strings.Builder{} mut sb := strings.Builder{}
sb.write('hi') sb.write_string('hi')
sb.write('!') sb.write_string('!')
sb.write('hello') sb.write_string('hello')
assert sb.len == 8 assert sb.len == 8
sb_end := sb.str() sb_end := sb.str()
assert sb_end == 'hi!hello' assert sb_end == 'hi!hello'
assert sb.len == 0 assert sb.len == 0
/// ///
sb = strings.new_builder(10) sb = strings.new_builder(10)
sb.write('a') sb.write_string('a')
sb.write('b') sb.write_string('b')
assert sb.len == 2 assert sb.len == 2
assert sb.str() == 'ab' assert sb.str() == 'ab'
// Test interpolation optimization // Test interpolation optimization
@ -28,12 +28,12 @@ fn test_sb() {
assert res.trim_space() == 'x = 10 y = 20' assert res.trim_space() == 'x = 10 y = 20'
// //
sb = strings.new_builder(10) sb = strings.new_builder(10)
sb.write('x = $x y = $y') sb.write_string('x = $x y = $y')
assert sb.str() == 'x = 10 y = 20' assert sb.str() == 'x = 10 y = 20'
$if !windows { $if !windows {
// TODO msvc bug // TODO msvc bug
sb = strings.new_builder(10) sb = strings.new_builder(10)
sb.write('123456') sb.write_string('123456')
last_2 := sb.cut_last(2) last_2 := sb.cut_last(2)
assert last_2 == '56' assert last_2 == '56'
final_sb := sb.str() final_sb := sb.str()
@ -50,7 +50,7 @@ fn test_big_sb() {
mut sb2 := strings.new_builder(10000) mut sb2 := strings.new_builder(10000)
for i in 0 .. maxn { for i in 0 .. maxn {
sb.writeln(i.str()) sb.writeln(i.str())
sb2.write('+') sb2.write_string('+')
} }
s := sb.str() s := sb.str()
lines := s.split_into_lines() lines := s.split_into_lines()
@ -78,8 +78,8 @@ fn test_byte_write() {
fn test_strings_builder_reuse() { fn test_strings_builder_reuse() {
mut sb := strings.new_builder(256) mut sb := strings.new_builder(256)
sb.write('world') sb.write_string('world')
assert sb.str() == 'world' assert sb.str() == 'world'
sb.write('hello') sb.write_string('hello')
assert sb.str() == 'hello' assert sb.str() == 'hello'
} }

View File

@ -22,7 +22,7 @@ pub fn (node &FnDecl) modname() string {
pub fn (node &FnDecl) stringify(t &table.Table, cur_mod string, m2a map[string]string) string { pub fn (node &FnDecl) stringify(t &table.Table, cur_mod string, m2a map[string]string) string {
mut f := strings.new_builder(30) mut f := strings.new_builder(30)
if node.is_pub { if node.is_pub {
f.write('pub ') f.write_string('pub ')
} }
mut receiver := '' mut receiver := ''
if node.is_method { if node.is_method {
@ -56,22 +56,22 @@ pub fn (node &FnDecl) stringify(t &table.Table, cur_mod string, m2a map[string]s
// name = 'JS.$name' // name = 'JS.$name'
// } // }
// } // }
f.write('fn $receiver$name') f.write_string('fn $receiver$name')
if name in ['+', '-', '*', '/', '%', '<', '>', '==', '!=', '>=', '<='] { if name in ['+', '-', '*', '/', '%', '<', '>', '==', '!=', '>=', '<='] {
f.write(' ') f.write_string(' ')
} }
if node.generic_params.len > 0 { if node.generic_params.len > 0 {
f.write('<') f.write_string('<')
for i, param in node.generic_params { for i, param in node.generic_params {
is_last := i == node.generic_params.len - 1 is_last := i == node.generic_params.len - 1
f.write(param.name) f.write_string(param.name)
if !is_last { if !is_last {
f.write(', ') f.write_string(', ')
} }
} }
f.write('>') f.write_string('>')
} }
f.write('(') f.write_string('(')
for i, arg in node.params { for i, arg in node.params {
// skip receiver // skip receiver
// if (node.is_method || node.is_interface) && i == 0 { // if (node.is_method || node.is_interface) && i == 0 {
@ -86,12 +86,12 @@ pub fn (node &FnDecl) stringify(t &table.Table, cur_mod string, m2a map[string]s
should_add_type := true // is_last_arg || is_type_only || node.params[i + 1].typ != arg.typ || should_add_type := true // is_last_arg || is_type_only || node.params[i + 1].typ != arg.typ ||
// (node.is_variadic && i == node.params.len - 2) // (node.is_variadic && i == node.params.len - 2)
if arg.is_mut { if arg.is_mut {
f.write(arg.typ.share().str() + ' ') f.write_string(arg.typ.share().str() + ' ')
} }
f.write(arg.name) f.write_string(arg.name)
mut s := t.type_to_str(arg.typ.clear_flag(.shared_f)) mut s := t.type_to_str(arg.typ.clear_flag(.shared_f))
if arg.is_mut { if arg.is_mut {
// f.write(' mut') // f.write_string(' mut')
if s.starts_with('&') { if s.starts_with('&') {
s = s[1..] s = s[1..]
} }
@ -102,24 +102,24 @@ pub fn (node &FnDecl) stringify(t &table.Table, cur_mod string, m2a map[string]s
} }
if should_add_type { if should_add_type {
if !is_type_only { if !is_type_only {
f.write(' ') f.write_string(' ')
} }
if node.is_variadic && is_last_arg { if node.is_variadic && is_last_arg {
f.write('...') f.write_string('...')
} }
f.write(s) f.write_string(s)
} }
if !is_last_arg { if !is_last_arg {
f.write(', ') f.write_string(', ')
} }
} }
f.write(')') f.write_string(')')
if node.return_type != table.void_type { if node.return_type != table.void_type {
mut rs := util.no_cur_mod(t.type_to_str(node.return_type), cur_mod) mut rs := util.no_cur_mod(t.type_to_str(node.return_type), cur_mod)
for mod, alias in m2a { for mod, alias in m2a {
rs = rs.replace(mod, alias) rs = rs.replace(mod, alias)
} }
f.write(' ' + rs) f.write_string(' ' + rs)
} }
return f.str() return f.str()
} }

View File

@ -4407,18 +4407,18 @@ fn (mut c Checker) match_exprs(mut node ast.MatchExpr, cond_type_sym table.TypeS
if expr_types.len > 1 { if expr_types.len > 1 {
mut agg_name := strings.new_builder(20) mut agg_name := strings.new_builder(20)
mut agg_cname := strings.new_builder(20) mut agg_cname := strings.new_builder(20)
agg_name.write('(') agg_name.write_string('(')
for i, expr in expr_types { for i, expr in expr_types {
if i > 0 { if i > 0 {
agg_name.write(' | ') agg_name.write_string(' | ')
agg_cname.write('___') agg_cname.write_string('___')
} }
type_str := c.table.type_to_str(expr.typ) type_str := c.table.type_to_str(expr.typ)
name := if c.is_builtin_mod { type_str } else { '${c.mod}.$type_str' } name := if c.is_builtin_mod { type_str } else { '${c.mod}.$type_str' }
agg_name.write(name) agg_name.write_string(name)
agg_cname.write(util.no_dots(name)) agg_cname.write_string(util.no_dots(name))
} }
agg_name.write(')') agg_name.write_string(')')
name := agg_name.str() name := agg_name.str()
existing_idx := c.table.type_idxs[name] existing_idx := c.table.type_idxs[name]
if existing_idx > 0 { if existing_idx > 0 {

View File

@ -96,7 +96,7 @@ pub fn (mut f Fmt) write(s string) {
if f.indent > 0 && f.empty_line { if f.indent > 0 && f.empty_line {
f.write_indent() f.write_indent()
} }
f.out.write(s) f.out.write_string(s)
f.line_len += s.len f.line_len += s.len
f.empty_line = false f.empty_line = false
} }
@ -112,11 +112,11 @@ pub fn (mut f Fmt) writeln(s string) {
fn (mut f Fmt) write_indent() { fn (mut f Fmt) write_indent() {
if f.indent < fmt.tabs.len { if f.indent < fmt.tabs.len {
f.out.write(fmt.tabs[f.indent]) f.out.write_string(fmt.tabs[f.indent])
} else { } else {
// too many indents, do it the slow way: // too many indents, do it the slow way:
for _ in 0 .. f.indent { for _ in 0 .. f.indent {
f.out.write('\t') f.out.write_string('\t')
} }
} }
f.line_len += f.indent * 4 f.line_len += f.indent * 4
@ -856,7 +856,7 @@ pub fn (mut f Fmt) prefix_expr_cast_expr(fexpr ast.Expr) {
} else if fexpr is ast.CastExpr { } else if fexpr is ast.CastExpr {
last := f.out.cut_last(1) last := f.out.cut_last(1)
if last != '&' { if last != '&' {
f.out.write(last) f.out.write_string(last)
} }
} }
if !is_pe_amp_ce { if !is_pe_amp_ce {

View File

@ -208,13 +208,13 @@ fn (mut g Gen) gen_map_equality_fn(left table.Type) string {
value_sym := g.table.get_type_symbol(value_typ) value_sym := g.table.get_type_symbol(value_typ)
func := value_sym.info as table.FnType func := value_sym.info as table.FnType
ret_styp := g.typ(func.func.return_type) ret_styp := g.typ(func.func.return_type)
fn_builder.write('\t\t$ret_styp (*v) (') fn_builder.write_string('\t\t$ret_styp (*v) (')
arg_len := func.func.params.len arg_len := func.func.params.len
for j, arg in func.func.params { for j, arg in func.func.params {
arg_styp := g.typ(arg.typ) arg_styp := g.typ(arg.typ)
fn_builder.write('$arg_styp $arg.name') fn_builder.write_string('$arg_styp $arg.name')
if j < arg_len - 1 { if j < arg_len - 1 {
fn_builder.write(', ') fn_builder.write_string(', ')
} }
} }
fn_builder.writeln(') = *(voidptr*)map_get_1(&a, k, &(voidptr[]){ 0 });') fn_builder.writeln(') = *(voidptr*)map_get_1(&a, k, &(voidptr[]){ 0 });')

View File

@ -203,7 +203,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.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('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 sb = strings__new_builder(a.len * 10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("["));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT("["));')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < a.len; ++i) {') g.auto_str_funcs.writeln('\tfor (int i = 0; i < a.len; ++i) {')
if sym.kind == .function { if sym.kind == .function {
g.auto_str_funcs.writeln('\t\tstring x = ${elem_str_fn_name}();') g.auto_str_funcs.writeln('\t\tstring x = ${elem_str_fn_name}();')
@ -239,16 +239,16 @@ fn (mut g Gen) gen_str_for_array(info table.Array, styp string, str_fn_name stri
} }
} }
} }
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, x);') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, x);')
if g.is_autofree && typ != table.bool_type { if g.is_autofree && typ != table.bool_type {
// no need to free "true"/"false" literals // no need to free "true"/"false" literals
g.auto_str_funcs.writeln('\t\tstring_free(&x);') 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\tif (i < a.len-1) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _SLIT(", "));') g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write_string(&sb, _SLIT(", "));')
g.auto_str_funcs.writeln('\t\t}') g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}') g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("]"));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT("]"));')
g.auto_str_funcs.writeln('\tstring res = strings__Builder_str(&sb);') 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('\tstrings__Builder_free(&sb);')
g.auto_str_funcs.writeln('\treturn res;') g.auto_str_funcs.writeln('\treturn res;')
@ -283,34 +283,34 @@ 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.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('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 sb = strings__new_builder($info.size * 10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("["));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT("["));')
if sym.kind == .function { if sym.kind == .function {
g.auto_str_funcs.writeln('\t\tstring x = ${elem_str_fn_name}();') g.auto_str_funcs.writeln('\t\tstring x = ${elem_str_fn_name}();')
} else { } else {
g.auto_str_funcs.writeln('\tfor (int i = 0; i < $info.size; ++i) {') g.auto_str_funcs.writeln('\tfor (int i = 0; i < $info.size; ++i) {')
if sym.kind == .struct_ && !sym_has_str_method { if sym.kind == .struct_ && !sym_has_str_method {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}(a[i]));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, ${elem_str_fn_name}(a[i]));')
} else if sym.kind in [.f32, .f64] { } else if sym.kind in [.f32, .f64] {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("%g", 1, a[i]));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("%g", 1, a[i]));')
} else if sym.kind == .string { } else if sym.kind == .string {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("\'%.*s\\000\'", 2, a[i]));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("\'%.*s\\000\'", 2, a[i]));')
} else if sym.kind == .rune { } else if sym.kind == .rune {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("`%.*s\\000`", 2, ${elem_str_fn_name}(a[i])));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("`%.*s\\000`", 2, ${elem_str_fn_name}(a[i])));')
} else { } else {
if (str_method_expects_ptr && is_elem_ptr) || (!str_method_expects_ptr && !is_elem_ptr) { if (str_method_expects_ptr && is_elem_ptr) || (!str_method_expects_ptr && !is_elem_ptr) {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}(a[i]));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, ${elem_str_fn_name}(a[i]));')
} else if str_method_expects_ptr && !is_elem_ptr { } else if str_method_expects_ptr && !is_elem_ptr {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}(&a[i]));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, ${elem_str_fn_name}(&a[i]));')
} else if !str_method_expects_ptr && is_elem_ptr { } else if !str_method_expects_ptr && is_elem_ptr {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}(*a[i]));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, ${elem_str_fn_name}(*a[i]));')
} }
} }
} }
g.auto_str_funcs.writeln('\t\tif (i < ${info.size - 1}) {') g.auto_str_funcs.writeln('\t\tif (i < ${info.size - 1}) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _SLIT(", "));') g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write_string(&sb, _SLIT(", "));')
g.auto_str_funcs.writeln('\t\t}') g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}') g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("]"));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT("]"));')
g.auto_str_funcs.writeln('\tstring res = strings__Builder_str(&sb);') 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('\tstrings__Builder_free(&sb);')
g.auto_str_funcs.writeln('\treturn res;') g.auto_str_funcs.writeln('\treturn res;')
@ -347,7 +347,7 @@ 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.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('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 sb = strings__new_builder(m.key_values.len*10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("{"));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT("{"));')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < m.key_values.len; ++i) {') g.auto_str_funcs.writeln('\tfor (int i = 0; i < m.key_values.len; ++i) {')
g.auto_str_funcs.writeln('\t\tif (!DenseArray_has_index(&m.key_values, i)) { continue; }') g.auto_str_funcs.writeln('\t\tif (!DenseArray_has_index(&m.key_values, i)) { continue; }')
@ -357,31 +357,31 @@ fn (mut g Gen) gen_str_for_map(info table.Map, styp string, str_fn_name string)
g.auto_str_funcs.writeln('\t\t$key_styp key = *($key_styp*)DenseArray_key(&m.key_values, i);') g.auto_str_funcs.writeln('\t\t$key_styp key = *($key_styp*)DenseArray_key(&m.key_values, i);')
} }
if key_sym.kind == .string { if key_sym.kind == .string {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("\'%.*s\\000\'", 2, key));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("\'%.*s\\000\'", 2, key));')
} else if key_sym.kind == .rune { } else if key_sym.kind == .rune {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("`%.*s\\000`", 2, ${key_str_fn_name}(key)));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("`%.*s\\000`", 2, ${key_str_fn_name}(key)));')
} else { } else {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${key_str_fn_name}(key));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, ${key_str_fn_name}(key));')
} }
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _SLIT(": "));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _SLIT(": "));')
if val_sym.kind == .function { if val_sym.kind == .function {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}());') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, ${elem_str_fn_name}());')
} else if val_sym.kind == .string { } else if val_sym.kind == .string {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("\'%.*s\\000\'", 2, *($val_styp*)DenseArray_value(&m.key_values, i)));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("\'%.*s\\000\'", 2, *($val_styp*)DenseArray_value(&m.key_values, i)));')
} else if val_sym.kind == .struct_ && !val_sym.has_method('str') { } else if val_sym.kind == .struct_ && !val_sym.has_method('str') {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, indent_${elem_str_fn_name}(*($val_styp*)DenseArray_value(&m.key_values, i), indent_count));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, indent_${elem_str_fn_name}(*($val_styp*)DenseArray_value(&m.key_values, i), indent_count));')
} else if val_sym.kind in [.f32, .f64] { } else if val_sym.kind in [.f32, .f64] {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("%g", 1, *($val_styp*)DenseArray_value(&m.key_values, i)));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("%g", 1, *($val_styp*)DenseArray_value(&m.key_values, i)));')
} else if val_sym.kind == .rune { } else if val_sym.kind == .rune {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("`%.*s\\000`", 2, ${elem_str_fn_name}(*($val_styp*)DenseArray_value(&m.key_values, i))));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, _STR("`%.*s\\000`", 2, ${elem_str_fn_name}(*($val_styp*)DenseArray_value(&m.key_values, i))));')
} else { } else {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${elem_str_fn_name}(*($val_styp*)DenseArray_value(&m.key_values, i)));') g.auto_str_funcs.writeln('\t\tstrings__Builder_write_string(&sb, ${elem_str_fn_name}(*($val_styp*)DenseArray_value(&m.key_values, i)));')
} }
g.auto_str_funcs.writeln('\t\tif (i != m.key_values.len-1) {') g.auto_str_funcs.writeln('\t\tif (i != m.key_values.len-1) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _SLIT(", "));') g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write_string(&sb, _SLIT(", "));')
g.auto_str_funcs.writeln('\t\t}') g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}') g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("}"));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT("}"));')
g.auto_str_funcs.writeln('\tstring res = strings__Builder_str(&sb);') 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('\tstrings__Builder_free(&sb);')
g.auto_str_funcs.writeln('\treturn res;') g.auto_str_funcs.writeln('\treturn res;')
@ -398,7 +398,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.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('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 sb = strings__new_builder($info.types.len * 10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT("("));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT("("));')
for i, typ in info.types { for i, typ in info.types {
sym := g.table.get_type_symbol(typ) sym := g.table.get_type_symbol(typ)
field_styp := g.typ(typ) field_styp := g.typ(typ)
@ -415,27 +415,27 @@ fn (mut g Gen) gen_str_for_multi_return(info table.MultiReturn, styp string, str
arg_str_fn_name = styp_to_str_fn_name(field_styp) arg_str_fn_name = styp_to_str_fn_name(field_styp)
} }
if sym.kind == .struct_ && !sym_has_str_method { if sym.kind == .struct_ && !sym_has_str_method {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, ${arg_str_fn_name}(a.arg$i));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, ${arg_str_fn_name}(a.arg$i));')
} else if sym.kind in [.f32, .f64] { } else if sym.kind in [.f32, .f64] {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _STR("%g", 1, a.arg$i));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _STR("%g", 1, a.arg$i));')
} else if sym.kind == .string { } else if sym.kind == .string {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _STR("\'%.*s\\000\'", 2, a.arg$i));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _STR("\'%.*s\\000\'", 2, a.arg$i));')
} else if sym.kind == .function { } else if sym.kind == .function {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, ${arg_str_fn_name}());') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, ${arg_str_fn_name}());')
} else { } else {
if (str_method_expects_ptr && is_arg_ptr) || (!str_method_expects_ptr && !is_arg_ptr) { if (str_method_expects_ptr && is_arg_ptr) || (!str_method_expects_ptr && !is_arg_ptr) {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, ${arg_str_fn_name}(a.arg$i));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, ${arg_str_fn_name}(a.arg$i));')
} else if str_method_expects_ptr && !is_arg_ptr { } else if str_method_expects_ptr && !is_arg_ptr {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, ${arg_str_fn_name}(&a.arg$i));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, ${arg_str_fn_name}(&a.arg$i));')
} else if !str_method_expects_ptr && is_arg_ptr { } else if !str_method_expects_ptr && is_arg_ptr {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, ${arg_str_fn_name}(*a.arg$i));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, ${arg_str_fn_name}(*a.arg$i));')
} }
} }
if i != info.types.len - 1 { if i != info.types.len - 1 {
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT(", "));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT(", "));')
} }
} }
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, _SLIT(")"));') g.auto_str_funcs.writeln('\tstrings__Builder_write_string(&sb, _SLIT(")"));')
g.auto_str_funcs.writeln('\tstring res = strings__Builder_str(&sb);') 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('\tstrings__Builder_free(&sb);')
g.auto_str_funcs.writeln('\treturn res;') g.auto_str_funcs.writeln('\treturn res;')
@ -480,17 +480,17 @@ fn (mut g Gen) gen_str_for_struct(info table.Struct, styp string, str_fn_name st
g.auto_str_funcs.writeln('\t\tindents = string_add(indents, _SLIT(" "));') g.auto_str_funcs.writeln('\t\tindents = string_add(indents, _SLIT(" "));')
g.auto_str_funcs.writeln('\t}') g.auto_str_funcs.writeln('\t}')
if info.fields.len == 0 { if info.fields.len == 0 {
g.auto_str_funcs.write('\treturn _SLIT("$clean_struct_v_type_name{}");') g.auto_str_funcs.write_string('\treturn _SLIT("$clean_struct_v_type_name{}");')
} else { } else {
g.auto_str_funcs.write('\treturn _STR("$clean_struct_v_type_name{\\n"') g.auto_str_funcs.write_string('\treturn _STR("$clean_struct_v_type_name{\\n"')
for field in info.fields { for field in info.fields {
mut fmt := if field.typ.is_ptr() { '&' } else { '' } mut fmt := if field.typ.is_ptr() { '&' } else { '' }
fmt += g.type_to_fmt(field.typ) fmt += g.type_to_fmt(field.typ)
g.auto_str_funcs.writeln('\t\t"%.*s\\000 $field.name: $fmt\\n"') g.auto_str_funcs.writeln('\t\t"%.*s\\000 $field.name: $fmt\\n"')
} }
g.auto_str_funcs.write('\t\t"%.*s\\000}", ${2 * (info.fields.len + 1)}') g.auto_str_funcs.write_string('\t\t"%.*s\\000}", ${2 * (info.fields.len + 1)}')
if info.fields.len > 0 { if info.fields.len > 0 {
g.auto_str_funcs.write(',\n\t\t') g.auto_str_funcs.write_string(',\n\t\t')
for i, field in info.fields { for i, field in info.fields {
sym := g.table.get_type_symbol(field.typ) sym := g.table.get_type_symbol(field.typ)
has_custom_str := sym.has_method('str') has_custom_str := sym.has_method('str')
@ -500,26 +500,26 @@ fn (mut g Gen) gen_str_for_struct(info table.Struct, styp string, str_fn_name st
} else { } else {
fnames2strfunc[field_styp] fnames2strfunc[field_styp]
} }
g.auto_str_funcs.write('indents, ') g.auto_str_funcs.write_string('indents, ')
func := struct_auto_str_func(sym, field.typ, field_styp_fn_name, field.name) func := struct_auto_str_func(sym, field.typ, field_styp_fn_name, field.name)
// reference types can be "nil" // reference types can be "nil"
if field.typ.is_ptr() { if field.typ.is_ptr() {
g.auto_str_funcs.write('isnil(it.${c_name(field.name)})') g.auto_str_funcs.write_string('isnil(it.${c_name(field.name)})')
g.auto_str_funcs.write(' ? _SLIT("nil") : ') g.auto_str_funcs.write_string(' ? _SLIT("nil") : ')
// struct, floats and ints have a special case through the _str function // struct, floats and ints have a special case through the _str function
if sym.kind != .struct_ && !field.typ.is_int() && !field.typ.is_float() { if sym.kind != .struct_ && !field.typ.is_int() && !field.typ.is_float() {
g.auto_str_funcs.write('*') g.auto_str_funcs.write_string('*')
} }
} }
// handle circular ref type of struct to the struct itself // handle circular ref type of struct to the struct itself
if styp == field_styp { if styp == field_styp {
g.auto_str_funcs.write('_SLIT("<circular>")') g.auto_str_funcs.write_string('_SLIT("<circular>")')
} else { } else {
g.auto_str_funcs.write(func) g.auto_str_funcs.write_string(func)
} }
if i < info.fields.len - 1 { if i < info.fields.len - 1 {
g.auto_str_funcs.write(',\n\t\t') g.auto_str_funcs.write_string(',\n\t\t')
} }
} }
} }
@ -647,9 +647,9 @@ fn (mut g Gen) gen_str_for_union_sum_type(info table.SumType, styp string, str_f
if sym.kind == .struct_ && !sym_has_str_method { if sym.kind == .struct_ && !sym_has_str_method {
func_name = 'indent_$func_name' func_name = 'indent_$func_name'
} }
g.auto_str_funcs.write('\t\tcase $typ: return _STR("${clean_sum_type_v_type_name}($value_fmt)", 2, ${func_name}(${deref}($typ_str*)x._$sym.cname') g.auto_str_funcs.write_string('\t\tcase $typ: return _STR("${clean_sum_type_v_type_name}($value_fmt)", 2, ${func_name}(${deref}($typ_str*)x._$sym.cname')
if sym.kind == .struct_ && !sym_has_str_method { if sym.kind == .struct_ && !sym_has_str_method {
g.auto_str_funcs.write(', indent_count') g.auto_str_funcs.write_string(', indent_count')
} }
g.auto_str_funcs.writeln('));') g.auto_str_funcs.writeln('));')
} }

View File

@ -275,71 +275,71 @@ pub fn gen(files []ast.File, table &table.Table, pref &pref.Preferences) string
g.finish() g.finish()
// //
mut b := strings.new_builder(250000) mut b := strings.new_builder(250000)
b.write(g.hashes()) b.write_string(g.hashes())
b.writeln('\n// V comptime_defines:') b.writeln('\n// V comptime_defines:')
b.write(g.comptime_defines.str()) b.write_string(g.comptime_defines.str())
b.writeln('\n// V typedefs:') b.writeln('\n// V typedefs:')
b.write(g.typedefs.str()) b.write_string(g.typedefs.str())
b.writeln('\n// V typedefs2:') b.writeln('\n// V typedefs2:')
b.write(g.typedefs2.str()) b.write_string(g.typedefs2.str())
b.writeln('\n// V cheaders:') b.writeln('\n// V cheaders:')
b.write(g.cheaders.str()) b.write_string(g.cheaders.str())
if g.pcs_declarations.len > 0 { if g.pcs_declarations.len > 0 {
b.writeln('\n// V profile counters:') b.writeln('\n// V profile counters:')
b.write(g.pcs_declarations.str()) b.write_string(g.pcs_declarations.str())
} }
b.writeln('\n// V includes:') b.writeln('\n// V includes:')
b.write(g.includes.str()) b.write_string(g.includes.str())
b.writeln('\n// Enum definitions:') b.writeln('\n// Enum definitions:')
b.write(g.enum_typedefs.str()) b.write_string(g.enum_typedefs.str())
b.writeln('\n// V type definitions:') b.writeln('\n// V type definitions:')
b.write(g.type_definitions.str()) b.write_string(g.type_definitions.str())
b.writeln('\n// V shared types:') b.writeln('\n// V shared types:')
b.write(g.shared_types.str()) b.write_string(g.shared_types.str())
b.writeln('\n// V Option_xxx definitions:') b.writeln('\n// V Option_xxx definitions:')
b.write(g.options.str()) b.write_string(g.options.str())
b.writeln('\n// V json forward decls:') b.writeln('\n// V json forward decls:')
b.write(g.json_forward_decls.str()) b.write_string(g.json_forward_decls.str())
b.writeln('\n// V definitions:') b.writeln('\n// V definitions:')
b.write(g.definitions.str()) b.write_string(g.definitions.str())
interface_table := g.interface_table() interface_table := g.interface_table()
if interface_table.len > 0 { if interface_table.len > 0 {
b.writeln('\n// V interface table:') b.writeln('\n// V interface table:')
b.write(interface_table) b.write_string(interface_table)
} }
if g.gowrappers.len > 0 { if g.gowrappers.len > 0 {
b.writeln('\n// V gowrappers:') b.writeln('\n// V gowrappers:')
b.write(g.gowrappers.str()) b.write_string(g.gowrappers.str())
} }
if g.hotcode_definitions.len > 0 { if g.hotcode_definitions.len > 0 {
b.writeln('\n// V hotcode definitions:') b.writeln('\n// V hotcode definitions:')
b.write(g.hotcode_definitions.str()) b.write_string(g.hotcode_definitions.str())
} }
if g.embedded_data.len > 0 { if g.embedded_data.len > 0 {
b.writeln('\n// V embedded data:') b.writeln('\n// V embedded data:')
b.write(g.embedded_data.str()) b.write_string(g.embedded_data.str())
} }
if g.options_typedefs.len > 0 { if g.options_typedefs.len > 0 {
b.writeln('\n// V option typedefs:') b.writeln('\n// V option typedefs:')
b.write(g.options_typedefs.str()) b.write_string(g.options_typedefs.str())
} }
if g.shared_functions.len > 0 { if g.shared_functions.len > 0 {
b.writeln('\n// V shared type functions:') b.writeln('\n// V shared type functions:')
b.write(g.shared_functions.str()) b.write_string(g.shared_functions.str())
b.write(c_concurrency_helpers) b.write_string(c_concurrency_helpers)
} }
if g.channel_definitions.len > 0 { if g.channel_definitions.len > 0 {
b.writeln('\n// V channel code:') b.writeln('\n// V channel code:')
b.write(g.channel_definitions.str()) b.write_string(g.channel_definitions.str())
} }
if g.stringliterals.len > 0 { if g.stringliterals.len > 0 {
b.writeln('\n// V stringliterals:') b.writeln('\n// V stringliterals:')
b.write(g.stringliterals.str()) b.write_string(g.stringliterals.str())
} }
if g.auto_str_funcs.len > 0 { if g.auto_str_funcs.len > 0 {
// if g.pref.build_mode != .build_module { // if g.pref.build_mode != .build_module {
b.writeln('\n// V auto str functions:') b.writeln('\n// V auto str functions:')
b.write(g.auto_str_funcs.str()) b.write_string(g.auto_str_funcs.str())
// } // }
} }
if g.auto_fn_definitions.len > 0 { if g.auto_fn_definitions.len > 0 {
@ -353,7 +353,7 @@ pub fn gen(files []ast.File, table &table.Table, pref &pref.Preferences) string
} }
} }
b.writeln('\n// V out') b.writeln('\n// V out')
b.write(g.out.str()) b.write_string(g.out.str())
b.writeln('\n// THE END.') b.writeln('\n// THE END.')
g.timers.show('cgen common') g.timers.show('cgen common')
return b.str() return b.str()
@ -593,7 +593,7 @@ fn (mut g Gen) register_optional(t table.Type) string {
} Option2_$no_ptr;') } Option2_$no_ptr;')
// println(styp) // println(styp)
g.typedefs2.writeln('typedef struct $styp $styp;') g.typedefs2.writeln('typedef struct $styp $styp;')
g.options.write(g.optional_type_text(styp, base)) g.options.write_string(g.optional_type_text(styp, base))
g.options.writeln(';\n') g.options.writeln(';\n')
g.optionals << styp.clone() g.optionals << styp.clone()
} }
@ -780,11 +780,11 @@ pub fn (mut g Gen) write_fn_typesymbol_declaration(sym table.TypeSymbol) {
not_anon := !info.is_anon not_anon := !info.is_anon
if !info.has_decl && (not_anon || is_fn_sig) && !func.return_type.has_flag(.generic) { if !info.has_decl && (not_anon || is_fn_sig) && !func.return_type.has_flag(.generic) {
fn_name := sym.cname fn_name := sym.cname
g.type_definitions.write('typedef ${g.typ(func.return_type)} (*$fn_name)(') g.type_definitions.write_string('typedef ${g.typ(func.return_type)} (*$fn_name)(')
for i, param in func.params { for i, param in func.params {
g.type_definitions.write(g.typ(param.typ)) g.type_definitions.write_string(g.typ(param.typ))
if i < func.params.len - 1 { if i < func.params.len - 1 {
g.type_definitions.write(',') g.type_definitions.write_string(',')
} }
} }
g.type_definitions.writeln(');') g.type_definitions.writeln(');')
@ -820,14 +820,14 @@ pub fn (mut g Gen) write(s string) {
} }
if g.indent > 0 && g.empty_line { if g.indent > 0 && g.empty_line {
if g.indent < c.tabs.len { if g.indent < c.tabs.len {
g.out.write(c.tabs[g.indent]) g.out.write_string(c.tabs[g.indent])
} else { } else {
for _ in 0 .. g.indent { for _ in 0 .. g.indent {
g.out.write('\t') g.out.write_string('\t')
} }
} }
} }
g.out.write(s) g.out.write_string(s)
g.empty_line = false g.empty_line = false
} }
@ -837,10 +837,10 @@ pub fn (mut g Gen) writeln(s string) {
} }
if g.indent > 0 && g.empty_line { if g.indent > 0 && g.empty_line {
if g.indent < c.tabs.len { if g.indent < c.tabs.len {
g.out.write(c.tabs[g.indent]) g.out.write_string(c.tabs[g.indent])
} else { } else {
for _ in 0 .. g.indent { for _ in 0 .. g.indent {
g.out.write('\t') g.out.write_string('\t')
} }
} }
} }
@ -1013,20 +1013,20 @@ fn (mut g Gen) stmt(node ast.Stmt) {
mut cur_enum_expr := '' mut cur_enum_expr := ''
mut cur_enum_offset := 0 mut cur_enum_offset := 0
for i, field in node.fields { for i, field in node.fields {
g.enum_typedefs.write('\t${enum_name}_$field.name') g.enum_typedefs.write_string('\t${enum_name}_$field.name')
if field.has_expr { if field.has_expr {
g.enum_typedefs.write(' = ') g.enum_typedefs.write_string(' = ')
pos := g.out.len pos := g.out.len
g.expr(field.expr) g.expr(field.expr)
expr_str := g.out.after(pos) expr_str := g.out.after(pos)
g.out.go_back(expr_str.len) g.out.go_back(expr_str.len)
g.enum_typedefs.write(expr_str) g.enum_typedefs.write_string(expr_str)
cur_enum_expr = expr_str cur_enum_expr = expr_str
cur_enum_offset = 0 cur_enum_offset = 0
} else if is_flag { } else if is_flag {
g.enum_typedefs.write(' = ') g.enum_typedefs.write_string(' = ')
cur_enum_expr = '1 << $i' cur_enum_expr = '1 << $i'
g.enum_typedefs.write((1 << i).str()) g.enum_typedefs.write_string((1 << i).str())
cur_enum_offset = 0 cur_enum_offset = 0
} }
cur_value := if cur_enum_offset > 0 { cur_value := if cur_enum_offset > 0 {
@ -2039,7 +2039,7 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
} }
if right_sym.kind == .function && is_decl { if right_sym.kind == .function && is_decl {
if is_inside_ternary && is_decl { if is_inside_ternary && is_decl {
g.out.write(c.tabs[g.indent - g.inside_ternary]) g.out.write_string(c.tabs[g.indent - g.inside_ternary])
} }
func := right_sym.info as table.FnType func := right_sym.info as table.FnType
ret_styp := g.typ(func.func.return_type) ret_styp := g.typ(func.func.return_type)
@ -2051,7 +2051,7 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
} else { } else {
if is_decl { if is_decl {
if is_inside_ternary { if is_inside_ternary {
g.out.write(c.tabs[g.indent - g.inside_ternary]) g.out.write_string(c.tabs[g.indent - g.inside_ternary])
} }
g.write('$styp ') g.write('$styp ')
} }
@ -2067,7 +2067,7 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
} }
if is_inside_ternary && is_decl { if is_inside_ternary && is_decl {
g.write(';\n$cur_line') g.write(';\n$cur_line')
g.out.write(c.tabs[g.indent]) g.out.write_string(c.tabs[g.indent])
g.expr(left) g.expr(left)
} }
g.is_assign_lhs = false g.is_assign_lhs = false
@ -2748,7 +2748,7 @@ fn (mut g Gen) expr(node ast.Expr) {
is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs
cur_line := if is_gen_or_and_assign_rhs { cur_line := if is_gen_or_and_assign_rhs {
line := g.go_before_stmt(0) line := g.go_before_stmt(0)
g.out.write(c.tabs[g.indent]) g.out.write_string(c.tabs[g.indent])
line line
} else { } else {
'' ''
@ -4305,7 +4305,7 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) {
is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs
cur_line := if is_gen_or_and_assign_rhs { cur_line := if is_gen_or_and_assign_rhs {
line := g.go_before_stmt(0) line := g.go_before_stmt(0)
g.out.write(c.tabs[g.indent]) g.out.write_string(c.tabs[g.indent])
line line
} else { } else {
'' ''
@ -4471,7 +4471,7 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) {
is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs
cur_line := if is_gen_or_and_assign_rhs { cur_line := if is_gen_or_and_assign_rhs {
line := g.go_before_stmt(0) line := g.go_before_stmt(0)
g.out.write(c.tabs[g.indent]) g.out.write_string(c.tabs[g.indent])
line line
} else { } else {
'' ''
@ -4841,7 +4841,7 @@ fn (mut g Gen) const_decl_simple_define(name string, val string) {
// so that we don't pollute the binary with unnecessary global vars // so that we don't pollute the binary with unnecessary global vars
// Do not do this when building a module, otherwise the consts // Do not do this when building a module, otherwise the consts
// will not be accessible. // will not be accessible.
g.definitions.write('#define _const_$name ') g.definitions.write_string('#define _const_$name ')
g.definitions.writeln(val) g.definitions.writeln(val)
} }
@ -5305,7 +5305,7 @@ fn (mut g Gen) write_types(types []table.TypeSymbol) {
g.typedefs2.writeln('typedef struct $styp $styp;') g.typedefs2.writeln('typedef struct $styp $styp;')
g.type_definitions.writeln('${g.optional_type_text(styp, g.type_definitions.writeln('${g.optional_type_text(styp,
base)};') base)};')
g.type_definitions.write(last_text) g.type_definitions.write_string(last_text)
} }
} }
type_name := g.typ(field.typ) type_name := g.typ(field.typ)
@ -5910,25 +5910,25 @@ fn (mut g Gen) go_stmt(node ast.GoStmt, joinable bool) string {
g.gowrappers.writeln('$thread_ret_type ${wrapper_fn_name}($wrapper_struct_name *arg) {') g.gowrappers.writeln('$thread_ret_type ${wrapper_fn_name}($wrapper_struct_name *arg) {')
if node.call_expr.return_type != table.void_type { if node.call_expr.return_type != table.void_type {
if g.pref.os == .windows { if g.pref.os == .windows {
g.gowrappers.write('\t*(($s_ret_typ*)(arg->ret_ptr)) = ') g.gowrappers.write_string('\t*(($s_ret_typ*)(arg->ret_ptr)) = ')
} else { } else {
g.gowrappers.writeln('\t$s_ret_typ* ret_ptr = malloc(sizeof($s_ret_typ));') g.gowrappers.writeln('\t$s_ret_typ* ret_ptr = malloc(sizeof($s_ret_typ));')
g.gowrappers.write('\t*ret_ptr = ') g.gowrappers.write_string('\t*ret_ptr = ')
} }
} else { } else {
g.gowrappers.write('\t') g.gowrappers.write_string('\t')
} }
g.gowrappers.write('${name}(') g.gowrappers.write_string('${name}(')
if expr.is_method { if expr.is_method {
g.gowrappers.write('arg->arg0') g.gowrappers.write_string('arg->arg0')
if expr.args.len > 0 { if expr.args.len > 0 {
g.gowrappers.write(', ') g.gowrappers.write_string(', ')
} }
} }
for i in 0 .. expr.args.len { for i in 0 .. expr.args.len {
g.gowrappers.write('arg->arg${i + 1}') g.gowrappers.write_string('arg->arg${i + 1}')
if i < expr.args.len - 1 { if i < expr.args.len - 1 {
g.gowrappers.write(', ') g.gowrappers.write_string(', ')
} }
} }
g.gowrappers.writeln(');') g.gowrappers.writeln(');')
@ -6039,11 +6039,11 @@ fn (mut g Gen) interface_table() string {
methodidx[method.name] = k methodidx[method.name] = k
typ_name := '_${interface_name}_${method.name}_fn' typ_name := '_${interface_name}_${method.name}_fn'
ret_styp := g.typ(method.return_type) ret_styp := g.typ(method.return_type)
methods_typ_def.write('typedef $ret_styp (*$typ_name)(void* _') methods_typ_def.write_string('typedef $ret_styp (*$typ_name)(void* _')
// the first param is the receiver, it's handled by `void*` above // the first param is the receiver, it's handled by `void*` above
for i in 1 .. method.params.len { for i in 1 .. method.params.len {
arg := method.params[i] arg := method.params[i]
methods_typ_def.write(', ${g.typ(arg.typ)} $arg.name') methods_typ_def.write_string(', ${g.typ(arg.typ)} $arg.name')
} }
// TODO g.fn_args(method.args[1..], method.is_variadic) // TODO g.fn_args(method.args[1..], method.is_variadic)
methods_typ_def.writeln(');') methods_typ_def.writeln(');')
@ -6101,7 +6101,7 @@ fn (mut g Gen) interface_table() string {
field_styp := g.typ(field.typ) field_styp := g.typ(field.typ)
cast_struct.writeln('\t\t.$cname = ($field_styp*)((char*)x + __offsetof($cctype, $cname)),') cast_struct.writeln('\t\t.$cname = ($field_styp*)((char*)x + __offsetof($cctype, $cname)),')
} }
cast_struct.write('\t}') cast_struct.write_string('\t}')
cast_struct_str := cast_struct.str() cast_struct_str := cast_struct.str()
cast_functions.writeln(' cast_functions.writeln('
@ -6135,8 +6135,8 @@ $staticprefix $interface_name* I_${cctype}_to_Interface_${interface_name}_ptr($c
mut method_call := '${cctype}_$method.name' mut method_call := '${cctype}_$method.name'
if !method.params[0].typ.is_ptr() { if !method.params[0].typ.is_ptr() {
// inline void Cat_speak_method_wrapper(Cat c) { return Cat_speak(*c); } // inline void Cat_speak_method_wrapper(Cat c) { return Cat_speak(*c); }
methods_wrapper.write('static inline ${g.typ(method.return_type)}') methods_wrapper.write_string('static inline ${g.typ(method.return_type)}')
methods_wrapper.write(' ${method_call}_method_wrapper(') methods_wrapper.write_string(' ${method_call}_method_wrapper(')
// //
params_start_pos := g.out.len params_start_pos := g.out.len
mut params := method.params.clone() mut params := method.params.clone()
@ -6146,11 +6146,11 @@ $staticprefix $interface_name* I_${cctype}_to_Interface_${interface_name}_ptr($c
typ: params[0].typ.set_nr_muls(1) typ: params[0].typ.set_nr_muls(1)
} }
fargs, _ := g.fn_args(params, false) // second argument is ignored anyway fargs, _ := g.fn_args(params, false) // second argument is ignored anyway
methods_wrapper.write(g.out.cut_last(g.out.len - params_start_pos)) methods_wrapper.write_string(g.out.cut_last(g.out.len - params_start_pos))
methods_wrapper.writeln(') {') methods_wrapper.writeln(') {')
methods_wrapper.write('\t') methods_wrapper.write_string('\t')
if method.return_type != table.void_type { if method.return_type != table.void_type {
methods_wrapper.write('return ') methods_wrapper.write_string('return ')
} }
methods_wrapper.writeln('${method_call}(*${fargs.join(', ')});') methods_wrapper.writeln('${method_call}(*${fargs.join(', ')});')
methods_wrapper.writeln('}') methods_wrapper.writeln('}')

View File

@ -44,16 +44,16 @@ fn (mut g Gen) gen_embedded_data() {
*/ */
for i, emfile in g.embedded_files { for i, emfile in g.embedded_files {
fbytes := os.read_bytes(emfile.apath) or { panic('Error while embedding file: $err') } fbytes := os.read_bytes(emfile.apath) or { panic('Error while embedding file: $err') }
g.embedded_data.write('static const unsigned char _v_embed_blob_$i[$fbytes.len] = {\n ') g.embedded_data.write_string('static const unsigned char _v_embed_blob_$i[$fbytes.len] = {\n ')
for j := 0; j < fbytes.len; j++ { for j := 0; j < fbytes.len; j++ {
b := fbytes[j].hex() b := fbytes[j].hex()
if j < fbytes.len - 1 { if j < fbytes.len - 1 {
g.embedded_data.write('0x$b,') g.embedded_data.write_string('0x$b,')
} else { } else {
g.embedded_data.write('0x$b') g.embedded_data.write_string('0x$b')
} }
if 0 == ((j + 1) % 16) { if 0 == ((j + 1) % 16) {
g.embedded_data.write('\n ') g.embedded_data.write_string('\n ')
} }
} }
g.embedded_data.writeln('\n};') g.embedded_data.writeln('\n};')

View File

@ -213,11 +213,11 @@ fn (mut g Gen) gen_fn_decl(node ast.FnDecl, skip bool) {
// //
if is_live_wrap { if is_live_wrap {
if is_livemain { if is_livemain {
g.definitions.write('$type_name (* $impl_fn_name)(') g.definitions.write_string('$type_name (* $impl_fn_name)(')
g.write('$type_name no_impl_${name}(') g.write('$type_name no_impl_${name}(')
} }
if is_liveshared { if is_liveshared {
g.definitions.write('$type_name ${impl_fn_name}(') g.definitions.write_string('$type_name ${impl_fn_name}(')
g.write('$type_name ${impl_fn_name}(') g.write('$type_name ${impl_fn_name}(')
} }
} else { } else {
@ -229,7 +229,7 @@ fn (mut g Gen) gen_fn_decl(node ast.FnDecl, skip bool) {
// If we are building vlib/builtin, we need all private functions like array_get // If we are building vlib/builtin, we need all private functions like array_get
// to be public, so that all V programs can access them. // to be public, so that all V programs can access them.
g.write('VV_LOCAL_SYMBOL ') g.write('VV_LOCAL_SYMBOL ')
g.definitions.write('VV_LOCAL_SYMBOL ') g.definitions.write_string('VV_LOCAL_SYMBOL ')
} }
} }
fn_header := if msvc_attrs.len > 0 { fn_header := if msvc_attrs.len > 0 {
@ -237,7 +237,7 @@ fn (mut g Gen) gen_fn_decl(node ast.FnDecl, skip bool) {
} else { } else {
'$type_name ${name}(' '$type_name ${name}('
} }
g.definitions.write(fn_header) g.definitions.write_string(fn_header)
g.write(fn_header) g.write(fn_header)
} }
arg_start_pos := g.out.len arg_start_pos := g.out.len
@ -361,26 +361,26 @@ fn (mut g Gen) fn_args(args []table.Param, is_variadic bool) ([]string, []string
func := info.func func := info.func
if !info.is_anon { if !info.is_anon {
g.write(arg_type_name + ' ' + caname) g.write(arg_type_name + ' ' + caname)
g.definitions.write(arg_type_name + ' ' + caname) g.definitions.write_string(arg_type_name + ' ' + caname)
fargs << caname fargs << caname
fargtypes << arg_type_name fargtypes << arg_type_name
} else { } else {
g.write('${g.typ(func.return_type)} (*$caname)(') g.write('${g.typ(func.return_type)} (*$caname)(')
g.definitions.write('${g.typ(func.return_type)} (*$caname)(') g.definitions.write_string('${g.typ(func.return_type)} (*$caname)(')
g.fn_args(func.params, func.is_variadic) g.fn_args(func.params, func.is_variadic)
g.write(')') g.write(')')
g.definitions.write(')') g.definitions.write_string(')')
} }
} else { } else {
s := '$arg_type_name $caname' s := '$arg_type_name $caname'
g.write(s) g.write(s)
g.definitions.write(s) g.definitions.write_string(s)
fargs << caname fargs << caname
fargtypes << arg_type_name fargtypes << arg_type_name
} }
if i < args.len - 1 { if i < args.len - 1 {
g.write(', ') g.write(', ')
g.definitions.write(', ') g.definitions.write_string(', ')
} }
} }
return fargs, fargtypes return fargs, fargtypes
@ -411,7 +411,7 @@ fn (mut g Gen) call_expr(node ast.CallExpr) {
is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs is_gen_or_and_assign_rhs := gen_or && g.is_assign_rhs
cur_line := if is_gen_or_and_assign_rhs && !g.is_autofree { cur_line := if is_gen_or_and_assign_rhs && !g.is_autofree {
line := g.go_before_stmt(0) line := g.go_before_stmt(0)
g.out.write(tabs[g.indent]) g.out.write_string(tabs[g.indent])
line line
} else { } else {
'' ''

View File

@ -155,7 +155,7 @@ fn (mut g Gen) string_inter_literal_sb_optimized(call_expr ast.CallExpr) {
// break // break
// continue // continue
// } // }
g.write('strings__Builder_write(&') g.write('strings__Builder_write_string(&')
g.expr(call_expr.left) g.expr(call_expr.left)
g.write(', _SLIT("') g.write(', _SLIT("')
g.write(escaped_val) g.write(escaped_val)
@ -170,7 +170,7 @@ fn (mut g Gen) string_inter_literal_sb_optimized(call_expr ast.CallExpr) {
if is_nl && i == node.exprs.len - 1 { if is_nl && i == node.exprs.len - 1 {
g.write('strings__Builder_writeln(&') g.write('strings__Builder_writeln(&')
} else { } else {
g.write('strings__Builder_write(&') g.write('strings__Builder_write_string(&')
} }
g.expr(call_expr.left) g.expr(call_expr.left)
g.write(', ') g.write(', ')

View File

@ -250,7 +250,7 @@ fn verror(msg string) {
[inline] [inline]
pub fn (mut g JsGen) gen_indent() { pub fn (mut g JsGen) gen_indent() {
if g.ns.indent > 0 && g.empty_line { if g.ns.indent > 0 && g.empty_line {
g.ns.out.write(js.tabs[g.ns.indent]) g.ns.out.write_string(js.tabs[g.ns.indent])
} }
g.empty_line = false g.empty_line = false
} }
@ -271,7 +271,7 @@ pub fn (mut g JsGen) write(s string) {
verror('g.write: not in a namespace') verror('g.write: not in a namespace')
} }
g.gen_indent() g.gen_indent()
g.ns.out.write(s) g.ns.out.write_string(s)
} }
[inline] [inline]

View File

@ -885,33 +885,33 @@ pub struct FnSignatureOpts {
pub fn (t &Table) fn_signature(func &Fn, opts FnSignatureOpts) string { pub fn (t &Table) fn_signature(func &Fn, opts FnSignatureOpts) string {
mut sb := strings.new_builder(20) mut sb := strings.new_builder(20)
if !opts.skip_receiver { if !opts.skip_receiver {
sb.write('fn ') sb.write_string('fn ')
// TODO write receiver // TODO write receiver
} }
if !opts.type_only { if !opts.type_only {
sb.write('$func.name') sb.write_string('$func.name')
} }
sb.write('(') sb.write_string('(')
start := int(opts.skip_receiver) start := int(opts.skip_receiver)
for i in start .. func.params.len { for i in start .. func.params.len {
if i != start { if i != start {
sb.write(', ') sb.write_string(', ')
} }
param := func.params[i] param := func.params[i]
mut typ := param.typ mut typ := param.typ
if param.is_mut { if param.is_mut {
typ = typ.deref() typ = typ.deref()
sb.write('mut ') sb.write_string('mut ')
} }
if !opts.type_only { if !opts.type_only {
sb.write('$param.name ') sb.write_string('$param.name ')
} }
styp := t.type_to_str(typ) styp := t.type_to_str(typ)
sb.write('$styp') sb.write_string('$styp')
} }
sb.write(')') sb.write_string(')')
if func.return_type != table.void_type { if func.return_type != table.void_type {
sb.write(' ${t.type_to_str(func.return_type)}') sb.write_string(' ${t.type_to_str(func.return_type)}')
} }
return sb.str() return sb.str()
} }

View File

@ -90,7 +90,7 @@ pub fn smart_quote(str string, raw bool) string {
toadd = '\\n' toadd = '\\n'
} }
} }
result.write(toadd) result.write_string(toadd)
last = current last = current
} }
return result.str() return result.str()

View File

@ -45,14 +45,14 @@ pub fn new_connection(conn &net.TcpConn) &SSEConnection {
pub fn (mut sse SSEConnection) start() ? { pub fn (mut sse SSEConnection) start() ? {
sse.conn.set_write_timeout(sse.write_timeout) sse.conn.set_write_timeout(sse.write_timeout)
mut start_sb := strings.new_builder(512) mut start_sb := strings.new_builder(512)
start_sb.write('HTTP/1.1 200') start_sb.write_string('HTTP/1.1 200')
start_sb.write('\r\nConnection: keep-alive') start_sb.write_string('\r\nConnection: keep-alive')
start_sb.write('\r\nCache-Control: no-cache') start_sb.write_string('\r\nCache-Control: no-cache')
start_sb.write('\r\nContent-Type: text/event-stream') start_sb.write_string('\r\nContent-Type: text/event-stream')
for k, v in sse.headers { for k, v in sse.headers {
start_sb.write('\r\n$k: $v') start_sb.write_string('\r\n$k: $v')
} }
start_sb.write('\r\n') start_sb.write_string('\r\n')
sse.conn.write(start_sb.buf) or { return error('could not start sse response') } sse.conn.write(start_sb.buf) or { return error('could not start sse response') }
} }
@ -61,17 +61,17 @@ pub fn (mut sse SSEConnection) start() ? {
pub fn (mut sse SSEConnection) send_message(message SSEMessage) ? { pub fn (mut sse SSEConnection) send_message(message SSEMessage) ? {
mut sb := strings.new_builder(512) mut sb := strings.new_builder(512)
if message.id != '' { if message.id != '' {
sb.write('id: $message.id\n') sb.write_string('id: $message.id\n')
} }
if message.event != '' { if message.event != '' {
sb.write('event: $message.event\n') sb.write_string('event: $message.event\n')
} }
if message.data != '' { if message.data != '' {
sb.write('data: $message.data\n') sb.write_string('data: $message.data\n')
} }
if message.retry != 0 { if message.retry != 0 {
sb.write('retry: $message.retry\n') sb.write_string('retry: $message.retry\n')
} }
sb.write('\n') sb.write_string('\n')
sse.conn.write(sb.buf) ? sse.conn.write(sb.buf) ?
} }

View File

@ -7,7 +7,7 @@ import os
import strings import strings
const ( const (
str_start = "sb.write('" str_start = "sb.write_string('"
str_end = "' ) " str_end = "' ) "
) )
@ -58,7 +58,7 @@ footer := \' \' // TODO remove
_ = footer _ = footer
") ")
s.write(tmpl.str_start) s.write_string(tmpl.str_start)
mut state := State.html mut state := State.html
mut in_span := false mut in_span := false
// for _line in lines { // for _line in lines {
@ -87,13 +87,13 @@ _ = footer
i-- i--
} else if line.contains('@js ') { } else if line.contains('@js ') {
pos := line.index('@js') or { continue } pos := line.index('@js') or { continue }
s.write('<script src="') s.write_string('<script src="')
s.write(line[pos + 5..line.len - 1]) s.write_string(line[pos + 5..line.len - 1])
s.writeln('"></script>') s.writeln('"></script>')
} else if line.contains('@css ') { } else if line.contains('@css ') {
pos := line.index('@css') or { continue } pos := line.index('@css') or { continue }
s.write('<link href="') s.write_string('<link href="')
s.write(line[pos + 6..line.len - 1]) s.write_string(line[pos + 6..line.len - 1])
s.writeln('" rel="stylesheet" type="text/css">') s.writeln('" rel="stylesheet" type="text/css">')
} else if line.contains('@if ') { } else if line.contains('@if ') {
s.writeln(tmpl.str_end) s.writeln(tmpl.str_end)

View File

@ -96,15 +96,15 @@ pub fn (mut ctx Context) send_response_to_client(mimetype string, res string) bo
defer { defer {
unsafe { sb.free() } unsafe { sb.free() }
} }
sb.write('HTTP/1.1 $ctx.status') sb.write_string('HTTP/1.1 $ctx.status')
sb.write('\r\nContent-Type: $mimetype') sb.write_string('\r\nContent-Type: $mimetype')
sb.write('\r\nContent-Length: $res.len') sb.write_string('\r\nContent-Length: $res.len')
if ctx.chunked_transfer { if ctx.chunked_transfer {
sb.write('\r\nTransfer-Encoding: chunked') sb.write_string('\r\nTransfer-Encoding: chunked')
} }
sb.write(ctx.headers) sb.write_string(ctx.headers)
sb.write('\r\n') sb.write_string('\r\n')
sb.write(vweb.headers_close) sb.write_string(vweb.headers_close)
if ctx.chunked_transfer { if ctx.chunked_transfer {
mut i := 0 mut i := 0
mut len := res.len mut len := res.len
@ -121,12 +121,12 @@ pub fn (mut ctx Context) send_response_to_client(mimetype string, res string) bo
chunk = res[i..] chunk = res[i..]
len = 0 len = 0
} }
sb.write(chunk.len.hex()) sb.write_string(chunk.len.hex())
sb.write('\r\n$chunk\r\n') sb.write_string('\r\n$chunk\r\n')
} }
sb.write('0\r\n\r\n') // End of chunks sb.write_string('0\r\n\r\n') // End of chunks
} else { } else {
sb.write(res) sb.write_string(res)
} }
s := sb.str() s := sb.str()
defer { defer {

View File

@ -8,9 +8,9 @@ import strings
fn write_value(v Any, i int, len int, mut wr strings.Builder) { fn write_value(v Any, i int, len int, mut wr strings.Builder) {
str := v.str() str := v.str()
if v is string { if v is string {
wr.write('"$str"') wr.write_string('"$str"')
} else { } else {
wr.write(str) wr.write_string(str)
} }
if i >= len - 1 { if i >= len - 1 {
return return
@ -24,7 +24,7 @@ pub fn (flds map[string]Any) str() string {
wr.write_b(`{`) wr.write_b(`{`)
mut i := 0 mut i := 0
for k, v in flds { for k, v in flds {
wr.write('"$k":') wr.write_string('"$k":')
write_value(v, i, flds.len, mut wr) write_value(v, i, flds.len, mut wr)
i++ i++
} }

View File

@ -154,7 +154,7 @@ ffbf ffff bf00 0000 0000 0000 0000 0000
fn save_raw_data_as_array(buf_bin []byte, file_name string) { fn save_raw_data_as_array(buf_bin []byte, file_name string) {
mut buf := strings.new_builder(buf_bin.len * 5) mut buf := strings.new_builder(buf_bin.len * 5)
for x in buf_bin { for x in buf_bin {
buf.write('0x${x:02x},') buf.write_string('0x${x:02x},')
} }
os.write_file_array(file_name, buf.buf) or { panic(err) } os.write_file_array(file_name, buf.buf) or { panic(err) }
} }

View File

@ -12,17 +12,17 @@ fn (mut ws Client) handshake() ? {
defer { defer {
unsafe { sb.free() } unsafe { sb.free() }
} }
sb.write('GET ') sb.write_string('GET ')
sb.write(ws.uri.resource) sb.write_string(ws.uri.resource)
sb.write(ws.uri.querystring) sb.write_string(ws.uri.querystring)
sb.write(' HTTP/1.1\r\nHost: ') sb.write_string(' HTTP/1.1\r\nHost: ')
sb.write(ws.uri.hostname) sb.write_string(ws.uri.hostname)
sb.write(':') sb.write_string(':')
sb.write(ws.uri.port) sb.write_string(ws.uri.port)
sb.write('\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n') sb.write_string('\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n')
sb.write('Sec-WebSocket-Key: ') sb.write_string('Sec-WebSocket-Key: ')
sb.write(seckey) sb.write_string(seckey)
sb.write('\r\nSec-WebSocket-Version: 13\r\n\r\n') sb.write_string('\r\nSec-WebSocket-Version: 13\r\n\r\n')
handshake := sb.str() handshake := sb.str()
defer { defer {
unsafe { handshake.free() } unsafe { handshake.free() }