Skip to content

Commit

Permalink
Support tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
propensive committed Sep 15, 2024
1 parent 872c5e6 commit 32dfa69
Show file tree
Hide file tree
Showing 6 changed files with 190 additions and 2 deletions.
24 changes: 24 additions & 0 deletions src/core/contingency-core.scala
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ infix type raises [SuccessType, ErrorType <: Exception] = Tactic[ErrorType] ?=>
infix type mitigates [ErrorType <: Exception, ErrorType2 <: Exception] =
ErrorType2 is Mitigable into ErrorType

infix type traces [ResultType, TraceType] = Tracing[TraceType] ?=> ResultType

inline def focus[TraceType, ResultType](using inline trace: Tracing[TraceType])
(transform: Optional[TraceType] => TraceType)
(block: => ResultType)
: Unit =
val length = trace.length
block.also:
trace.supplement(trace.length - length, transform)

transparent inline def tend(inline block: PartialFunction[Exception, Exception]): Any =
${Contingency.tend('block)}

Expand All @@ -125,6 +135,13 @@ extension [ResultType, LambdaType[_]](inline mend: Mend[ResultType, LambdaType])
: ResultType2 =
${Contingency.mendWithin[LambdaType, ResultType2]('mend, 'lambda)}

transparent inline def trace[AccrualType <: Exception](accrual: AccrualType)[TraceType]
(using DummyImplicit)
[ResultType]
(inline block: (focus: Optional[TraceType], accrual: AccrualType) ?=> PartialFunction[Exception, AccrualType])
: Any =
${Contingency.trace[AccrualType, TraceType]('accrual, 'block)}

transparent inline def accrue[AccrualType <: Exception](accrual: AccrualType)[ResultType]
(inline block: (accrual: AccrualType) ?=> PartialFunction[Exception, AccrualType])
: Any =
Expand All @@ -136,3 +153,10 @@ extension [AccrualType <: Exception, LambdaType[_]]
(using tactic: Tactic[AccrualType])
: ResultType =
${Contingency.accrueWithin[AccrualType, LambdaType, ResultType]('accrue, 'lambda, 'tactic)}

extension [AccrualType <: Exception, LambdaType[_], TraceType]
(inline trace: Trace[AccrualType, LambdaType, TraceType])
inline def within[ResultType](inline lambda: Tracing[TraceType] ?=> LambdaType[ResultType])
(using tactic: Tactic[AccrualType])
: ResultType =
${ Contingency.traceWithin[AccrualType, LambdaType, ResultType, TraceType]('trace, 'lambda, 'tactic) }
63 changes: 62 additions & 1 deletion src/core/contingency.Contingency.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import scala.quoted.*
import anticipation.*
import fulminate.*
import rudiments.*
import vacuous.*

object Contingency:

Expand Down Expand Up @@ -124,8 +125,32 @@ object Contingency:
(typeLambda.asType: @unchecked) match
case '[type typeLambda[_]; typeLambda] => '{Tend[typeLambda]($handler)}

def trace[AccrualType <: Exception: Type, TraceType: Type]
(accrual: Expr[AccrualType],
handler: Expr[(Optional[TraceType], AccrualType) ?=> PartialFunction[Exception, AccrualType]])
(using Quotes)
: Expr[Any] =

import quotes.reflect.*

val errors = mapping(handler.asTerm)
val tactics = errors.keys.to(List).map(_.typeRef).map(TypeRepr.of[Tactic].appliedTo(_))
val functionType = defn.FunctionClass(errors.size, true).typeRef

val typeLambda =
TypeLambda
(List("ResultType"),
_ => List(TypeBounds(TypeRepr.of[Nothing], TypeRepr.of[Any])),
typeLambda => functionType.appliedTo(tactics :+ typeLambda.param(0)))

(typeLambda.asType: @unchecked) match
case '[type typeLambda[_]; typeLambda] =>
'{Trace[AccrualType, typeLambda, TraceType]($accrual, (focus, accrual) ?=> $handler(using focus, accrual))}

def accrue[AccrualType <: Exception: Type]
(accrual: Expr[AccrualType], handler: Expr[AccrualType ?=> PartialFunction[Exception, AccrualType]])(using Quotes)
(accrual: Expr[AccrualType],
handler: Expr[AccrualType ?=> PartialFunction[Exception, AccrualType]])
(using Quotes)
: Expr[Any] =

import quotes.reflect.*
Expand Down Expand Up @@ -254,3 +279,39 @@ object Contingency:
case null => value
case error => $tactic.abort(error)
}

def traceWithin[AccrualType <: Exception: Type, ContextType[_]: Type, ResultType: Type, TraceType: Type]
(trace: Expr[Trace[AccrualType, ContextType, TraceType]],
lambda: Expr[Tracing[TraceType] ?=> ContextType[ResultType]],
tactic: Expr[Tactic[AccrualType]])
(using Quotes)
: Expr[ResultType] =

'{ val tracing: Tracing[TraceType] = Tracing()
val result = boundary[Option[ResultType]]: label ?=>
${ import quotes.reflect.*

val cases = unwrap(trace.asTerm) match
case Apply(_, List(_, Block(List(DefDef(_, _, _, Some(block))), _))) =>
mapping(unwrap(block))

case other => abandon:
m"argument to `trace` should be a partial function implemented as match cases"

val tactics = cases.map: (_, _) =>
'{SupplementTactic(label, $trace.initial, tracing)}.asTerm

val contextTypeRepr = TypeRepr.of[ContextType[ResultType]]
val method = contextTypeRepr.typeSymbol.declaredMethod("apply").head
val term = '{$lambda(using tracing)}.asTerm.select(method).appliedToArgs(tactics.to(List))
val expr = term.asExprOf[ResultType]

'{Some($expr)} }

result match
case None => $tactic.abort($trace.initial)
case Some(value) =>
if tracing.success then value
else $tactic.abort(tracing.fold[AccrualType]($trace.initial)($trace.lambda(using _, _)))

}
24 changes: 24 additions & 0 deletions src/core/contingency.Focus.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Contingency, version [unreleased]. Copyright 2024 Jon Pretty, Propensive OÜ.
The primary distribution site is: https://propensive.com/
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 contingency

import vacuous.*

class Trace[AccrualType <: Exception, LambdaType[_], TraceType]
(val initial: AccrualType,
val lambda: (supplement: Optional[TraceType], accrual: AccrualType) ?=>
PartialFunction[Exception, AccrualType])
35 changes: 35 additions & 0 deletions src/core/contingency.SupplementTactic.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Contingency, version [unreleased]. Copyright 2024 Jon Pretty, Propensive OÜ.
The primary distribution site is: https://propensive.com/
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 contingency

import language.experimental.pureFunctions

import rudiments.*

@capability
class SupplementTactic
[ErrorType <: Exception, AccrualType, ResultType, SupplementType]
(label: boundary.Label[Option[ResultType]],
initial: AccrualType,
trace: Tracing[SupplementType])
extends Tactic[ErrorType]:
def record(error: ErrorType): Unit = trace.register(error)
def finish(): Unit = ()

def abort(error: ErrorType): Nothing =
trace.register(error)
boundary.break(None)(using label)
2 changes: 1 addition & 1 deletion src/core/contingency.Tactic.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ object Tactic:

given [ErrorType <: Exception](using erased ErrorType is Unchecked)
=> Tactic[ErrorType] as uncheckedErrors:
import unsafeExceptions.canThrowAny
given CanThrow[Exception] = unsafeExceptions.canThrowAny
def record(error: ErrorType): Unit = throw error
def abort(error: ErrorType): Nothing = throw error

Expand Down
44 changes: 44 additions & 0 deletions src/core/contingency.Tracing.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
Contingency, version [unreleased]. Copyright 2024 Jon Pretty, Propensive OÜ.
The primary distribution site is: https://propensive.com/
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 contingency

import rudiments.*
import vacuous.*

import scala.collection.mutable as scm

class Tracing[SupplementType]():
private val buffer: scm.ArrayBuffer[Exception] = scm.ArrayBuffer()
private val supplements: scm.ArrayBuffer[Optional[SupplementType]] = scm.ArrayBuffer()

def length: Int = buffer.length
def success: Boolean = length == 0
def register(error: Exception): Unit =
buffer.append(error)
supplements.append(Unset)

def fold[AccrualType](initial: AccrualType)
(lambda: (Optional[SupplementType], AccrualType) => PartialFunction[Exception, AccrualType])
: AccrualType =
(0 until buffer.length).foldLeft(initial): (accrual, index) =>
lambda(supplements(index), accrual)(buffer(index))

def supplement(last: Int, transform: Optional[SupplementType] => SupplementType)
: Unit =

for i <- (buffer.length - last) until buffer.length do
supplements(i) = transform(supplements(i))

0 comments on commit 32dfa69

Please sign in to comment.