Skip to content

Commit

Permalink
doc: add initial documentation about the supported comptime metadata (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Jan 3, 2024
1 parent 0486c33 commit 7ba8161
Showing 1 changed file with 111 additions and 0 deletions.
111 changes: 111 additions & 0 deletions doc/docs.md
Expand Up @@ -5591,6 +5591,11 @@ print($embed_file(@FILE).to_string())
Having built-in JSON support is nice, but V also allows you to create efficient
serializers for any data format. V has compile time `if` and `for` constructs:
#### <h4 id="comptime-fields">.fields</h4>
You can iterate over struct fields using `.fields`, it also works with generic types
(e.g. `T.fields`) and generic arguments (e.g. `param.fields` where `fn gen[T](param T) {`).
```v
struct User {
name string
Expand All @@ -5609,6 +5614,112 @@ fn main() {
// name is of type string
```
#### <h4 id="comptime-values">.values</h4>
You can read [Enum](#enums) values and their attributes.
```V
enum Color {
red @[RED] // first attribute
blue @[BLUE] // second attribute
}
fn main() {
$for e in Color.values {
println(e.name)
println(e.attrs)
}
}
// Output:
// red
// ['RED']
// blue
// ['BLUE']
```
#### <h4 id="comptime-attrs">.attributes</h4>
You can read [Struct](#structs) attributes.
```V
@[COLOR]
struct Foo {
a int
}
fn main() {
$for e in Foo.attributes {
println(e)
}
}
// Output:
// StructAttribute{
// name: 'COLOR'
// has_arg: false
// arg: ''
// kind: plain
// }
```
#### <h4 id="comptime-variants">.variants</h4>
You can read variant types from [Sum type](#sum-types).
```V
type MySum = int | string
fn main() {
$for v in MySum.variants {
$if v.typ is int {
println('has int type')
} $else $if v.typ is string {
println('has string type')
}
}
}
// Output:
// has int type
// has string type
```
#### <h4 id="comptime-methods">.methods</h4>
You can retrieve information about struct methods.
```V
struct Foo {
}
fn (f Foo) test() int {
return 123
}
fn (f Foo) test2() string {
return 'foo'
}
fn main() {
foo := Foo{}
$for m in Foo.methods {
$if m.return_type is int {
print('${m.name} returns int: ')
println(foo.$method())
} $else $if m.return_type is string {
print('${m.name} returns string: ')
println(foo.$method())
}
}
}
// Output:
// test returns int: 123
// test2 returns string: foo
```
See [`examples/compiletime/reflection.v`](/examples/compiletime/reflection.v)
for a more complete example.
Expand Down

0 comments on commit 7ba8161

Please sign in to comment.