V语言抽象语法树(AST)

V语言所有的语法树结构体都在标准库的v.ast子模块中定义.

主要是通过联合类型来实现,用联合类型来实现语法树,代码显得非常的简洁,清晰.

v ast子命令

可使用v ast子命令来生成语法树结构,这样你就可以边写代码,边查看代码对应的语法树,有助于加深对V语言语法树的理解.

1. v ast main.v       //生成json格式的AST语法树文件main.json
2. v ast -w main.v    //生成main.json,并且监控源文件变化,保存后自动重新生成
3. v ast -c main.v    //同时生成AST语法树文件main.json和C源代码main.c,并监控源文件变化,保存后自动重新生成

使用v ast子命令,将本章节中的示例代码生成语法树,即可查看到各种不同代码对应的语法树.

语法树结构体总览

V抽象语法树 - 图1

ast.File语法树文件

整个编译过程主要的步骤就是: [ ]os.File => [ ]ast.File => 目标代码(c/x64/js) => 可执行文件.

一个os.File(源代码文件)会生成一个对应的ast.File(语法树文件).

AST结构体

1. File 语法树文件

示例代码

1. module main

3. import os
4. import time

6. fn main() {

8. }

生成的AST:

整个源文件的所有语句都保存在stmts语句数组节点中

1. {
2. "ast_type": "ast.File",
3. "path": "/Users/xxx/v/vprojects/v_test/main.v",
4. "mod": {
5. "ast_type": "Module",
6. "name": "main",
7. "is_skipped": false,
8. "pos": {
9. "line_nr": 0,
10. "pos": 0,
11. "len": 19
12. }
13. },
14. "imports": [
15. {
16. "ast_type": "Import",
17. "mod": "os",
18. "alias": "os",
19. "syms": [],
20. "pos": {
21. "line_nr": 2,
22. "pos": 20,
23. "len": 2
24. }
25. },
26. {
27. "ast_type": "Import",
28. "mod": "time",
29. "alias": "time",
30. "syms": [],
31. "pos": {
32. "line_nr": 3,
33. "pos": 30,
34. "len": 4
35. }
36. }
37. ],
38. "global_scope": {
39. "ast_type": "Scope",
40. "parent": "0",
41. "children": [],
42. "start_pos": 0,
43. "end_pos": 0,
44. "objects": {},
45. "struct_fields": []
46. },
47. "scope": {
48. "ast_type": "Scope",
49. "parent": "7f970ef07c90",
50. "children": [
51. {
52. "parent": "7f970ef081f0",
53. "start_pos": 39,
54. "end_pos": 51
55. }
56. ],
57. "start_pos": 0,
58. "end_pos": 53,
59. "objects": {},
60. "struct_fields": []
61. },
62. "errors": [],
63. "warnings": [],
64. "imported_symbols": {},
65. "generic_fns": [],
66. "stmts": [
67. {
68. "ast_type": "Module",
69. "name": "main",
70. "is_skipped": false,
71. "pos": {
72. "line_nr": 0,
73. "pos": 0,
74. "len": 19
75. }
76. },
77. {
78. "ast_type": "Import",
79. "mod": "os",
80. "alias": "os",
81. "syms": [],
82. "pos": {
83. "line_nr": 2,
84. "pos": 20,
85. "len": 2
86. }
87. },
88. {
89. "ast_type": "Import",
90. "mod": "time",
91. "alias": "time",
92. "syms": [],
93. "pos": {
94. "line_nr": 3,
95. "pos": 30,
96. "len": 4
97. }
98. },
99. {
100. "ast_type": "FnDecl",
101. "name": "main.main",
102. "mod": "main",
103. "is_deprecated": false,
104. "is_pub": false,
105. "is_variadic": false,
106. "is_anon": false,
107. "receiver": {
108. "ast_type": "Field",
109. "name": "",
110. "typ": "void",
111. "pos": {
112. "line_nr": 0,
113. "pos": 0,
114. "len": 0
115. }
116. },
117. "receiver_pos": {
118. "line_nr": 0,
119. "pos": 0,
120. "len": 0
121. },
122. "is_method": false,
123. "method_idx": 0,
124. "rec_mut": false,
125. "rec_share": "enum:0(mut)",
126. "language": "enum:0(v)",
127. "no_body": false,
128. "is_builtin": false,
129. "is_generic": false,
130. "is_direct_arr": false,
131. "pos": {
132. "line_nr": 5,
133. "pos": 36,
134. "len": 9
135. },
136. "body_pos": {
137. "line_nr": 7,
138. "pos": 51,
139. "len": 1
140. },
141. "file": "/Users/xxx/v/vprojects/v_test/main.v",
142. "return_type": "void",
143. "source_file": 0,
144. "scope": 250645264,
145. "attrs": [],
146. "params": [],
147. "stmts": [],
148. "comments": [],
149. "next_comments": []
150. }
151. ]
152. }

Module 模块

AST结构体

1. Module 模块声明语句
2. Import 模块导入语句

示例代码

1. module  main

3. import os // comment for mod
4. //comment for time
5. import time as t
6. import math { min, max }

8. fn main() {

10. }

Const 常量

AST结构体

1. ConstDecl 常量声明语句
2. ConstField 常量字段

示例代码

1. module main

3. pub const p = 3.14
4. const (
5. // version comment 1
6. version = '0.2.0' // version comment 2
7. usage   = 'usage:xxxx'
8. pi      = 3.14
9. //end comment 1
10. //end comment 2
11. )

Enum 枚举

1. EnumDecl 枚举声明语句
2. EnumField 枚举字段语句
3. EnumVal 枚举值表达式

示例代码

1. module main

3. [attr1]
4. ['attr2:123']
5. enum Color { // enum comment 1
6. // black comment 1
7. // black comment 2
8. black = 2 // black comment 3
9. // white comment 1
10. // white comment 2
11. white // white comment 3
12. blue
13. green // green comment
14. // end comment 1
15. // end comment 2
16. }

18. [flag]
19. enum BitEnum {
20. e1
21. e2
22. e3
23. }

25. [_allow_multiple_values]
26. enum MultipleEnum {
27. v1 = 1
28. }

30. fn main() {
31. mut color := Color.black
32. color = .blue
33. }

Variable 变量

Assign 变量赋值语句

AST结构体

1. AssignStmt 变量赋值语句
2. Var 变量

示例代码

1. module main

3. fn main() {
4. // an assignment
5. a := 'abc' // comment for a
6. mut b := 1
7. // more operator
8. b = 2
9. b += 2
10. b -= 2
11. b *= 2
12. b /= 2
13. b %= 2
14. // multi assign
15. x, y, z := 1, 'y', 3.3
16. mut xx, mut yy, zz := 1, 3, 5
17. // swap variable
18. mut c := 1
19. mut d := 2
20. c, d = d, c
21. }

Identifier 标识符

AST结构体

1. Ident 标识符表达式
2. IdentFn 函数标识符
3. IdentVar 变量标识符

示例代码

1. module main

3. fn main() {
4. i := 123 // common(unresolved) identifier
5. _, x := 1, 2 // blank identifier
6. mut s := 'abc' // with mut
7. s = 'aaa'
8. }

Literal 字面量

AST结构体

1. IntegerLiteral 整数字面量
2. FloatLiteral    小数字面量
3. StringLiteral    字符串字面量
4. StringInterLiteral 字符串模板字面量
5. CharLiteral 单字符字面量
6. BoolLiteral 布尔值字面量

示例代码

1. module main

3. fn main() {
4. a := 1 // integer literal
5. b := 1.2 // float literal
6. c := 'abc' // string literal
7. name:='tom'
8. age:= 33
9. //string literal with `$xx` or `${xxx}`
10. s1 := 'a is $a,b is $b,c is $c'
11. s2 := 'name is ${name}, age is ${age}'
12. e := `c` // char literal
13. f := true // bool literal
14. }

AsCast as造型语句

AST结构体

1. AsCast as造型语句

示例代码

1. module main

3. type Mysumtype = bool | f64 | int | string

5. fn main() {
6. x := Mysumtype(3)
7. x2 := x as int // as must be used for sumtype
8. println(x2)
9. }

SizeOf sizeof语句

AST结构体

1. SizeOf sizeof语句

示例代码

1. module main

3. struct Point {
4. x int
5. y int
6. }

8. fn main() {
9. a := sizeof(int) // basic type
10. b := sizeof(bool) // basic type
11. p := Point{
12. x: 1
13. y: 2
14. }
15. s1 := sizeof(Point) // struct type
16. s2 := sizeof(p) // variable
17. }

TypeOf typeof语句

AST结构体

1. TypeOf  typeof语句

示例代码

1. module main

3. type MySumType = f32 | int

5. fn myfn(i int) int {
6. return i
7. }

9. fn main() {
10. a := 123
11. s := 'abc'
12. aint := []int{}
13. astring := []string{}
14. println(typeof(a)) // int
15. println(typeof(s)) // string
16. println(typeof(aint)) // array_int
17. println(typeof(astring)) // array_string
18. // sumtype
19. sa := MySumType(32)
20. println(typeof(sa)) // int
21. // function type
22. println(typeof(myfn)) // fn (int) int
23. }

CastExpr 造型表达式

AST结构体

1. CastExpr 造型表达式

示例代码 ( todo: need more about string(buf,n) )

1. module main

3. fn main() {
4. x:=byte(3)
5. y:=f32(2.1)
6. }

Array 数组

ArrayInit 数组初始化语句

AST结构体

1. ArrayInit 数组初始化语句

示例代码

1. module main

3. fn main() {
4. mut arr := []string{len: 3, cap: 6, init: 'default'}
5. arr[0] = 'a'
6. arr[1] = 'b'
7. println(arr)
8. }

IndexExpr 索引表达式

AST结构体

1. IndexExpr 索引表达式

示例代码

1. module main

3. fn main() {
4. mut arr := []string{len: 3, cap: 6, init: 'default'}
5. arr[0] = 'a' //index expr
6. arr[1] = 'b'
7. println(arr)
8. mut m := map[string]string{}
9. m['name'] = 'tom' //index expr
10. m['age'] = '33'
11. }

RangeExpr 数组区间表达式

AST结构体

1. RangeExpr 数组区间表达式

示例代码

1. module main

3. fn main() {
4. n := [1, 2, 3, 4, 5]
5. a1 := n[..2] //[1, 2]
6. a2 := n[2..] //[3, 4, 5]
7. a3 := n[2..4] //[3, 4]
8. }

ArrayDecompose 数组解构

AST结构体

1. ArrayDecompose 数组解构

示例代码

1. module main

3. fn main() {
4. a := ['a', 'b', 'c']
5. println(variadic_fn_a(a...)) //ArrayDecompose
6. }

8. fn variadic_fn_a(a ...string) string {
9. return variadic_fn_b(a...) //ArrayDecompose
10. }

12. fn variadic_fn_b(a ...string) string {
13. a0 := a[0]
14. a1 := a[1]
15. a2 := a[2]
16. return '$a0$a1$a2'
17. }

Map 字典

MapInit 字典初始化

AST结构体

1. MapInit 字典初始化

示例代码

1. module main

3. fn main() {
4. mut m := map[string]string{} //map declaration
5. m['name'] = 'tom'
6. m['age'] = '33'
7. //map literal declaration and init
8. m2 := {
9. 'one':   1
10. 'two':   2
11. 'three': 3
12. }
13. }

Operator 操作符

PrefixExpr 前缀表达式

AST结构体

1. PrefixExpr 前缀表达式

示例代码

1. module main

3. fn main() {
4. x := -1 // minus
5. p := &x // get address of variable
6. x2 := *p // get value of pointer
7. b := !true // logic not
8. bit := ~0x0000 // bit not
9. }

InfixExpr 中缀表达式

AST结构体

1. InfixExpr 中缀表达式

示例代码

1. module main

3. fn main() {
4. x := 1 + 2
5. y := 1 - 2
6. a := x == y // equal
7. b := x > y // compare
8. c := 1 in [1, 2] // in operator
9. d := (x > y) && (1 < 2) // logic and
10. e := 2 == 2 || 3 == 3 // logic or
11. mut arr := [1, 2] // array append
12. arr << 3
13. }

PostfixExpr 后缀表达式

AST结构体

1. PostfixExpr 后缀表达式

示例代码

1. module main

3. fn main() {
4. mut x:=1
5. x++
6. x--
7. }

SelectorExpr 选择器表达式

AST结构体

1. SelectorExpr 选择器表达式

示例代码

1. module main

3. struct Point {
4. mut:
5. x int
6. y int
7. }

9. fn (mut p Point) move(a int, b int) {
10. p.x += a // selector for struct field assign
11. p.y += b
12. }

14. fn main() {
15. mut p := Point{
16. x: 1
17. y: 3
18. }
19. p.x // selector for access field value
20. p.move(2, 3)
21. }

ParExpr 括号表达式

AST结构体

1. ParExpr 括号表达式

示例代码

1. module main

3. fn main() {
4. x:=(1+2)
5. y:=(1<2)
6. }

ConcatExpr 连接表达式

AST结构体

1. ConcatExpr 连接表达式

示例代码

1. a, b, c := match false {
2. true { 1, 2, 3 }
3. false { 4, 5, 6 }
4. else { 7, 8, 9 }
5. }

Function 函数

FnDecl 函数声明

AST结构体

1. FnDecl 函数声明语句

3. CallExpr 函数调用表达式

5. CallArg  调用参数

7. Return 返回值语句

示例代码

1. module main

3. fn main() {
4. s := add(1, 3)
5. println(s)
6. s2 := add_generic(2, 4)
7. s3 := add_generic<int>(2, 4)
8. println(s2)
9. println(s3)
10. }

12. // function
13. fn add(x int, y int) int {
14. return x + y
15. }

17. struct Point {
18. x int
19. y int
20. }

22. // method
23. pub fn (p Point) move(a int, b int) (int, int) {
24. new_x := p.x + a
25. new_y := p.y + b
26. return new_x, new_y
27. }

29. // generic function
30. fn add_generic<T>(x T, y T) T {
31. return x + y
32. }

AnonFn 匿名函数

AST结构体

1. AnonFn 匿名函数

示例代码

1. module main

3. fn main() {
4. f1 := fn (x int, y int) int {
5. return x + y
6. }
7. f1(1,3)
8. }

DeferStmt 函数defer语句

AST结构体

1. DeferStmt  函数defer语句

示例代码

1. fn main() {
2. println('main start')
3. // defer {defer_fn1()}
4. // defer {defer_fn2()}
5. defer {
6. defer_fn1()
7. }
8. defer {
9. defer_fn2()
10. }
11. println('main end')
12. }

14. fn defer_fn1() {
15. println('from defer_fn1')
16. }

18. fn defer_fn2() {
19. println('from defer_fn2')
20. }

Struct 结构体

StructDecl 结构体声明语句

AST结构体

1. StructDecl 结构体声明语句

3. StructField 结构体字段

5. Embed 结构体组合

示例代码

1. module main

3. [attr1]
4. [attr2]
5. struct Point { //comment 1
6. mut:
7. x int [attr3]
8. y int ['attr4=123']
9. pub mut:
10. z int = 1
11. //end comment
12. }

14. fn main() {
15. }

示例代码

1. module main

3. struct Widget {
4. mut:
5. x int
6. y int
7. }

9. pub fn (mut w Widget) move(x_step int, y_step int) {
10. w.x += x_step
11. w.y += y_step
12. }

14. struct Widget2 {
15. mut:
16. z int
17. }

19. pub fn (mut w Widget2) move_z(z_step int) {
20. w.z += z_step
21. }

23. struct Button {
24. Widget //embed
25. Widget2 //embed
26. title string
27. }

29. fn main() {
30. mut button := Button{
31. title: 'Click me'
32. }
33. button.x = 3 // x comes from Widget
34. button.z = 4 // z comes from Widget2
35. println('x:$button.x,y:$button.y,z:$button.z')
36. button.move(3, 4) // move comes from Widget
37. println('x:$button.x,y:$button.y,z:$button.z')
38. button.move_z(5) // move_z comes from Widget2
39. println('x:$button.x,y:$button.y,z:$button.z')
40. }

StructInit 结构体初始化表达式

AST结构体

1. StructInit 结构体初始化

3. StructInitField 结构体初始化字段

5. StructInitEmbed 结构体初始化组合

示例代码

1. module main

3. struct User {
4. name string
5. age int
6. }

8. fn add(u User) {
9. println(u)
10. }

12. fn main(){
13. add(User{name:'jack',age:22}) //standard
14. add({name:'tom',age:23}) //short
15. add(name:'tt',age:33) // more short
16. }

结构体初始化例子

1. struct City {
2. name       string
3. population int
4. }

6. struct Country {
7. name    string
8. capital City
9. }

11. fn main() {
12. ccc := Country{
13. name: 'test'
14. capital: City{
15. name: 'city'
16. }
17. }
18. c2 := Country{
19. ...ccc  //update_expr
20. capital: City{
21. name: 'city2'
22. population: 200
23. }
24. }
25. println(c2)
26. }

Interface 接口

InterfaceDecl 接口声明语句

AST结构体

1. InterfaceDecl 接口声明语句

示例代码

1. module main

3. interface Speaker { //comment 1
4. speak() string
5. silent()
6. }

Type 类型

AliasType 类型别名声明语句

AST结构体

1. AliasTypeDecl 类型别名声明语句

示例代码

1. module main

3. struct Human {
4. name string
5. }
6. type Myint =  int /*comment 1*/ //comment 2
7. type Person = Human

FunctionType 函数类型声明语句

AST结构体

1. FnTypeDecl  函数类型声明语句

示例代码

1. module main

3. type Mid_fn = fn (int, string) int /*comment 1*/ //comment 2

Sumtype 联合类型

AST结构体

1. SumTypeDecl 联合类型声明语句

示例代码

1. module main

3. struct User {
4. name string
5. age  int
6. }

8. type MySumtype = User | int | string //comment 1

TypeNode 类型表达式

主要用于联合类型的match类型匹配,以及is类型判断

AST结构体

1. TypeNode 类型表达式

示例代码

1. module main

3. struct User {
4. name string
5. age  int
6. }

8. pub fn (m &User) str() string {
9. return 'name:$m.name,age:$m.age'
10. }

12. type MySum = User | int | string

14. pub fn (ms MySum) str() string {
15. if ms is int { //类型表达式

17. }
18. match ms {
19. int { //类型表达式
20. return ms.str()
21. }
22. string { //类型表达式
23. return ms
24. }
25. User { //类型表达式
26. return ms.str()
27. }
28. }
29. }

FlowControl 流程控制

Block 代码块语句

AST结构体

1. Block 代码块语句

示例代码

1. fn main() {
2. my_fn()
3. }

5. fn my_fn() {
6. // block
7. {
8. println('in block')
9. }
10. // unsafe block
11. unsafe {
12. }
13. }

if 条件语句

AST结构体

1. IfExpr if表达式
2. IfBranch if条件分支
3. IfGuardExpr if守护条件表达式

示例代码

1. module main

3. //带错误的函数
4. fn my_fn(i int) ?int {
5. if i == 0 {
6. return error('Not ok!') //抛出错误
7. }
8. if i == 1 {
9. return none //抛出错误
10. }
11. return i //正常返回
12. }

14. fn main() {
15. a := 10
16. b := 20
17. // if statement
18. if a < b {
19. println('$a < $b')
20. } else if a > b {
21. println('$a > $b')
22. } else {
23. println('$a == $b')
24. }

26. // if guard expr
27. if c := my_fn(2) { // if守护条件,调用函数时,正常返回,执行if分支
28. println('$c')
29. } else {
30. println('from else')
31. }
32. if c := my_fn(1) { // if守护条件,调用函数时,抛出错误,执行else分支
33. println('$c')
34. } else {
35. println('from else')
36. }

38. // if守护条件,其实等价于
39. cc := my_fn(22) or {
40. println('from or')
41. 0
42. }
43. println(cc)

45. // if expr
46. num := 777
47. s := if num % 2 == 0 { 'even' } else { 'odd' }
48. x, y, z := if true { 1, 'awesome', 13 } else { 0, 'bad', 0 }
49. // compile time if
50. $if macos {
51. } $else {
52. }
53. println('s:$s,x:$x,y:$y,z:$z')
54. }

match 分支匹配

AST结构体

1. MatchExpr 匹配表达式
2. MatchBranch 匹配分支

示例代码

1. fn main() {
2. os := 'macos'
3. // match statement
4. match os {
5. 'windows' { println('windows') }
6. 'macos', 'linux' { println('macos or linux') }
7. else { println('unknow') }
8. }
9. // match expr
10. price := match os {
11. 'windows' { 100 }
12. 'linux' { 120 }
13. 'macos' { 150 }
14. else { 0 }
15. }
16. // multi assign
17. a, b, c := match false {
18. true { 1, 2, 3 }
19. false { 4, 5, 6 }
20. else { 7, 8, 9 }
21. }
22. }

24. type MySum = bool | int | string

26. pub fn (ms MySum) str() string {
27. // match sum type
28. match ms {
29. int { return ms.str() }
30. string { return ms }
31. else { return 'unknown' }
32. }
33. }

for 循环语句

AST结构体

1. ForCStmt forC循环语句
2. ForInStmt forin循环语句
3. ForStmt for循环语句
4. BranchStmt 分支语句

示例代码

1. fn main() {
2. for i := 0; i < 10; i++ {
3. if i == 6 {
4. continue
5. }
6. if i == 10 {
7. break
8. }
9. println(i)
10. }
11. }

示例代码

1. fn main() {
2. // string
3. str := 'abcdef'
4. for s in str {
5. println(s.str())
6. }
7. // array
8. numbers := [1, 2, 3, 4, 5]
9. for num in numbers {
10. println('num:$num')
11. }
12. // range
13. mut sum := 0
14. for i in 1 .. 11 {
15. sum += i
16. }
17. // map
18. m := {
19. 'name': 'jack'
20. 'age':  '20'
21. 'desc': 'good man'
22. }
23. for key, value in m {
24. println('key:$key,value:$value')
25. }
26. }

示例代码

1. fn main() {
2. mut sum := 0
3. mut x := 0
4. for x <= 100 {
5. sum += x
6. x++
7. }
8. println(sum)
9. // label for
10. mut i := 4
11. goto L1
12. L1: for { // label for
13. i++
14. for {
15. if i < 7 {
16. continue L1
17. } else {
18. break L1
19. }
20. }
21. }
22. }

goto 跳转语句

AST结构体

1. GotoLabel 跳转标签
2. GotoStmt 跳转语句

示例代码

1. fn main() {
2. mut i := 0
3. a: // goto label
4. i++
5. if i < 3 {
6. goto a
7. }
8. println(i)
9. }

Error handle 错误控制

AST结构体

1. OrExpr or表达式
2. None none表达式

示例代码

1. fn my_fn(i int) ?int {
2. if i == 0 {
3. return error('Not ok!')
4. }
5. if i == 1 {
6. return none
7. }
8. return i
9. }

11. fn main() {
12. println('from main') // OrKind is absent
13. v1 := my_fn(0) or { // OrKind is block
14. println('from 0')
15. panic(err)
16. }
17. v2 := my_fn(1) or {
18. println('from 1')
19. panic('error msg is $err')
20. }
21. v3 := my_fn(2) or {
22. println('from 2')
23. return
24. }
25. v4 := my_fn(3) ? // OrKind is propagate
26. }

Concurrent 并发

ChanInit 通道初始化

AST结构体

1. ChanInit 通道初始化语句
2. GoStmt go并发语句

示例代码

1. module main

3. const (
4. num_iterations = 10000
5. )

7. fn do_send(ch chan int) {
8. for i in 0 .. num_iterations {
9. ch <- i
10. }
11. }

13. fn main() {
14. ch := chan int{cap: 1000} // chan init
15. go do_send(ch) // go statement
16. mut sum := i64(0)
17. for _ in 0 .. num_iterations {
18. sum += <-ch
19. println(sum)
20. }
21. }

SelectExpr 通道监听表达式

AST结构体

1. SelectExpr 通道监听表达式
2. SelectBranch 通道监听分支

示例代码

1. import time
2. import sync

4. fn main() {
5. ch1 := chan int{}
6. ch2 := chan int{}
7. go send(ch1, ch2)
8. mut x := 0
9. mut y := 0
10. for {
11. select { //
12. x = <-ch1 { // read channel
13. println('$x')
14. }
15. y = <-ch2 {
16. println('$y')
17. }
18. > 2 * time.second { // timeout
19. break
20. }
21. }
22. }
23. }

25. fn send(ch1 chan int, ch2 chan int) {
26. ch1 <- 1
27. ch2 <- 2
28. ch1 <- 3
29. ch2 <- 4
30. ch1 <- 5
31. ch2 <- 6
32. }

LockExpr 并发锁表达式

AST结构体

1. LockExpr 并发锁表达式

示例代码

1. module main

3. import time

5. struct St {
6. mut:
7. x f64
8. }

10. fn f(x int, y f64, shared s St,shared m map[string]string) {
11. time.usleep(50000)
12. lock s,m {
13. s.x = x * y
14. println(s.x)
15. unsafe {
16. m['a']='aa'
17. }
18. println(m['a'])
19. }
20. return
21. }

23. fn main() {
24. shared t := &St{}
25. shared m := &map[string]string
26. unsafe {
27. m['a']='aa'
28. }
29. r := go f(3, 4.0, shared t,shared m)
30. r.wait()
31. rlock t {
32. println(t.x)
33. }
34. }

GoExpr 并发表达式

AST结构体

1. GoExpr 并发表达式

示例代码

1. module main

3. import time

5. fn do_something() {
6. println('start do_something...')
7. time.sleep(2)
8. println('end do_something')
9. }
10. fn add(x int, y int) int {
11. println('add start...')
12. time.sleep(4) //
13. println('end add')
14. return x + y
15. }

17. fn main() {
18. g:= go do_something()
19. g2 := go add(3, 2)
20. g.wait()
21. result := g2.wait()
22. println(result)
23. }

Unsafe 不安全代码

AST结构体

1. UnsafeExpr 不安全代码表达式

示例代码

1. module main

3. fn main() {
4. a := ['a', 'b', 'c']
5. p := unsafe { &a[2] } // unsafe expr
6. println(p)
7. }

ASM 汇编

AST结构体

1. AsmStmt 汇编语句

3. AsmTemplate
4. AsmClobbered
5. AsmIO
6. AsmArg
7. AsmAddressing
8. AsmAlias
9. AsmRegister

示例代码

1. fn main() {
2. a := 100
3. b := 20
4. mut c := 0
5. asm amd64 {
6. mov eax, a
7. add eax, b
8. mov c, eax
9. ; =r (c) // output
10. ; r (a) // input
11. r (b)
12. }
13. println('a: $a') // 100
14. println('b: $b') // 20
15. println('c: $c') // 120
16. }

SQL SQL语句

AST结构体

1. SqlStmt sql语句
2. SqlExpr sql表达式

示例代码

1. module main

3. import sqlite

5. struct Module {
6. id           int
7. name         string
8. nr_downloads int
9. }

11. struct User {
12. id             int
13. age            int
14. name           string
15. is_customer    bool
16. skipped_string string [skip]
17. }

19. struct Foo {
20. age int
21. }

23. fn main() {
24. db := sqlite.connect(':memory:') or { panic(err) }
25. db.exec('drop table if exists User')
26. db.exec("create table User (id integer primary key, age int default 0, name text default '', is_customer int default 0);")
27. name := 'Peter'
28. db.exec("insert into User (name, age) values ('Sam', 29)")
29. db.exec("insert into User (name, age) values ('Peter', 31)")
30. db.exec("insert into User (name, age, is_customer) values ('Kate', 30, 1)")
31. nr_all_users := sql db {
32. select count from User
33. }
34. println('nr_all_users=$nr_all_users')
35. //
36. nr_users1 := sql db {
37. select count from User where id == 1
38. }
39. println('nr_users1=$nr_users1')
40. //
41. nr_peters := sql db {
42. select count from User where id == 2 && name == 'Peter'
43. }
44. //
45. new_user := User{
46. name: 'New user'
47. age: 30
48. }
49. sql db {
50. insert new_user into User
51. }
52. sql db {
53. update User set age = 31 where name == 'Kate'
54. }
55. sql db {
56. delete from User where age == 34
57. }
58. }

TestAssert 测试断言

AssertStmt 测试断言语句

AST结构体

1. AssertStmt 测试断言语句

示例代码

1. fn test_abc() {
2. x := 1
3. assert x == 1
4. }

DumpExpr 转储函数表达式

AST结构体

1. DumpExpr 转储函数表达式

示例代码

1. fn factorial(n u32) u32 {
2. if dump(n <= 1) {
3. return dump(1)
4. }
5. return dump(n * factorial(n - 1))
6. }

8. fn main() {
9. println(factorial(5))
10. }

Compile time 编译时

CompFor 编译时循环语句

AST结构体

1. CompFor 编译时循环语句
2. ComptimeCall 编译时调用表达式
3. ComptimeSelector 编译时选择器表达式

示例代码

1. struct App {
2. a string
3. b string
4. mut:
5. c int
6. d f32
7. pub:
8. e f32
9. f u64
10. pub mut:
11. g string
12. h byte
13. }

15. fn (mut app App) m1() {
16. }

18. fn (mut app App) m2() {
19. }

21. fn (mut app App) m3() int {
22. return 0
23. }

25. fn main() {
26. $for field in App.fields {
27. println('field: $field.name')
28. }
29. $for method in App.methods {
30. println('method: $method.name')
31. }
32. }

AtExpr at全局常量表达式

AST结构体

1. AtExpr at全局常量量表达式

示例代码

1. module main

3. fn main() {
4. println('module: ${@MOD}')            //当前模块
5. println('fn: ${@FN}')                //当前函数
6. println('sturct: ${@STRUCT}')        //当前结构体
7. println('method: ${@METHOD}')        //当前方法
8. println('vexe: ${@VEXE}')            //当前V编译器命令行可执行文件
9. println('vexeroot: ${@VEXEROOT}')    //当前V编译器命令行所在的目录
10. println('file: ${@FILE}')            //当前源代码文件名
11. println('line: ${@LINE}')            //当前代码所在的行
12. println('column: ${@COLUMN}')        //当前代码在当前行中的列数
13. println('vhash: ${@VHASH}')            //当前V命令行编译时的hash
14. println('vmod_file: ${@VMOD_FILE}')    //当前文件所处项目的v.mod文件内容
15. println('vmodroot: ${@VMODROOT}')    //当前文件所处项目的v.mod文件所在的目录
16. }

C Integration C代码互操作

GlobalDecl 全局变量声明

AST结构体

1. GlobalDecl 全局变量声明
2. GlobalField 全局字段声明

示例代码

1. module main

3. // single
4. __global  g1 int

6. // group
7. __global (
8. g2 byte
9. g3 byte
10. )

12. fn main() {
13. g1 = 1
14. g2 = 2
15. g3 = 3
16. println(g1)
17. println(g2)
18. println(g3)
19. }

HashStmt C宏指令语句

AST结构体

1. HashStmt C宏指令语句

示例代码

1. module main

3. #include <stdio.h>

5. #flag -lmysqlclient
6. #flag linux -I/usr/include/mysql
7. #include <mysql.h>

9. fn main() {

11. }

Likely likely表达式

AST结构体

1. Likely

示例代码

1. module main

3. fn main() {
4. x := 1
5. if _likely_(x == 1) {
6. println('a')
7. } else {
8. println('b')
9. }
10. if _unlikely_(x == 1) {
11. println('a')
12. } else {
13. println('b')
14. }
15. }

OffsetOf 结构体字段内存偏移量

AST结构体

1. OffsetOf 结构体字段内存偏移量

示例代码

1. module main

3. struct User {
4. name [50]byte
5. age int
6. desc string
7. }

9. fn main() {
10. offset_name:=__offsetof(User,name)
11. offset_age:=__offsetof(User,age)
12. offset_desc:=__offsetof(User,desc)
13. println(offset_name)
14. println(offset_age)
15. println(offset_desc)
16. }

Comment 注释

AST结构体

1. Comment 注释

示例代码

1. module main
2. /*
3. multi line comment
4. multi line comment
5. */
6. // signle line comment
7. fn main() {
8. x := 1 // behind statement comment
9. }

Other 其他

Empty 空语句/表达式

只在编译内部使用,用来判断空语句和空表达式.

AST结构体

1. EmptyStmt 空语句
2. EmptyExpr 空表达式

NodeError 错误节点

只在编译内部使用,当解析器报错时,返回NodeError节点.

NodeError既是语句,也是表达式.