Skip to content

Solve a closure for a given variable within a rust procedural macro

License

Notifications You must be signed in to change notification settings

TurnOfACard/proc-lineq

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

proc-lineq

Solves a basic linear equation for a variable, given a syn::ExprClosure, for use within a rust procedural macro. proc-lineq stands for "proc-macro linear equation".

The intent of this crate is to allow a procedural macro to solve a linear equation using the basic mathematical operators (add, subtract, divide multiply).

For example, if passed a syn::ExprClosure with a mathematical equation y = 5*x + 2, it will return the equation x = (y - 2)/5.

Example

If a theoretical crate had a proc-macro Inverter with an argument invert, it could use this crate to invert a closure:

#[derive(Inverter)]
#[invert("|| 5 * x + 2")]
struct Invertable;

It could produce:

impl Invertable {
    fn calculate(value: usize) -> usize {
        // This next line is generated by this crate.
        let closure = |v| (v-2)/5;
        // The other code is generated by the procedural macro
        closure(value)
    }
}

The code to produce this closure is shown in the usage section below.

Usage

Within the procedural macro, first build a syn::ExprClosure. Then, build a Variables struct. Then ask the Variables struct to build an inverted closure:

use quote::format_ident;
use proc_lineq::Variables;

let closure: ExprClosure = syn::parse_quote!( || 5 * x + 2 );
let mut eq = ClosureInverter::new(format_ident!("x"), format_ident!("y"));
let solved_closure = eq.solve(closure);

An example of a simple implementation can be found in the proc-lineq-derive folder.

About

Solve a closure for a given variable within a rust procedural macro

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages