# macros (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/macros/

vanilla-engine procedural macros. (in place of the runtime reflection of the original vanilla.js)
- The original is JavaScript, so at runtime it walks an object's prototype to find get, is, set functions.
  (collectReflectedProperties in ui/uidocument.js, getComponentProperties in misc/devtools.js)
  Rust has no runtime reflection, so like Unreal's UHT (UPROPERTY) and Qt's moc, it generates code at compile time to do the same job.
- Putting `#[reflect]` on a component's impl block gathers the block's `pub fn get_*(&self) -> T`, `pub fn is_*(&self) -> T` and
  their paired `pub fn set_*(&mut self, value)` to build a vanilla::core::reflection::Reflect implementation.
- `#[reflect]` on an impl Component block collects the getters redefined in that block (like isTickNeeded overridden by an original subclass) for the inspector.
  When that block has no fn draw, it generates Component::is_draw_overridden returning false. (a component that draws nothing, original draw === Component.prototype.draw)
  Both blocks must have it. Reflect is a supertrait of Component, so leaving out either one is a compile error. (Like the original, every component is reflected)
  A type without getters takes it on an empty block, `#[reflect] impl Type {}`.
- Follows the original rules as is:
  - Getters are argumentless `get*`, `is*` functions. (original `getterFunction.length === 0`) Saved properties are only getters with a `set*` of the same key. (original `"set" + baseName`)
    &mut self getters are getters too. (the original functions make no &self, &mut self distinction) Reflection calls them through the branches that take &mut (get_reflected_value_mut, collect_reflected_getters_mut).
    Rust _mut accessors (like get_uiview_mut) and functions returning &mut are not original getters, so they are excluded.
  - Setters are `set*` taking one value. Setters taking the tree and a value (like set_snap_current_index(tree, slot)) are also recognized,
    and the side holding the tree (UIDocument reading) calls them with set_reflected_value_in_tree as in the original.
  - Getters taking only the tree (like get_target_button(&self, tree)) are original getters too. The original holds neighbor components directly, but the Rust version takes them out of the tree.
    The side holding the tree (the DevTools inspector) calls them with collect_reflected_getters_in_tree. They are not saved properties.
  - The key is the original name with the prefix (get, is) removed. Rust snake_case is turned back into the original camelCase. (get_line_width → getLineWidth → LineWidth)
  - The order is definition order, and on the same key the first one wins.
- Getters of types that cannot be turned into values do not cause compile errors either. Through autoref specialization (autoref specialization) only convertible types are read as values,
  and the rest are skipped in saving as in the original and shown in the inspector as `[kind name]`.
- Put on functions: `#[reflect(skip)]` excludes from reflection. `#[reflect(transient)]` shows in the inspector but excludes from the property list.
  `#[reflect(unsaved)]` keeps it in the property list but excludes it from reflection saving and reading. (properties saveByReflection does not write because the value is an object in the original, ShadowText's FontFace)
  `#[reflect(name = "UIScale")]` sets the original key name. (names that cannot be recovered from snake_case, like acronym words in original names, and getters whose names differ from the original)
  `#[reflect(after = "getFittedFontSize")]` places an impl Component block getter after that original getter in the inspector list. (the order in the original class body, at the front if absent)
- Put on blocks: `#[reflect(base = field)]` chains the reflection of a held value afterwards, like an original superclass.
  `#[reflect(crate = path)]` engine path. (default ::vanilla, inside the engine crate the same path works through extern crate self as vanilla in lib.rs)

Example: Putting it on an impl block and an impl Component block (ignore: doctests of the procedural macro crate cannot depend on the engine. The engine's core::reflection module example runs the same example)

```rust
use vanilla::core::reflection::{collect_reflected_properties, read_reflected_property, write_reflected_property};
use vanilla::{reflect, Component, ComponentBase, ReflectValue};

struct Spin {
	component_base: ComponentBase,
	speed: f32,
}

#[reflect]
impl Spin {
	pub fn get_speed(&self) -> f32 {
		self.speed
	}

	pub fn set_speed(&mut self, speed: f32) {
		self.speed = speed;
	}
}

#[reflect]
impl Component for Spin {
	fn get_component_base(&self) -> &ComponentBase {
		&self.component_base
	}

	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
		&mut self.component_base
	}

	fn get_component_type(&self) -> &'static str {
		"Spin"
	}
}

let mut spin = Spin {
	component_base: ComponentBase::new(),
	speed: 1.5,
};
let property_names: Vec<&str> = collect_reflected_properties(&spin).iter().map(|property| property.name).collect();
assert_eq!(property_names, ["Speed", "GizmoVisible", "Enable", "ComponentType"]);
assert_eq!(read_reflected_property(&spin, "Speed"), Some(ReflectValue::Number(1.5)));
assert!(write_reflected_property(&mut spin, "Speed", &ReflectValue::Number(3.0)));
assert_eq!(spin.get_speed(), 3.0);
```

## Functions and constants

- `#[reflect]` (method, since 0.4.0): Reflection macro. (put on an impl block. A trait impl is treated as an impl Component block)
  - Games use vanilla::reflect re-exported by the engine. (`#[reflect]` after `use vanilla::reflect;`, or `#[vanilla::reflect]`)
  - Put it on both the component's impl block and the impl Component block. If only one has it, the compile error tells where to put it.
  - Block options are `base = field`, `crate = path`, and function options are `skip`, `transient`, `unsaved`, `name = "..."`, `after = "..."`. (base is not used on impl Component blocks)

  Example: Function options and held values (ignore: doctests of the procedural macro crate cannot depend on the engine. The engine's core::reflection module example runs the same example)

  ```rust
  use vanilla::core::reflection::{collect_reflected_getters, collect_reflected_properties};
  use vanilla::{reflect, Component, ComponentBase};
  
  struct Meter {
  	component_base: ComponentBase,
  	value: f32,
  }
  
  #[reflect]
  impl Meter {
  	pub fn get_value(&self) -> f32 {
  		self.value
  	}
  
  	pub fn set_value(&mut self, value: f32) {
  		self.value = value;
  	}
  }
  
  #[reflect]
  impl Component for Meter {
  	fn get_component_base(&self) -> &ComponentBase {
  		&self.component_base
  	}
  
  	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
  		&mut self.component_base
  	}
  
  	fn get_component_type(&self) -> &'static str {
  		"Meter"
  	}
  }
  
  struct LabeledMeter {
  	component_base: ComponentBase,
  	meter: Meter,
  	label: String,
  }
  
  #[reflect(base = meter)]
  impl LabeledMeter {
  	#[reflect(name = "Caption")]
  	pub fn get_label(&self) -> &str {
  		&self.label
  	}
  
  	#[reflect(name = "Caption")]
  	pub fn set_label(&mut self, label: &str) {
  		self.label = String::from(label);
  	}
  
  	#[reflect(transient)]
  	pub fn get_label_length(&self) -> usize {
  		self.label.len()
  	}
  
  	#[reflect(skip)]
  	pub fn get_meter(&self) -> &Meter {
  		&self.meter
  	}
  }
  
  #[reflect]
  impl Component for LabeledMeter {
  	fn get_component_base(&self) -> &ComponentBase {
  		&self.component_base
  	}
  
  	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
  		&mut self.component_base
  	}
  
  	fn get_component_type(&self) -> &'static str {
  		"LabeledMeter"
  	}
  }
  
  let labeled_meter = LabeledMeter {
  	component_base: ComponentBase::new(),
  	meter: Meter {
  		component_base: ComponentBase::new(),
  		value: 0.5,
  	},
  	label: String::from("hp"),
  };
  let property_names: Vec<&str> = collect_reflected_properties(&labeled_meter).iter().map(|property| property.name).collect();
  assert_eq!(property_names, ["Caption", "Value", "GizmoVisible", "Enable", "ComponentType"]);
  let getter_names: Vec<&str> = collect_reflected_getters(&labeled_meter).expect("reflection").iter().map(|getter| getter.name).collect();
  assert_eq!(getter_names, ["getCaption", "getLabelLength", "getValue"]);
  ```

