11module c
22
3+ import strings
4+
35const c_reserved_words = ['auto' , 'break' , 'case' , 'char' , 'const' , 'continue' , 'copy' , 'default' ,
46 'do' , 'double' , 'else' , 'enum' , 'extern' , 'float' , 'for' , 'goto' , 'if' , 'inline' , 'int' , 'long' ,
57 'register' , 'restrict' , 'return' , 'short' , 'signed' , 'sizeof' , 'static' , 'struct' , 'switch' ,
@@ -19,15 +21,105 @@ fn c_name(name string) string {
1921 if name == 'exit' {
2022 return 'v_exit'
2123 }
22- n := name.replace ('[]' , 'Array_' ).replace ('.-' , '__minus' ).replace ('.+' , '__plus' ).replace ('.==' ,
23- '__eq' ).replace ('.!=' , '__ne' ).replace ('.<=' , '__le' ).replace ('.>=' , '__ge' ).replace ('.<' ,
24- '__lt' ).replace ('.>' , '__gt' ).replace ('&' , 'ptr' ).replace ('[' , '_' ).replace (']' , '' ).replace (',' , '_' ).replace (' ' , '_' ).replace ('.' , '__' )
24+ if c_name_is_plain (name) {
25+ if name in c_reserved_words {
26+ return 'v_${name }'
27+ }
28+ return name
29+ }
30+ n := c_name_sanitize (name)
2531 if n in c_reserved_words {
2632 return 'v_${n }'
2733 }
2834 return n
2935}
3036
37+ fn c_name_sanitize (name string ) string {
38+ mut b := strings.new_builder (name.len + 8 )
39+ mut i := 0
40+ for i < name.len {
41+ c := name[i]
42+ if c == `[` {
43+ if i + 1 < name.len && name[i + 1 ] == `]` {
44+ b.write_string ('Array_' )
45+ i + = 2
46+ continue
47+ }
48+ b.write_u8 (`_` )
49+ } else if c == `]` {
50+ i++
51+ continue
52+ } else if c == `.` {
53+ if i + 1 < name.len {
54+ next := name[i + 1 ]
55+ if next == `-` {
56+ b.write_string ('__minus' )
57+ i + = 2
58+ continue
59+ }
60+ if next == `+` {
61+ b.write_string ('__plus' )
62+ i + = 2
63+ continue
64+ }
65+ if i + 2 < name.len {
66+ op := name[i + 2 ]
67+ if next == `=` && op == `=` {
68+ b.write_string ('__eq' )
69+ i + = 3
70+ continue
71+ }
72+ if next == `!` && op == `=` {
73+ b.write_string ('__ne' )
74+ i + = 3
75+ continue
76+ }
77+ if next == `<` && op == `=` {
78+ b.write_string ('__le' )
79+ i + = 3
80+ continue
81+ }
82+ if next == `>` && op == `=` {
83+ b.write_string ('__ge' )
84+ i + = 3
85+ continue
86+ }
87+ }
88+ if next == `<` {
89+ b.write_string ('__lt' )
90+ i + = 2
91+ continue
92+ }
93+ if next == `>` {
94+ b.write_string ('__gt' )
95+ i + = 2
96+ continue
97+ }
98+ }
99+ b.write_string ('__' )
100+ } else if c == `&` {
101+ b.write_string ('ptr' )
102+ } else if c == `,` || c == ` ` {
103+ b.write_u8 (`_` )
104+ } else {
105+ b.write_u8 (c)
106+ }
107+ i++
108+ }
109+ return b.str ()
110+ }
111+
112+ fn c_name_is_plain (name string ) bool {
113+ for i in 0 .. name.len {
114+ c := name[i]
115+ if (c > = `a` && c < = `z` ) || (c > = `A` && c < = `Z` ) || (c > = `0` && c < = `9` ) || c == `_` {
116+ continue
117+ }
118+ return false
119+ }
120+ return true
121+ }
122+
31123fn c_escape (s string ) string {
32124 return s.replace ('\\ ' , '\\\\ ' ).replace ('"' , '\\ "' ).replace ('\n ' , '\\ n' ).replace ('\t ' , '\\ t' ).replace ('\r ' ,
33125 '\\ r' )
0 commit comments