V语言抽象语法树(AST)

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

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

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

    语法树结构体总览

    ast.File语法树文件

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

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

    AST结构体

    示例代码

    1. module main
    2. import os
    3. import time
    4. fn main() {
    5. }

    生成的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
    2. import os // comment for mod
    3. //comment for time
    4. import time as t
    5. import math { min, max }
    6. fn main() {
    7. }

    Const 常量

    AST结构体

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

    示例代码

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

    Enum 枚举

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

    示例代码

    1. module main
    2. [attr1]
    3. ['attr2:123']
    4. enum Color { // enum comment 1
    5. // black comment 1
    6. // black comment 2
    7. black = 2 // black comment 3
    8. // white comment 1
    9. // white comment 2
    10. white // white comment 3
    11. blue
    12. green // green comment
    13. // end comment 1
    14. // end comment 2
    15. }
    16. [flag]
    17. enum BitEnum {
    18. e1
    19. e2
    20. e3
    21. }
    22. [_allow_multiple_values]
    23. enum MultipleEnum {
    24. v1 = 1
    25. }
    26. fn main() {
    27. mut color := Color.black
    28. color = .blue
    29. }

    Variable 变量

    AST结构体

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

    示例代码

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

    Identifier 标识符

    AST结构体

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

    示例代码

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

    Literal 字面量

    AST结构体

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

    示例代码

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

    AsCast as造型语句

    AST结构体

    1. AsCast as造型语句

    示例代码

    1. module main
    2. type Mysumtype = bool | f64 | int | string
    3. fn main() {
    4. x := Mysumtype(3)
    5. x2 := x as int // as must be used for sumtype
    6. println(x2)
    7. }

    SizeOf sizeof语句

    AST结构体

    1. SizeOf sizeof语句

    示例代码

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

    TypeOf typeof语句

    AST结构体

    1. TypeOf typeof语句

    示例代码

    1. module main
    2. type MySumType = f32 | int
    3. fn myfn(i int) int {
    4. return i
    5. }
    6. fn main() {
    7. a := 123
    8. s := 'abc'
    9. aint := []int{}
    10. astring := []string{}
    11. println(typeof(a)) // int
    12. println(typeof(s)) // string
    13. println(typeof(aint)) // array_int
    14. println(typeof(astring)) // array_string
    15. // sumtype
    16. sa := MySumType(32)
    17. println(typeof(sa)) // int
    18. // function type
    19. println(typeof(myfn)) // fn (int) int
    20. }

    CastExpr 造型表达式

    AST结构体

    1. CastExpr 造型表达式

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

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

    Array 数组

    ArrayInit 数组初始化语句

    AST结构体

    1. ArrayInit 数组初始化语句

    示例代码

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

    IndexExpr 索引表达式

    AST结构体

    1. IndexExpr 索引表达式

    示例代码

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

    RangeExpr 数组区间表达式

    AST结构体

    1. RangeExpr 数组区间表达式

    示例代码

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

    ArrayDecompose 数组解构

    AST结构体

    1. ArrayDecompose 数组解构

    示例代码

    1. module main
    2. fn main() {
    3. a := ['a', 'b', 'c']
    4. println(variadic_fn_a(a...)) //ArrayDecompose
    5. }
    6. fn variadic_fn_a(a ...string) string {
    7. return variadic_fn_b(a...) //ArrayDecompose
    8. }
    9. fn variadic_fn_b(a ...string) string {
    10. a0 := a[0]
    11. a1 := a[1]
    12. a2 := a[2]
    13. return '$a0$a1$a2'
    14. }

    MapInit 字典初始化

    AST结构体

    1. MapInit 字典初始化

    示例代码

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

    Operator 操作符

    PrefixExpr 前缀表达式

    AST结构体

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

    InfixExpr 中缀表达式

    AST结构体

    1. InfixExpr 中缀表达式

    示例代码

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

    PostfixExpr 后缀表达式

    AST结构体

    示例代码

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

    AST结构体

    1. SelectorExpr 选择器表达式

    示例代码

    1. module main
    2. struct Point {
    3. mut:
    4. x int
    5. y int
    6. }
    7. fn (mut p Point) move(a int, b int) {
    8. p.x += a // selector for struct field assign
    9. p.y += b
    10. }
    11. fn main() {
    12. mut p := Point{
    13. x: 1
    14. y: 3
    15. }
    16. p.x // selector for access field value
    17. p.move(2, 3)
    18. }

    ParExpr 括号表达式

    AST结构体

    1. ParExpr 括号表达式

    示例代码

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

    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 函数声明语句
    2. CallExpr 函数调用表达式
    3. CallArg 调用参数
    4. Return 返回值语句

    示例代码

    1. module main
    2. fn main() {
    3. s := add(1, 3)
    4. println(s)
    5. s2 := add_generic(2, 4)
    6. s3 := add_generic<int>(2, 4)
    7. println(s2)
    8. println(s3)
    9. }
    10. // function
    11. fn add(x int, y int) int {
    12. return x + y
    13. }
    14. struct Point {
    15. x int
    16. y int
    17. }
    18. // method
    19. pub fn (p Point) move(a int, b int) (int, int) {
    20. new_x := p.x + a
    21. new_y := p.y + b
    22. return new_x, new_y
    23. }
    24. // generic function
    25. fn add_generic<T>(x T, y T) T {
    26. return x + y
    27. }

    AnonFn 匿名函数

    AST结构体

    1. AnonFn 匿名函数

    示例代码

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

    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. }
    13. fn defer_fn1() {
    14. println('from defer_fn1')
    15. }
    16. fn defer_fn2() {
    17. println('from defer_fn2')
    18. }

    Struct 结构体

    StructDecl 结构体声明语句

    AST结构体

    1. StructDecl 结构体声明语句
    2. StructField 结构体字段
    3. Embed 结构体组合

    示例代码

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

    示例代码

    1. module main
    2. struct Widget {
    3. mut:
    4. x int
    5. y int
    6. }
    7. pub fn (mut w Widget) move(x_step int, y_step int) {
    8. w.x += x_step
    9. w.y += y_step
    10. }
    11. struct Widget2 {
    12. mut:
    13. z int
    14. }
    15. pub fn (mut w Widget2) move_z(z_step int) {
    16. w.z += z_step
    17. }
    18. struct Button {
    19. Widget //embed
    20. Widget2 //embed
    21. title string
    22. }
    23. fn main() {
    24. mut button := Button{
    25. title: 'Click me'
    26. }
    27. button.x = 3 // x comes from Widget
    28. button.z = 4 // z comes from Widget2
    29. println('x:$button.x,y:$button.y,z:$button.z')
    30. button.move(3, 4) // move comes from Widget
    31. println('x:$button.x,y:$button.y,z:$button.z')
    32. button.move_z(5) // move_z comes from Widget2
    33. println('x:$button.x,y:$button.y,z:$button.z')
    34. }

    StructInit 结构体初始化表达式

    AST结构体

    1. StructInit 结构体初始化
    2. StructInitField 结构体初始化字段
    3. StructInitEmbed 结构体初始化组合

    示例代码

    1. module main
    2. struct User {
    3. name string
    4. age int
    5. }
    6. fn add(u User) {
    7. println(u)
    8. }
    9. fn main(){
    10. add(User{name:'jack',age:22}) //standard
    11. add({name:'tom',age:23}) //short
    12. add(name:'tt',age:33) // more short
    13. }

    结构体初始化例子

    1. struct City {
    2. name string
    3. population int
    4. }
    5. struct Country {
    6. name string
    7. capital City
    8. }
    9. fn main() {
    10. ccc := Country{
    11. name: 'test'
    12. capital: City{
    13. name: 'city'
    14. }
    15. }
    16. c2 := Country{
    17. ...ccc //update_expr
    18. capital: City{
    19. name: 'city2'
    20. population: 200
    21. }
    22. }
    23. println(c2)
    24. }

    Interface 接口

    InterfaceDecl 接口声明语句

    AST结构体

    1. InterfaceDecl 接口声明语句

    示例代码

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

    Type 类型

    AliasType 类型别名声明语句

    AST结构体

    1. AliasTypeDecl 类型别名声明语句

    示例代码

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

    FunctionType 函数类型声明语句

    AST结构体

    1. FnTypeDecl 函数类型声明语句

    示例代码

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

    Sumtype 联合类型

    AST结构体

    1. SumTypeDecl 联合类型声明语句

    示例代码

    1. module main
    2. struct User {
    3. name string
    4. age int
    5. }
    6. type MySumtype = User | int | string //comment 1

    TypeNode 类型表达式

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

    AST结构体

    1. TypeNode 类型表达式

    示例代码

    1. module main
    2. struct User {
    3. name string
    4. age int
    5. }
    6. pub fn (m &User) str() string {
    7. return 'name:$m.name,age:$m.age'
    8. }
    9. type MySum = User | int | string
    10. pub fn (ms MySum) str() string {
    11. if ms is int { //类型表达式
    12. }
    13. match ms {
    14. int { //类型表达式
    15. return ms.str()
    16. }
    17. string { //类型表达式
    18. return ms
    19. }
    20. User { //类型表达式
    21. return ms.str()
    22. }
    23. }
    24. }

    FlowControl 流程控制

    Block 代码块语句

    AST结构体

    1. Block 代码块语句

    示例代码

    1. fn main() {
    2. my_fn()
    3. }
    4. fn my_fn() {
    5. // block
    6. {
    7. println('in block')
    8. }
    9. // unsafe block
    10. unsafe {
    11. }
    12. }

    if 条件语句

    AST结构体

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

    示例代码

    1. module main
    2. //带错误的函数
    3. fn my_fn(i int) ?int {
    4. if i == 0 {
    5. return error('Not ok!') //抛出错误
    6. }
    7. if i == 1 {
    8. return none //抛出错误
    9. }
    10. return i //正常返回
    11. }
    12. fn main() {
    13. a := 10
    14. b := 20
    15. // if statement
    16. if a < b {
    17. println('$a < $b')
    18. } else if a > b {
    19. println('$a > $b')
    20. } else {
    21. println('$a == $b')
    22. }
    23. // if guard expr
    24. if c := my_fn(2) { // if守护条件,调用函数时,正常返回,执行if分支
    25. println('$c')
    26. } else {
    27. println('from else')
    28. }
    29. if c := my_fn(1) { // if守护条件,调用函数时,抛出错误,执行else分支
    30. println('$c')
    31. } else {
    32. println('from else')
    33. }
    34. // if守护条件,其实等价于
    35. cc := my_fn(22) or {
    36. println('from or')
    37. 0
    38. }
    39. println(cc)
    40. // if expr
    41. num := 777
    42. s := if num % 2 == 0 { 'even' } else { 'odd' }
    43. x, y, z := if true { 1, 'awesome', 13 } else { 0, 'bad', 0 }
    44. // compile time if
    45. $if macos {
    46. } $else {
    47. }
    48. println('s:$s,x:$x,y:$y,z:$z')
    49. }

    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. }
    23. type MySum = bool | int | string
    24. pub fn (ms MySum) str() string {
    25. // match sum type
    26. int { return ms.str() }
    27. string { return ms }
    28. else { return 'unknown' }
    29. }
    30. }

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

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

    ChanInit 通道初始化

    AST结构体

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

    示例代码

    1. module main
    2. const (
    3. num_iterations = 10000
    4. )
    5. fn do_send(ch chan int) {
    6. for i in 0 .. num_iterations {
    7. ch <- i
    8. }
    9. }
    10. fn main() {
    11. ch := chan int{cap: 1000} // chan init
    12. go do_send(ch) // go statement
    13. mut sum := i64(0)
    14. for _ in 0 .. num_iterations {
    15. sum += <-ch
    16. println(sum)
    17. }
    18. }

    SelectExpr 通道监听表达式

    AST结构体

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

    示例代码

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

    LockExpr 并发锁表达式

    AST结构体

    1. LockExpr 并发锁表达式

    示例代码

    1. module main
    2. import time
    3. struct St {
    4. mut:
    5. x f64
    6. }
    7. fn f(x int, y f64, shared s St,shared m map[string]string) {
    8. time.usleep(50000)
    9. lock s,m {
    10. s.x = x * y
    11. println(s.x)
    12. unsafe {
    13. m['a']='aa'
    14. }
    15. println(m['a'])
    16. }
    17. return
    18. }
    19. fn main() {
    20. shared t := &St{}
    21. shared m := &map[string]string
    22. unsafe {
    23. m['a']='aa'
    24. }
    25. r := go f(3, 4.0, shared t,shared m)
    26. r.wait()
    27. rlock t {
    28. println(t.x)
    29. }
    30. }

    GoExpr 并发表达式

    AST结构体

    1. GoExpr 并发表达式

    示例代码

    1. module main
    2. import time
    3. fn do_something() {
    4. println('start do_something...')
    5. time.sleep(2)
    6. println('end do_something')
    7. }
    8. fn add(x int, y int) int {
    9. println('add start...')
    10. time.sleep(4) //
    11. println('end add')
    12. return x + y
    13. }
    14. fn main() {
    15. g:= go do_something()
    16. g2 := go add(3, 2)
    17. g.wait()
    18. result := g2.wait()
    19. println(result)
    20. }

    Unsafe 不安全代码

    AST结构体

    1. UnsafeExpr 不安全代码表达式

    示例代码

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

    ASM 汇编

    AST结构体

    1. AsmStmt 汇编语句
    2. AsmTemplate
    3. AsmClobbered
    4. AsmIO
    5. AsmArg
    6. AsmAddressing
    7. AsmAlias
    8. 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
    2. import sqlite
    3. struct Module {
    4. id int
    5. name string
    6. nr_downloads int
    7. }
    8. struct User {
    9. id int
    10. age int
    11. name string
    12. is_customer bool
    13. skipped_string string [skip]
    14. }
    15. struct Foo {
    16. age int
    17. }
    18. fn main() {
    19. db := sqlite.connect(':memory:') or { panic(err) }
    20. db.exec('drop table if exists User')
    21. db.exec("create table User (id integer primary key, age int default 0, name text default '', is_customer int default 0);")
    22. name := 'Peter'
    23. db.exec("insert into User (name, age) values ('Sam', 29)")
    24. db.exec("insert into User (name, age) values ('Peter', 31)")
    25. db.exec("insert into User (name, age, is_customer) values ('Kate', 30, 1)")
    26. nr_all_users := sql db {
    27. select count from User
    28. }
    29. println('nr_all_users=$nr_all_users')
    30. //
    31. nr_users1 := sql db {
    32. select count from User where id == 1
    33. }
    34. println('nr_users1=$nr_users1')
    35. //
    36. nr_peters := sql db {
    37. select count from User where id == 2 && name == 'Peter'
    38. }
    39. //
    40. new_user := User{
    41. name: 'New user'
    42. age: 30
    43. }
    44. sql db {
    45. insert new_user into User
    46. }
    47. sql db {
    48. update User set age = 31 where name == 'Kate'
    49. }
    50. sql db {
    51. delete from User where age == 34
    52. }
    53. }

    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. }
    7. fn main() {
    8. println(factorial(5))
    9. }

    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. }
    14. fn (mut app App) m1() {
    15. }
    16. fn (mut app App) m2() {
    17. }
    18. fn (mut app App) m3() int {
    19. return 0
    20. }
    21. fn main() {
    22. $for field in App.fields {
    23. println('field: $field.name')
    24. }
    25. $for method in App.methods {
    26. println('method: $method.name')
    27. }
    28. }

    AtExpr at全局常量表达式

    AST结构体

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

    示例代码

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

    C Integration C代码互操作

    GlobalDecl 全局变量声明

    AST结构体

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

    示例代码

    1. module main
    2. // single
    3. __global g1 int
    4. // group
    5. __global (
    6. g2 byte
    7. g3 byte
    8. )
    9. fn main() {
    10. g1 = 1
    11. g2 = 2
    12. g3 = 3
    13. println(g1)
    14. println(g2)
    15. println(g3)
    16. }

    HashStmt C宏指令语句

    AST结构体

    1. HashStmt C宏指令语句

    示例代码

    1. module main
    2. #include <stdio.h>
    3. #flag -lmysqlclient
    4. #flag linux -I/usr/include/mysql
    5. #include <mysql.h>
    6. fn main() {
    7. }

    Likely likely表达式

    AST结构体

    1. Likely

    示例代码

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

    OffsetOf 结构体字段内存偏移量

    AST结构体

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

    示例代码

    1. module main
    2. struct User {
    3. name [50]byte
    4. age int
    5. desc string
    6. }
    7. fn main() {
    8. offset_name:=__offsetof(User,name)
    9. offset_age:=__offsetof(User,age)
    10. offset_desc:=__offsetof(User,desc)
    11. println(offset_name)
    12. println(offset_age)
    13. println(offset_desc)
    14. }

    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. }

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

    AST结构体

    NodeError 错误节点

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