Files
sakurac/tests/programs/reflection_reaches_declarations_by_name_1.sakura
T
2026-12-06 13:52:57 -06:00

60 lines
2.5 KiB
Plaintext

import std::io;
@usage{ on = target::functions | target::constants }
struct check : attribute { val name: span<u8> = ""; val skip: bool = false; }
@usage{ many = true }
struct tag : attribute { val text: span<u8>; val weight: u8 = 1; }
struct other : attribute {}
struct nil {}
union shape { var none: nil; var circle: f64; var square: i64; }
struct point { var x: i64; var y: i64; }
def point::sum(&this): i64 { return this.x + this.y; }
val point::twice: i64 { get => this.sum() * 2; }
type spot = point;
enum color: u8 { red, green = 4, blue, first = color::red }
def doubled<T>(x: T): T where T: numeric { return x + x; }
@check def adds(): i64 { return 1 + 1; }
@check{ name = "second" } def muls(): i64 { return 2 * 3; }
@check{ skip = true } def skipped(): i64 { return 0; }
@check const doubles := doubled::<i64>;
@tag{ text = "a" } @other @tag{ text = "b", weight = 3 }
var counter: i64 = 0;
def which(s: shape): span<u8> {
for const f in members_of(decl_of::<shape>()) {
if s is (f) { return f.name; }
}
return "?";
}
def show<T>(x: &T): void {
print(name_of::<T>());
for const f in members_of(decl_of::<T>()) {
if const f.kind == target::fields { print($" {f.name}={x.(f)}"); }
if const f.kind == target::methods { print($" {f.name}()={x.(f)()}"); }
if const f.kind == target::properties { print($" {f.name}={x.(f)}"); }
}
println("");
}
def main(): void {
for const d in declarations() {
if const attached::<check>(d).length == 0 { continue; }
val found := attached::<check>(d)[0];
if found.skip { continue; }
if const d.kind == target::functions { print($"{d.name}:{found.name}={value_of(d)()} "); }
if const d.kind == target::constants { print($"{d.name}={value_of(d)(21)} "); }
}
println("");
show(&point{ x = 3, y = 4 });
for const m in members_of(decl_of::<color>()) { print($"{m.name}={value_of(m) as u8} "); }
println($"{which(shape{ circle = 1.5 })} {which(shape{ square = 2 })} {which(shape{})}");
for const d in declarations() {
if const attached::<tag>(d).length == 0 { continue; }
val tags := attached::<tag>(d);
for i in 0..tags.length { print($"{tags[i].text}{tags[i].weight} "); }
value_of(d) = 7;
value_of(d) += 1;
println($"{attributes_of(d).length} {d.kind} {d.path} {counter}");
}
for const m in members_of(decl_of::<spot>()) { print($"{owner_of(m).name}.{m.name} "); }
val here := decl_of::<point>();
println($"{here.name} {here.at.line} {here.exported} {decl_of::<shape>().kind}");
}