-
Notifications
You must be signed in to change notification settings - Fork 9
/
meta.scala
401 lines (369 loc) · 16.6 KB
/
meta.scala
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
* Copyright 2022 Erik Erlandson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package coulomb.infra
import coulomb.rational.Rational
import coulomb.*
import coulomb.define.*
object meta:
import scala.unchecked
import scala.quoted.*
import scala.language.implicitConversions
given ctx_RationalToExpr: ToExpr[Rational] with
def apply(r: Rational)(using Quotes): Expr[Rational] = r match
// Rational(1) is a useful special case to have predefined
// could we get clever with some kind of expression caching/sharing here?
case v if (v == 1) => '{ Rational.const1 }
case _ => '{ Rational(${ Expr(r.n) }, ${ Expr(r.d) }) }
sealed class SigMode
object SigMode:
/**
* Canonical mode yields signatures fully expand down to base units. Its
* primary purpose is to compute coefficients of unit conversion, or
* determine whether two unit types are convertable.
*/
case object Canonical extends SigMode
/**
* Simplify mode is for constructing operator output types. It does not
* expand derived units, and respects type aliases.
*/
case object Simplify extends SigMode
/**
* Constant mode is for extracting constant coefficents from derived
* unit definitions. It is used by the physical-constants library.
*/
case object Constant extends SigMode
object rationalTE:
def unapply(using Quotes)(
tr: quotes.reflect.TypeRepr
): Option[Rational] =
import quotes.reflect.*
tr match
case AppliedType(op, List(rationalTE(n), rationalTE(d)))
if (op =:= TypeRepr.of[/]) =>
Some(n / d)
case AppliedType(op, List(rationalTE(n), rationalTE(d)))
if (op =:= TypeRepr.of[*]) =>
Some(n * d)
case AppliedType(op, List(rationalTE(b), bigintTE(e)))
if (op =:= TypeRepr.of[^]) && e.isValidInt =>
Some(b.pow(e.toInt))
case bigintTE(v) => Some(Rational(v, 1))
case ConstantType(DoubleConstant(v)) => Some(Rational(v))
case ConstantType(FloatConstant(v)) => Some(Rational(v))
case _ => None
def apply(using Quotes)(v: Rational): quotes.reflect.TypeRepr =
import quotes.reflect.*
if (v.d == 1) then bigintTE(v.n)
else TypeRepr.of[/].appliedTo(List(bigintTE(v.n), bigintTE(v.d)))
object bigintTE:
def unapply(using Quotes)(tr: quotes.reflect.TypeRepr): Option[BigInt] =
import quotes.reflect.*
tr match
case ConstantType(IntConstant(v)) => Some(BigInt(v))
case ConstantType(LongConstant(v)) => Some(BigInt(v))
case ConstantType(StringConstant(v)) => Some(BigInt(v))
case _ => None
def apply(using Quotes)(v: BigInt): quotes.reflect.TypeRepr =
import quotes.reflect.*
v match
case _ if v.isValidInt => ConstantType(IntConstant(v.toInt))
case _ if v.isValidLong => ConstantType(LongConstant(v.toLong))
case _ => ConstantType(StringConstant(v.toString()))
def coefficient[U1, U2](using Quotes, Type[U1], Type[U2]): Expr[Rational] =
import quotes.reflect.*
// this call will fail if no coefficient exists, which means that
// U1 and U2 are not convertable
val c = coef(TypeRepr.of[U1], TypeRepr.of[U2])
Expr(c)
def coef(using
Quotes
)(u1: quotes.reflect.TypeRepr, u2: quotes.reflect.TypeRepr): Rational =
import quotes.reflect.*
// the fundamental algorithmic unit analysis criterion:
// http://erikerlandson.github.io/blog/2019/05/03/algorithmic-unit-analysis/
given sigmode: SigMode = SigMode.Canonical
val (rcoef, rsig) = cansig(TypeRepr.of[/].appliedTo(List(u1, u2)))
if (rsig == Nil) then rcoef
else
report.error(
s"unit type ${typestr(u1)} not convertable to ${typestr(u2)}"
)
Rational.const0
def offset(using
Quotes
)(u: quotes.reflect.TypeRepr, b: quotes.reflect.TypeRepr): Rational =
import quotes.reflect.*
given sigmode: SigMode = SigMode.Simplify
u match
case deltaunit(offset, db) =>
if (matchingdelta(db, b)) offset
else
report.error(s"bad DeltaUnit in offset: ${typestr(u)}")
Rational.const0
case baseunit() if convertible(u, b) => Rational.const0
case derivedunit(_, _) if convertible(u, b) => Rational.const0
case _ => {
report.error(
s"unknown unit expression in offset: ${typestr(u)}"
); Rational.const0
}
def matchingdelta(using
Quotes
)(db: quotes.reflect.TypeRepr, b: quotes.reflect.TypeRepr): Boolean =
import quotes.reflect.*
// units of db and b should cancel, and leave only a constant behind
simplify(TypeRepr.of[/].appliedTo(List(db, b))) match
case rationalTE(_) => true
case _ => false
def convertible(using
Quotes
)(u1: quotes.reflect.TypeRepr, u2: quotes.reflect.TypeRepr): Boolean =
import quotes.reflect.*
given sigmode: SigMode = SigMode.Canonical
val (_, rsig) = cansig(TypeRepr.of[/].appliedTo(List(u1, u2)))
rsig == Nil
// returns tuple: (expr-for-coef, type-of-Res)
def cansig(using qq: Quotes, mode: SigMode)(
uu: quotes.reflect.TypeRepr
): (Rational, List[(quotes.reflect.TypeRepr, Rational)]) =
import quotes.reflect.*
val u = mode match
// in simplification mode we respect type aliases
case SigMode.Simplify => uu
case _ => uu.dealias
// if this encounters a unit type pattern it cannot expand to a canonical signature,
// at any level, it raises a compile-time error such that the context parameter search fails.
u match
// identify embedded coefficients (includes '1' aka unitless)
case unitconst(c) =>
mode match
case SigMode.Simplify =>
// in simplify mode we preserve constants in the signature
if (c == 1) (Rational.const1, Nil)
else (Rational.const1, (u, Rational.const1) :: Nil)
case _ => (c, Nil)
// traverse down the operator types first, since that can be done without
// any attempts to look up context variables for BaseUnit and DerivedUnit,
// which only happen at the leaves of expressions
case AppliedType(op, List(lu, ru)) if (op =:= TypeRepr.of[*]) =>
val (lcoef, lsig) = cansig(lu)
val (rcoef, rsig) = cansig(ru)
val usig = unifyOp(lsig, rsig, _ + _)
(lcoef * rcoef, usig)
case AppliedType(op, List(lu, ru)) if (op =:= TypeRepr.of[/]) =>
val (lcoef, lsig) = cansig(lu)
val (rcoef, rsig) = cansig(ru)
val usig = unifyOp(lsig, rsig, _ - _)
(lcoef / rcoef, usig)
case AppliedType(op, List(b, p)) if (op =:= TypeRepr.of[^]) =>
val (bcoef, bsig) = cansig(b)
val rationalTE(e) = p: @unchecked
if (e == 0) (Rational.const1, Nil)
else if (e == 1) (bcoef, bsig)
else if (e.n.isValidInt && e.d.isValidInt)
val ucoef =
if (e.d == 1) bcoef.pow(e.n.toInt)
else bcoef.pow(e.n.toInt).root(e.d.toInt)
val usig = unifyPow(e, bsig)
(ucoef, usig)
else
report.error(s"bad exponent in cansig: ${typestr(u)}")
(Rational.const0, Nil)
case baseunit() => (Rational.const1, (u, Rational.const1) :: Nil)
case derivedunit(ucoef, usig) =>
mode match
case SigMode.Canonical => (ucoef, usig)
case _ => (Rational.const1, (u, Rational.const1) :: Nil)
case _ =>
// treat any other type as if it were a BaseUnit
(Rational.const1, (u, Rational.const1) :: Nil)
def sortsig(using Quotes)(
sig: List[(quotes.reflect.TypeRepr, Rational)]
): (
List[(quotes.reflect.TypeRepr, Rational)],
List[(quotes.reflect.TypeRepr, Rational)]
) =
sig match
case Nil => (Nil, Nil)
case (u, e) :: tail =>
val (nsig, dsig) = sortsig(tail)
if (e > 0) ((u, e) :: nsig, dsig) else (nsig, (u, -e) :: dsig)
def simplify(using Quotes)(
u: quotes.reflect.TypeRepr
): quotes.reflect.TypeRepr =
import quotes.reflect.*
given sigmode: SigMode = SigMode.Simplify
simplifysig(cansig(u)._2)
def simplifysig(using Quotes)(
sig: List[(quotes.reflect.TypeRepr, Rational)]
): quotes.reflect.TypeRepr =
import quotes.reflect.*
val (un, ud) = sortsig(sig)
(uProd(un), uProd(ud)) match
case (unitconst1(), unitconst1()) => TypeRepr.of[1]
case (n, unitconst1()) => n
case (unitconst1(), d) =>
TypeRepr.of[/].appliedTo(List(TypeRepr.of[1], d))
case (n, d) => TypeRepr.of[/].appliedTo(List(n, d))
def uProd(using Quotes)(
sig: List[(quotes.reflect.TypeRepr, Rational)]
): quotes.reflect.TypeRepr =
import quotes.reflect.*
sig match
case Nil => TypeRepr.of[1]
case (u, e) :: Nil => uTerm(u, e)
case (u1, e1) :: (u2, e2) :: Nil =>
TypeRepr.of[*].appliedTo(List(uTerm(u1, e1), uTerm(u2, e2)))
case (u, e) :: tail =>
TypeRepr.of[*].appliedTo(List(uTerm(u, e), uProd(tail)))
def uTerm(using
Quotes
)(u: quotes.reflect.TypeRepr, p: Rational): quotes.reflect.TypeRepr =
import quotes.reflect.*
if (p == 1) u else TypeRepr.of[^].appliedTo(List(u, rationalTE(p)))
object unitconst1:
def unapply(using Quotes)(u: quotes.reflect.TypeRepr): Boolean =
u match
case rationalTE(v) if (v == 1) => true
case _ => false
object unitconst:
def unapply(using Quotes)(
u: quotes.reflect.TypeRepr
): Option[Rational] =
u match
case rationalTE(v) => Some(v)
case _ => None
object baseunit:
def unapply(using Quotes)(u: quotes.reflect.TypeRepr): Boolean =
import quotes.reflect.*
Implicits.search(
TypeRepr
.of[BaseUnit]
.appliedTo(List(u, TypeBounds.empty, TypeBounds.empty))
) match
case iss: ImplicitSearchSuccess => true
case _ => false
object derivedunit:
def unapply(using qq: Quotes, mode: SigMode)(
u: quotes.reflect.TypeRepr
): Option[(Rational, List[(quotes.reflect.TypeRepr, Rational)])] =
import quotes.reflect.*
Implicits.search(
TypeRepr
.of[DerivedUnit]
.appliedTo(
List(
u,
TypeBounds.empty,
TypeBounds.empty,
TypeBounds.empty
)
)
) match
case iss: ImplicitSearchSuccess =>
mode match
case SigMode.Simplify =>
// don't expand the signature definition in simplify mode
Some((Rational.const1, (u, Rational.const1) :: Nil))
case _ =>
val AppliedType(_, List(_, d, _, _)) =
iss.tree.tpe.baseType(
TypeRepr.of[DerivedUnit].typeSymbol
): @unchecked
Some(cansig(d))
case _ => None
object deltaunit:
def unapply(using Quotes)(
u: quotes.reflect.TypeRepr
): Option[(Rational, quotes.reflect.TypeRepr)] =
import quotes.reflect.*
Implicits.search(
TypeRepr
.of[DeltaUnit]
.appliedTo(
List(
u,
TypeBounds.empty,
TypeBounds.empty,
TypeBounds.empty,
TypeBounds.empty
)
)
) match
case iss: ImplicitSearchSuccess =>
val AppliedType(_, List(_, b, o, _, _)) =
iss.tree.tpe.baseType(
TypeRepr.of[DeltaUnit].typeSymbol
): @unchecked
val rationalTE(offset) = o: @unchecked
Some((offset, b))
case _ => None
def unifyOp(using Quotes)(
sig1: List[(quotes.reflect.TypeRepr, Rational)],
sig2: List[(quotes.reflect.TypeRepr, Rational)],
op: (Rational, Rational) => Rational
): List[(quotes.reflect.TypeRepr, Rational)] =
sig2 match
case Nil => sig1
case (u, e) :: tail => unifyOp(insertTerm(u, e, sig1, op), tail, op)
def insertTerm(using Quotes)(
u: quotes.reflect.TypeRepr,
e: Rational,
sig: List[(quotes.reflect.TypeRepr, Rational)],
op: (Rational, Rational) => Rational
): List[(quotes.reflect.TypeRepr, Rational)] =
sig match
case Nil => (u, op(Rational.const0, e)) :: Nil
case (u0, e0) :: tail if (u =:= u0) =>
val ei = op(e0, e)
if (ei == Rational.const0) tail else (u, ei) :: tail
case (u0, e0) :: tail => (u0, e0) :: insertTerm(u, e, tail, op)
def unifyPow(using Quotes)(
e: Rational,
sig: List[(quotes.reflect.TypeRepr, Rational)]
): List[(quotes.reflect.TypeRepr, Rational)] =
sig match
case _ if (e == Rational.const0) => Nil
case Nil => Nil
case (u, e0) :: tail => (u, e0 * e) :: unifyPow(e, tail)
def typestr(using Quotes)(t: quotes.reflect.TypeRepr): String =
import quotes.reflect.*
def work(tr: TypeRepr): String = tr match
// The policy goal here is that type aliases are never expanded.
case typealias(_) => tr.typeSymbol.name
case unitconst(v) => s"$v"
case AppliedType(op, List(lhs, rhs)) if op =:= TypeRepr.of[*] =>
s"(${work(lhs)} * ${work(rhs)})"
case AppliedType(op, List(lhs, rhs)) if op =:= TypeRepr.of[/] =>
s"(${work(lhs)} / ${work(rhs)})"
case AppliedType(op, List(lhs, rhs)) if op =:= TypeRepr.of[^] =>
s"(${work(lhs)} ^ ${work(rhs)})"
case AppliedType(tc, ta) =>
val tcn = tc.typeSymbol.name
val as = ta.map(work)
if (as.length == 0) tcn
else
tcn + "[" + as.mkString(",") + "]"
case t => t.typeSymbol.name
work(t)
object typealias:
def unapply(using Quotes)(
t: quotes.reflect.TypeRepr
): Option[quotes.reflect.TypeRepr] =
import quotes.reflect.*
val d = t.dealias
// "=:=" doesn't work here, it will test 'true' even if dealiasing happened
if (d.typeSymbol.name == t.typeSymbol.name) None else Some(d)