Skip to content

Commit

Permalink
Use macro for ops traits reference implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-blackbird committed Nov 10, 2024
1 parent bc0d551 commit 7da958d
Show file tree
Hide file tree
Showing 15 changed files with 202 additions and 533 deletions.
24 changes: 23 additions & 1 deletion codegen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use anyhow::{bail, Context};
use clap::{arg, command};
use rustfmt_wrapper::rustfmt;
use std::path::Path;
use tera::{from_value, to_value, Value};

use outputs::build_output_pairs;

Expand Down Expand Up @@ -60,7 +61,28 @@ fn main() -> anyhow::Result<()> {
} else {
None
};
let tera = tera::Tera::new("templates/**/*.rs.tera").context("tera parsing error(s)")?;
let mut tera = tera::Tera::new("templates/**/*.rs.tera").context("tera parsing error(s)")?;
tera.register_filter(
"snake_case",
|value: &Value, _: &_| -> tera::Result<Value> {
let input = from_value::<String>(value.clone())?;
let mut iter = input.chars();

let mut string = String::new();

if let Some(first) = iter.next() {
string.push(first.to_ascii_lowercase());

for char in iter {
if char.is_uppercase() {
string.push('_');
}
string.push(char.to_ascii_lowercase());
}
}
tera::Result::Ok(to_value(string)?)
},
);

let repo = git2::Repository::open(GLAM_ROOT).context("failed to open git repo")?;
let workdir = repo.workdir().unwrap();
Expand Down
33 changes: 33 additions & 0 deletions codegen/templates/macros.rs.tera
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,36 @@
}
}
{% endmacro impl_mat4_minor %}


{% macro impl_op_ref_inner(op, self_t, rhs_t, output_t, self, self_ref, rhs_ref) %}
{% set method = op | snake_case %}
{% if rhs_ref and rhs_t %}
{% set rhs = "&" ~ rhs_t %}
{% elif rhs_t %}
{% set rhs = rhs_t %}
{% endif %}

impl {{ op }}{% if rhs_t %}<{{ rhs }}>{% endif %} for {% if self_ref %}&{% endif %}{{ self_t }} {
{% if output_t %}
type Output = {{ output_t }};
{% endif -%}
#[inline]
fn {{ method }}({{ self }}{% if rhs_t %}, rhs: {{ rhs }}{% endif %}){% if output_t %} -> {{ output_t }}{% endif %}{
{% if self_ref %} (*self) {% else %} self {% endif %}.{{method}}
({% if rhs_ref %} *rhs {% elif rhs_t %} rhs {% endif %})
}
}
{% endmacro impl_op_ref_inner %}

{% macro impl_op_ref(op, self_t, rhs_t=false, output_t=false, self="self") %}
{%if rhs_t %}
{{ self::impl_op_ref_inner(op=op, self_t=self_t, rhs_t=rhs_t, output_t=output_t, self=self, self_ref=false, rhs_ref=true) }}
{%if output_t %}
{{ self::impl_op_ref_inner(op=op, self_t=self_t, rhs_t=rhs_t, output_t=output_t, self=self, self_ref=true, rhs_ref=true) }}
{% endif %}
{% endif %}
{%if output_t %}
{{ self::impl_op_ref_inner(op=op, self_t=self_t, rhs_t=rhs_t, output_t=output_t, self=self, self_ref=true, rhs_ref=false) }}
{% endif %}
{% endmacro impl_op_ref %}
Loading

0 comments on commit 7da958d

Please sign in to comment.