1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use crate::expression::Expression;
use crate::variable::{FormatWithVars, Variable};
use core::fmt::{Debug, Formatter};
use std::ops::{Shl, Shr, Sub};
pub struct Constraint {
pub(crate) expression: Expression,
pub(crate) is_equality: bool,
}
impl Constraint {
fn new(expression: Expression, is_equality: bool) -> Constraint {
Constraint {
expression,
is_equality,
}
}
}
impl FormatWithVars for Constraint {
fn format_with<FUN>(&self, f: &mut Formatter<'_>, variable_format: FUN) -> std::fmt::Result
where
FUN: Fn(&mut Formatter<'_>, Variable) -> std::fmt::Result,
{
self.expression.linear.format_with(f, variable_format)?;
write!(f, " {} ", if self.is_equality { "=" } else { "<=" })?;
write!(f, "{}", -self.expression.constant)
}
}
impl Debug for Constraint {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.format_debug(f)
}
}
pub fn eq<B, A: Sub<B, Output = Expression>>(a: A, b: B) -> Constraint {
Constraint::new(a - b, true)
}
pub fn leq<B, A: Sub<B, Output = Expression>>(a: A, b: B) -> Constraint {
Constraint::new(a - b, false)
}
pub fn geq<A, B: Sub<A, Output = Expression>>(a: A, b: B) -> Constraint {
leq(b, a)
}
macro_rules! impl_shifts {
($($t:ty)*) => {$(
impl< RHS> Shl<RHS> for $t where Self: Sub<RHS, Output=Expression> {
type Output = Constraint;
fn shl(self, rhs: RHS) -> Self::Output {
leq(self, rhs)
}
}
impl< RHS: Sub<Self, Output=Expression>> Shr<RHS> for $t {
type Output = Constraint;
fn shr(self, rhs: RHS) -> Self::Output {
geq(self, rhs)
}
}
)*}
}
impl_shifts!(Expression Variable);
#[macro_export]
macro_rules! constraint {
([$($left:tt)*] <= $($right:tt)*) => {
$crate::constraint::leq($($left)*, $($right)*)
};
([$($left:tt)*] >= $($right:tt)*) => {
$crate::constraint::geq($($left)*, $($right)*)
};
([$($left:tt)*] == $($right:tt)*) => {
$crate::constraint::eq($($left)*, $($right)*)
};
([$($left:tt)*]) => {
$($left:tt)*
};
([$($left:tt)*] $next:tt $($right:tt)*) => {
constraint!([$($left)* $next] $($right)*)
};
($($all:tt)*) => {
constraint!([] $($all)*)
};
}
#[cfg(test)]
mod tests {
use crate::variables;
#[test]
fn test_leq() {
let mut vars = variables!();
let v0 = vars.add_variable();
let v1 = vars.add_variable();
let f = format!("{:?}", (3. - v0) >> v1);
assert!(vec!["v0 + v1 <= 3", "v1 + v0 <= 3"].contains(&&*f), "{}", f)
}
}