refactor into SqError

This commit is contained in:
Vyacheslav Matyukhin 2022-09-26 04:44:08 +04:00
parent 111dd5535c
commit 69b32d0b93
No known key found for this signature in database
GPG Key ID: 3D2A774C5489F96C
36 changed files with 329 additions and 404 deletions

View File

@ -22,9 +22,7 @@ let expectExpressionToBe = (expr, answer, ~v="_", ()) => {
} else {
let a2 =
rExpr
->E.R2.errMap(e =>
e->Reducer_ErrorValue.fromParseError->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue
)
->E.R2.errMap(e => e->SqError.Message.fromParseError->SqError.Error.fromMessage)
->Result.flatMap(expr => Expression.BackCompatible.evaluate(expr))
->Reducer_Value.toStringResultOkless
(a1, a2)->expect->toEqual((answer, v))

View File

@ -1,4 +1,3 @@
module ErrorValue = Reducer_ErrorValue
module Expression = Reducer_Expression
module ExpressionT = Reducer_Expression_T
@ -9,7 +8,7 @@ let unwrapRecord = rValue =>
rValue->Belt.Result.flatMap(value =>
switch value {
| Reducer_T.IEvRecord(aRecord) => Ok(aRecord)
| _ => ErrorValue.RETodo("TODO: Internal bindings must be returned")->Error
| _ => SqError.Message.RETodo("TODO: Internal bindings must be returned")->Error
}
)

View File

@ -70,7 +70,7 @@ describe("test exceptions", () => {
testDescriptionEvalToBe(
"javascript exception",
"javascriptraise('div by 0')",
"Error(Error: 'div by 0')",
"Error(JS Exception: Error: 'div by 0')",
)
// testDescriptionEvalToBe(
// "rescript exception",

View File

@ -25,7 +25,7 @@ x=1`,
let mainIncludes = Project.getIncludes(project, "main")
switch mainIncludes {
| Ok(includes) => expect(includes) == ["common"]
| Error(error) => fail(error->Reducer_ErrorValue.errorValueToString)
| Error(error) => fail(error->SqError.Message.toString)
}
})
test("past chain", () => {
@ -60,7 +60,7 @@ x=1`,
let mainIncludes = Project.getIncludes(project, "main")
switch mainIncludes {
| Ok(includes) => expect(includes) == ["common", "myModule"]
| Error(error) => fail(error->Reducer_ErrorValue.errorValueToString)
| Error(error) => fail(error->SqError.Message.toString)
}
})
@ -99,7 +99,7 @@ x=1`,
let mainIncludes = Project.getIncludes(project, "main")
switch mainIncludes {
| Ok(includes) => expect(includes) == ["common", "common2", "myModule"]
| Error(error) => fail(error->Reducer_ErrorValue.errorValueToString)
| Error(error) => fail(error->SqError.Message.toString)
}
})
test("direct past chain", () => {

View File

@ -36,7 +36,7 @@ Here we will finally proceed to a real life scenario. */
/* Parse includes has set the includes */
switch project->Project.getIncludes("main") {
| Ok(includes) => includes->expect == ["common"]
| Error(err) => err->Reducer_ErrorValue.errorValueToString->fail
| Error(err) => err->SqError.Message.toString->fail
}
/* If the includes cannot be parsed then you get a syntax error.
Otherwise you get the includes.
@ -85,7 +85,7 @@ Here we will finally proceed to a real life scenario. */
let rIncludes = project->Project.getIncludes(sourceName)
switch rIncludes {
/* Maybe there is an include syntax error */
| Error(err) => err->Reducer_ErrorValue.errorValueToString->Js.Exn.raiseError
| Error(err) => err->SqError.Message.toString->Js.Exn.raiseError
| Ok(includes) =>
includes->Belt.Array.forEach(newIncludeName => {
@ -169,7 +169,7 @@ Here we will finally proceed to a real life scenario. */
test("getIncludes", () => {
switch Project.getIncludes(project, "main") {
| Ok(includes) => includes->expect == ["common"]
| Error(err) => err->Reducer_ErrorValue.errorValueToString->fail
| Error(err) => err->SqError.Message.toString->fail
}
})
})

View File

@ -1,13 +1,13 @@
import * as RSErrorValue from "../rescript/ForTS/ForTS_Reducer_ErrorValue.gen";
import * as RSError from "../rescript/ForTS/ForTS_SqError.gen";
export class SqError {
constructor(private _value: RSErrorValue.reducerError) {}
constructor(private _value: RSError.error) {}
toString() {
return RSErrorValue.toString(this._value);
return RSError.toString(this._value);
}
static createOtherError(v: string) {
return new SqError(RSErrorValue.createOtherError(v));
return new SqError(RSError.createOtherError(v));
}
}

View File

@ -1,15 +1,12 @@
import * as RSProject from "../rescript/ForTS/ForTS_ReducerProject.gen";
import {
reducerError,
reducerErrorValue,
attachEmptyStackTraceToErrorValue,
} from "../rescript/ForTS/ForTS_Reducer_ErrorValue.gen";
import * as RSError from "../rescript/ForTS/ForTS_SqError.gen";
import { environment } from "../rescript/ForTS/ForTS_Distribution/ForTS_Distribution_Environment.gen";
import { SqError } from "./SqError";
import { SqRecord } from "./SqRecord";
import { wrapValue } from "./SqValue";
import { resultMap2 } from "./types";
import { SqValueLocation } from "./SqValueLocation";
import { errorFromMessage } from "../rescript/ForTS/ForTS_SqError.gen";
export class SqProject {
constructor(private _value: RSProject.reducerProject) {}
@ -54,8 +51,7 @@ export class SqProject {
return resultMap2(
RSProject.getIncludes(this._value, sourceId),
(a) => a,
(v: reducerErrorValue) =>
new SqError(attachEmptyStackTraceToErrorValue(v))
(v: RSError.errorMessage) => new SqError(errorFromMessage(v))
);
}
@ -109,7 +105,7 @@ export class SqProject {
items: [],
})
),
(v: reducerError) => new SqError(v)
(v: RSError.error) => new SqError(v)
);
}

View File

@ -5,7 +5,7 @@ let nameSpace = "" // no namespaced versions
type simpleDefinition = {
inputs: array<frType>,
fn: array<Reducer_T.value> => result<Reducer_T.value, errorValue>,
fn: array<Reducer_T.value> => result<Reducer_T.value, errorMessage>,
}
let makeFnMany = (name: string, definitions: array<simpleDefinition>) =>
@ -22,7 +22,7 @@ let makeFnMany = (name: string, definitions: array<simpleDefinition>) =>
let makeFn = (
name: string,
inputs: array<frType>,
fn: array<Reducer_T.value> => result<Reducer_T.value, errorValue>,
fn: array<Reducer_T.value> => result<Reducer_T.value, errorMessage>,
) => makeFnMany(name, [{inputs: inputs, fn: fn}])
let library = [

View File

@ -77,7 +77,7 @@ module Integration = {
| Reducer_T.IEvNumber(x) => Ok(x)
| _ =>
Error(
"Error 1 in Danger.integrate. It's possible that your function doesn't return a number, try definining auxiliaryFunction(x) = mean(yourFunction(x)) and integrate auxiliaryFunction instead"->Reducer_ErrorValue.REOther,
"Error 1 in Danger.integrate. It's possible that your function doesn't return a number, try definining auxiliaryFunction(x) = mean(yourFunction(x)) and integrate auxiliaryFunction instead"->SqError.Message.REOther,
)
}
result
@ -143,8 +143,8 @@ module Integration = {
| Error(b) =>
("Integration error 2 in Danger.integrate. It's possible that your function doesn't return a number, try definining auxiliaryFunction(x) = mean(yourFunction(x)) and integrate auxiliaryFunction instead." ++
"Original error: " ++
b->Reducer_ErrorValue.errorValueToString)
->Reducer_ErrorValue.REOther
b->SqError.Message.toString)
->SqError.Message.REOther
->Error
}
result
@ -169,7 +169,7 @@ module Integration = {
let result = switch inputs {
| [_, _, _, IEvNumber(0.0)] =>
"Integration error 4 in Danger.integrate: Increment can't be 0."
->Reducer_ErrorValue.REOther
->SqError.Message.REOther
->Error
| [
IEvLambda(aLambda),
@ -187,7 +187,7 @@ module Integration = {
)
| _ =>
Error(
Reducer_ErrorValue.REOther(
SqError.Message.REOther(
"Integration error 5 in Danger.integrate. Remember that inputs are (function, number (min), number (max), number(increment))",
),
)
@ -213,7 +213,7 @@ module Integration = {
let result = switch inputs {
| [_, _, _, IEvNumber(0.0)] =>
"Integration error in Danger.integrate: Increment can't be 0."
->Reducer_ErrorValue.REOther
->SqError.Message.REOther
->Error
| [IEvLambda(aLambda), IEvNumber(min), IEvNumber(max), IEvNumber(epsilon)] =>
Helpers.integrateFunctionBetweenWithNumIntegrationPoints(
@ -225,11 +225,11 @@ module Integration = {
reducer,
)->E.R2.errMap(b =>
("Integration error 7 in Danger.integrate. Something went wrong along the way: " ++
b->Reducer_ErrorValue.errorValueToString)->Reducer_ErrorValue.REOther
b->SqError.Message.toString)->SqError.Message.REOther
)
| _ =>
"Integration error 8 in Danger.integrate. Remember that inputs are (function, number (min), number (max), number(increment))"
->Reducer_ErrorValue.REOther
->SqError.Message.REOther
->Error
}
result
@ -246,7 +246,7 @@ module DiminishingReturns = {
module Helpers = {
type diminishingReturnsAccumulatorInner = {
optimalAllocations: array<float>,
currentMarginalReturns: result<array<float>, errorValue>,
currentMarginalReturns: result<array<float>, errorMessage>,
}
let findBiggestElementIndex = (xs: array<float>) =>
E.A.reducei(xs, 0, (acc, newElement, index) => {
@ -255,7 +255,7 @@ module DiminishingReturns = {
| false => acc
}
})
type diminishingReturnsAccumulator = result<diminishingReturnsAccumulatorInner, errorValue>
type diminishingReturnsAccumulator = result<diminishingReturnsAccumulatorInner, errorMessage>
// TODO: This is so complicated, it probably should be its own file. It might also make sense to have it work in Rescript directly, taking in a function rather than a reducer; then something else can wrap that function in the reducer/lambdas/environment.
/*
The key idea for this function is that
@ -290,19 +290,19 @@ module DiminishingReturns = {
) {
| (false, _, _, _) =>
Error(
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, number of functions should be greater than 1."->Reducer_ErrorValue.REOther,
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, number of functions should be greater than 1."->SqError.Message.REOther,
)
| (_, false, _, _) =>
Error(
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, funds should be greater than 0."->Reducer_ErrorValue.REOther,
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, funds should be greater than 0."->SqError.Message.REOther,
)
| (_, _, false, _) =>
Error(
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, approximateIncrement should be greater than 0."->Reducer_ErrorValue.REOther,
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, approximateIncrement should be greater than 0."->SqError.Message.REOther,
)
| (_, _, _, false) =>
Error(
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, approximateIncrement should be smaller than funds amount."->Reducer_ErrorValue.REOther,
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions, approximateIncrement should be smaller than funds amount."->SqError.Message.REOther,
)
| (true, true, true, true) => {
let applyFunctionAtPoint = (lambda, point: float) => {
@ -318,7 +318,7 @@ module DiminishingReturns = {
| Reducer_T.IEvNumber(x) => Ok(x)
| _ =>
Error(
"Error 1 in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions. It's possible that your function doesn't return a number, try definining auxiliaryFunction(x) = mean(yourFunction(x)) and integrate auxiliaryFunction instead"->Reducer_ErrorValue.REOther,
"Error 1 in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions. It's possible that your function doesn't return a number, try definining auxiliaryFunction(x) = mean(yourFunction(x)) and integrate auxiliaryFunction instead"->SqError.Message.REOther,
)
}
}
@ -411,7 +411,7 @@ module DiminishingReturns = {
| Reducer_T.IEvLambda(lambda) => Ok(lambda)
| _ =>
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions. A member of the array wasn't a function"
->Reducer_ErrorValue.REOther
->SqError.Message.REOther
->Error
}
}, innerlambdas)
@ -433,7 +433,7 @@ module DiminishingReturns = {
}
| _ =>
"Error in Danger.diminishingMarginalReturnsForTwoFunctions"
->Reducer_ErrorValue.REOther
->SqError.Message.REOther
->Error
},
(),

View File

@ -4,7 +4,7 @@ open FunctionRegistry_Helpers
let makeFn = (
name: string,
inputs: array<frType>,
fn: array<Reducer_T.value> => result<Reducer_T.value, errorValue>,
fn: array<Reducer_T.value> => result<Reducer_T.value, errorMessage>,
) =>
Function.make(
~name,
@ -66,7 +66,7 @@ let library = [
| [IEvNumber(year)] =>
switch DateTime.Date.makeFromYear(year) {
| Ok(t) => IEvDate(t)->Ok
| Error(e) => Reducer_ErrorValue.RETodo(e)->Error
| Error(e) => SqError.Message.RETodo(e)->Error
}
| _ => Error(impossibleError)
}

View File

@ -17,7 +17,7 @@ module Internals = {
->E.A2.fmap(((key, value)) => Wrappers.evArray([IEvString(key), value]))
->Wrappers.evArray
let fromList = (items: array<Reducer_T.value>): result<Reducer_T.value, errorValue> =>
let fromList = (items: array<Reducer_T.value>): result<Reducer_T.value, errorMessage> =>
items
->E.A2.fmap(item => {
switch (item: Reducer_T.value) {
@ -59,7 +59,6 @@ let library = [
],
(),
),
Function.make(
~name="mergeMany",
~nameSpace,
@ -72,12 +71,16 @@ let library = [
~inputs=[FRTypeArray(FRTypeDict(FRTypeAny))],
~run=(inputs, _, _) => {
switch inputs {
| [IEvArray(dicts)] => {
dicts->Belt.Array.map(dictValue => switch dictValue {
| [IEvArray(dicts)] =>
dicts
->Belt.Array.map(dictValue =>
switch dictValue {
| IEvRecord(dict) => dict
| _ => impossibleError->Reducer_ErrorValue.toException
})->Internals.mergeMany->Ok
| _ => impossibleError->SqError.Message.toException
}
)
->Internals.mergeMany
->Ok
| _ => impossibleError->Error
}
},

View File

@ -16,14 +16,13 @@ module DistributionCreation = {
r
->E.R.bind(Process.DistOrNumberToDist.twoValuesUsingSymbolicDist(~fn, ~values=_, ~env))
->E.R2.fmap(Wrappers.evDistribution)
->E.R2.errMap(e => Reducer_ErrorValue.REOther(e))
->E.R2.errMap(e => SqError.Message.REOther(e))
let make = (name, fn) => {
FnDefinition.make(
~name,
~inputs=[FRTypeDistOrNumber, FRTypeDistOrNumber],
~run=(inputs, env, _) =>
inputs->Prepare.ToValueTuple.twoDistOrNumber->process(~fn, ~env),
~run=(inputs, env, _) => inputs->Prepare.ToValueTuple.twoDistOrNumber->process(~fn, ~env),
(),
)
}
@ -43,7 +42,9 @@ module DistributionCreation = {
~name,
~inputs=[FRTypeRecord([("mean", FRTypeDistOrNumber), ("stdev", FRTypeDistOrNumber)])],
~run=(inputs, env, _) =>
inputs->Prepare.ToValueTuple.Record.twoDistOrNumber(("mean", "stdev"))->process(~fn, ~env),
inputs
->Prepare.ToValueTuple.Record.twoDistOrNumber(("mean", "stdev"))
->process(~fn, ~env),
(),
)
}
@ -54,14 +55,13 @@ module DistributionCreation = {
r
->E.R.bind(Process.DistOrNumberToDist.oneValueUsingSymbolicDist(~fn, ~value=_, ~env))
->E.R2.fmap(Wrappers.evDistribution)
->E.R2.errMap(e => Reducer_ErrorValue.REOther(e))
->E.R2.errMap(e => SqError.Message.REOther(e))
let make = (name, fn) =>
FnDefinition.make(
~name,
~inputs=[FRTypeDistOrNumber],
~run=(inputs, env, _) =>
inputs->Prepare.ToValueTuple.oneDistOrNumber->process(~fn, ~env),
~run=(inputs, env, _) => inputs->Prepare.ToValueTuple.oneDistOrNumber->process(~fn, ~env),
(),
)
}

View File

@ -296,7 +296,7 @@ module Old = {
let genericOutputToReducerValue = (o: DistributionOperation.outputType): result<
Reducer_T.value,
Reducer_ErrorValue.errorValue,
SqError.Message.t,
> =>
switch o {
| Dist(d) => Ok(Reducer_T.IEvDistribution(d))
@ -311,9 +311,9 @@ module Old = {
switch dispatchToGenericOutput(call, environment) {
| Some(o) => genericOutputToReducerValue(o)
| None =>
Reducer_ErrorValue.REOther("Internal error in FR_GenericDist implementation")
->Reducer_ErrorValue.ErrorException
->raise
SqError.Message.REOther(
"Internal error in FR_GenericDist implementation",
)->SqError.Message.toException
}
}
@ -405,6 +405,6 @@ let library = E.A.concatMany([
let mxLambda = Reducer_Expression_Lambda.makeFFILambda((inputs, env, _) => {
switch Old.dispatch(("mx", inputs), env) {
| Ok(value) => value
| Error(e) => e->Reducer_ErrorValue.ErrorException->raise
| Error(e) => e->SqError.Message.toException
}
})

View File

@ -7,31 +7,32 @@ let requiresNamespace = true
let inputsToDist = (inputs: array<Reducer_T.value>, xyShapeToPointSetDist) => {
// TODO - rewrite in more functional/functor-based style
switch inputs {
| [IEvArray(items)] => {
items->Belt.Array.map(
item =>
| [IEvArray(items)] =>
items
->Belt.Array.map(item =>
switch item {
| IEvRecord(map) => {
let xValue = map->Belt.Map.String.get("x")
let yValue = map->Belt.Map.String.get("y")
switch (xValue, yValue) {
| (Some(IEvNumber(x)), Some(IEvNumber(y))) => (x, y)
| _ => impossibleError->Reducer_ErrorValue.toException
| _ => impossibleError->SqError.Message.toException
}
}
| _ => impossibleError->Reducer_ErrorValue.toException
| _ => impossibleError->SqError.Message.toException
}
)->Ok->E.R.bind(r => r->XYShape.T.makeFromZipped->E.R2.errMap(XYShape.Error.toString))
)
->Ok
->E.R.bind(r => r->XYShape.T.makeFromZipped->E.R2.errMap(XYShape.Error.toString))
->E.R2.fmap(r => Reducer_T.IEvDistribution(PointSet(r->xyShapeToPointSetDist)))
}
| _ => impossibleError->Reducer_ErrorValue.toException
| _ => impossibleError->SqError.Message.toException
}
}
module Internal = {
type t = PointSetDist.t
let toType = (r): result<Reducer_T.value, Reducer_ErrorValue.errorValue> =>
let toType = (r): result<Reducer_T.value, SqError.Message.t> =>
switch r {
| Ok(r) => Ok(Wrappers.evDistribution(PointSet(r)))
| Error(err) => Error(REOperationError(err))
@ -71,7 +72,7 @@ let library = [
)
->E.R2.fmap(Wrappers.pointSet)
->E.R2.fmap(Wrappers.evDistribution)
->E.R2.errMap(e => Reducer_ErrorValue.REDistributionError(e))
->E.R2.errMap(e => SqError.Message.REDistributionError(e))
| _ => Error(impossibleError)
},
(),

View File

@ -18,7 +18,7 @@ module Internal = {
| _ => Error(Operation.SampleMapNeedsNtoNFunction)
}
let toType = (r): result<Reducer_T.value, Reducer_ErrorValue.errorValue> =>
let toType = (r): result<Reducer_T.value, SqError.Message.t> =>
switch r {
| Ok(r) => Ok(Wrappers.evDistribution(SampleSet(r)))
| Error(r) => Error(REDistributionError(SampleSetError(r)))
@ -95,7 +95,7 @@ let libaryBase = [
GenericDist.toSampleSetDist(dist, environment.sampleCount)
->E.R2.fmap(Wrappers.sampleSet)
->E.R2.fmap(Wrappers.evDistribution)
->E.R2.errMap(e => Reducer_ErrorValue.REDistributionError(e))
->E.R2.errMap(e => SqError.Message.REDistributionError(e))
| _ => Error(impossibleError)
},
(),
@ -115,9 +115,8 @@ let libaryBase = [
~inputs=[FRTypeArray(FRTypeNumber)],
~run=(inputs, _, _) => {
let sampleSet =
inputs->Prepare.ToTypedArray.numbers |> E.R2.bind(r =>
SampleSetDist.make(r)->E.R2.errMap(_ => "AM I HERE? WHYERE AMI??")
)
inputs->Prepare.ToTypedArray.numbers
|> E.R2.bind(r => SampleSetDist.make(r)->E.R2.errMap(_ => "AM I HERE? WHYERE AMI??"))
sampleSet
->E.R2.fmap(Wrappers.sampleSet)
->E.R2.fmap(Wrappers.evDistribution)
@ -164,7 +163,7 @@ let libaryBase = [
| [IEvLambda(lambda)] =>
switch Internal.fromFn(lambda, environment, reducer) {
| Ok(r) => Ok(r->Wrappers.sampleSet->Wrappers.evDistribution)
| Error(e) => e->Reducer_ErrorValue.REOperationError->Error
| Error(e) => e->SqError.Message.REOperationError->Error
}
| _ => Error(impossibleError)
},
@ -291,7 +290,7 @@ module Comparison = {
r
->E.R2.fmap(r => r->Wrappers.sampleSet->Wrappers.evDistribution)
->E.R2.errMap(e =>
e->DistributionTypes.Error.sampleErrorToDistErr->Reducer_ErrorValue.REDistributionError
e->DistributionTypes.Error.sampleErrorToDistErr->SqError.Message.REDistributionError
)
let mkBig = (name, withDist, withFloat) =>

View File

@ -6,7 +6,7 @@ let requiresNamespace = true
let runScoring = (estimate, answer, prior, env) => {
GenericDist.Score.logScore(~estimate, ~answer, ~prior, ~env)
->E.R2.fmap(FunctionRegistry_Helpers.Wrappers.evNumber)
->E.R2.errMap(e => Reducer_ErrorValue.REDistributionError(e))
->E.R2.errMap(e => SqError.Message.REDistributionError(e))
}
let library = [
@ -31,14 +31,13 @@ let library = [
]),
],
~run=(inputs, environment, _) => {
switch FunctionRegistry_Helpers.Prepare.ToValueArray.Record.threeArgs(inputs, ("estimate", "answer", "prior")) {
switch FunctionRegistry_Helpers.Prepare.ToValueArray.Record.threeArgs(
inputs,
("estimate", "answer", "prior"),
) {
| Ok([IEvDistribution(estimate), IEvDistribution(d), IEvDistribution(prior)]) =>
runScoring(estimate, Score_Dist(d), Some(prior), environment)
| Ok([
IEvDistribution(estimate),
IEvNumber(d),
IEvDistribution(prior),
]) =>
| Ok([IEvDistribution(estimate), IEvNumber(d), IEvDistribution(prior)]) =>
runScoring(estimate, Score_Scalar(d), Some(prior), environment)
| Error(e) => Error(e->FunctionRegistry_Helpers.wrapError)
| _ => Error(FunctionRegistry_Helpers.impossibleError)
@ -50,7 +49,10 @@ let library = [
~name="logScore",
~inputs=[FRTypeRecord([("estimate", FRTypeDist), ("answer", FRTypeDistOrNumber)])],
~run=(inputs, environment, _) => {
switch FunctionRegistry_Helpers.Prepare.ToValueArray.Record.twoArgs(inputs, ("estimate", "answer")) {
switch FunctionRegistry_Helpers.Prepare.ToValueArray.Record.twoArgs(
inputs,
("estimate", "answer"),
) {
| Ok([IEvDistribution(estimate), IEvDistribution(d)]) =>
runScoring(estimate, Score_Dist(d), None, environment)
| Ok([IEvDistribution(estimate), IEvNumber(d)]) =>

View File

@ -1,7 +1,7 @@
@genType type reducerProject = ReducerProject_T.project //re-export
type reducerError = ForTS_Reducer_ErrorValue.reducerError //use
type reducerErrorValue = ForTS_Reducer_ErrorValue.reducerErrorValue //use
type error = ForTS_SqError.error //use
type errorMessage = ForTS_SqError.errorMessage //use
type squiggleValue = ForTS_SquiggleValue.squiggleValue //use
type squiggleValue_Record = ForTS_SquiggleValue.squiggleValue_Record //use
@ -99,7 +99,7 @@ To set the includes one first has to call "parseIncludes". The parsed includes o
@genType
let getIncludes = (project: reducerProject, sourceId: string): result<
array<string>,
reducerErrorValue,
errorMessage,
> => project->Private.getIncludes(sourceId)
/* Other sources contributing to the global namespace of this source. */
@ -192,7 +192,7 @@ let getBindings = (project: reducerProject, sourceId: string): squiggleValue_Rec
Get the result after running this source file or the project
*/
@genType
let getResult = (project: reducerProject, sourceId: string): result<squiggleValue, reducerError> =>
let getResult = (project: reducerProject, sourceId: string): result<squiggleValue, error> =>
project->Private.getResult(sourceId)
/*
@ -201,7 +201,7 @@ However, without a project, you cannot handle include directives.
The source has to be include free
*/
@genType
let evaluate = (sourceCode: string): (result<squiggleValue, reducerError>, squiggleValue_Record) =>
let evaluate = (sourceCode: string): (result<squiggleValue, error>, squiggleValue_Record) =>
Private.evaluate(sourceCode)
@genType

View File

@ -1,21 +0,0 @@
@genType type reducerError = Reducer_ErrorValue.error //alias
@genType type reducerErrorValue = Reducer_ErrorValue.errorValue //alias
@genType type location = Reducer_Peggy_Parse.location //alias
@genType
let toString = (e: reducerError): string => Reducer_ErrorValue.errorToString(e)
@genType
let getLocation = (e: reducerError): option<location> =>
switch e.stackTrace {
| Some(stack) => Some(stack.location)
| None => None
}
@genType
let createOtherError = (v: string): reducerError =>
Reducer_ErrorValue.REOther(v)->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue
@genType
let attachEmptyStackTraceToErrorValue = (v: reducerErrorValue): reducerError =>
Reducer_ErrorValue.attachEmptyStackTraceToErrorValue(v)

View File

@ -0,0 +1,19 @@
@genType type error = SqError.Error.t //alias
@genType type errorMessage = SqError.Message.t //alias
@genType type location = Reducer_Peggy_Parse.location //alias
@genType
let toString = (e: error): string => SqError.Error.toString(e)
@genType
let getLocation = (e: error): option<location> =>
switch e.stackTrace {
| Some(stack) => Some(stack.location)
| None => None
}
@genType
let createOtherError = (v: string): error => SqError.Message.REOther(v)->SqError.Error.fromMessage
@genType
let errorFromMessage = (v: errorMessage): error => v->SqError.Error.fromMessage

View File

@ -1,5 +1,5 @@
@genType type squiggleValue = Reducer_T.value //re-export
type reducerError = ForTS_Reducer_ErrorValue.reducerError //use
type error = ForTS_SqError.error //use
@genType type squiggleValue_Array = Reducer_T.arrayValue //re-export recursive type
@genType type squiggleValue_Record = Reducer_T.map //re-export recursive type
@ -69,7 +69,7 @@ let toString = (variant: squiggleValue) => Reducer_Value.toString(variant)
// This is a useful method for unit tests.
// Convert the result along with the error message to a string.
@genType
let toStringResult = (variantResult: result<squiggleValue, reducerError>) =>
let toStringResult = (variantResult: result<squiggleValue, error>) =>
Reducer_Value.toStringResult(variantResult)
@genType

View File

@ -1,5 +1,4 @@
@genType type reducerErrorValue = ForTS_Reducer_ErrorValue.reducerErrorValue //re-export
@genType type location = ForTS_Reducer_ErrorValue.location //re-export
@genType type location = ForTS_SqError.location //re-export
@genType type reducerProject = ForTS_ReducerProject.reducerProject //re-export
@genType type squiggleValue = ForTS_SquiggleValue.squiggleValue //re-export

View File

@ -1,5 +1,5 @@
type internalExpressionValueType = Reducer_Value.internalExpressionValueType
type errorValue = Reducer_ErrorValue.errorValue
type errorMessage = SqError.Message.t
/*
Function Registry "Type". A type, without any other information.
@ -32,7 +32,7 @@ type fnDefinition = {
array<Reducer_T.value>,
Reducer_T.environment,
Reducer_T.reducerFn,
) => result<Reducer_T.value, errorValue>,
) => result<Reducer_T.value, errorMessage>,
}
type function = {
@ -83,19 +83,17 @@ module FRType = {
| (FRTypeNumeric, IEvNumber(_)) => true
| (FRTypeNumeric, IEvDistribution(Symbolic(#Float(_)))) => true
| (FRTypeLambda, IEvLambda(_)) => true
| (FRTypeArray(intendedType), IEvArray(elements)) => {
| (FRTypeArray(intendedType), IEvArray(elements)) =>
elements->Belt.Array.every(v => matchWithValue(intendedType, v))
}
| (FRTypeDict(r), IEvRecord(map)) =>
map->Belt.Map.String.valuesToArray->Belt.Array.every(v => matchWithValue(r, v))
| (FRTypeRecord(recordParams), IEvRecord(map)) => {
| (FRTypeRecord(recordParams), IEvRecord(map)) =>
recordParams->Belt.Array.every(((name, input)) => {
switch map->Belt.Map.String.get(name) {
| Some(v) => matchWithValue(input, v)
| None => false
}
})
}
| _ => false
}
@ -104,8 +102,7 @@ module FRType = {
if !isSameLength {
false
} else {
E.A.zip(inputs, args)
->Belt.Array.every(((input, arg)) => matchWithValue(input, arg))
E.A.zip(inputs, args)->Belt.Array.every(((input, arg)) => matchWithValue(input, arg))
}
}
}
@ -230,7 +227,7 @@ module Registry = {
args: array<Reducer_T.value>,
env: Reducer_T.environment,
reducer: Reducer_T.reducerFn,
): result<Reducer_T.value, errorValue> => {
): result<Reducer_T.value, errorMessage> => {
switch Belt.Map.String.get(registry.fnNameDict, fnName) {
| Some(definitions) => {
let showNameMatchDefinitions = () => {

View File

@ -2,8 +2,8 @@ open FunctionRegistry_Core
open Reducer_T
let impossibleErrorString = "Wrong inputs / Logically impossible"
let impossibleError: errorValue = impossibleErrorString->Reducer_ErrorValue.REOther
let wrapError = e => Reducer_ErrorValue.REOther(e)
let impossibleError: errorMessage = impossibleErrorString->SqError.Message.REOther
let wrapError = e => SqError.Message.REOther(e)
module Wrappers = {
let symbolic = r => DistributionTypes.Symbolic(r)
@ -108,8 +108,10 @@ module Prepare = {
}
module Record = {
let twoDistOrNumber = (values: ts, labels: (string, string)): result<(frValueDistOrNumber, frValueDistOrNumber), err> =>
values->ToValueArray.Record.twoArgs(labels)->E.R.bind(twoDistOrNumber)
let twoDistOrNumber = (values: ts, labels: (string, string)): result<
(frValueDistOrNumber, frValueDistOrNumber),
err,
> => values->ToValueArray.Record.twoArgs(labels)->E.R.bind(twoDistOrNumber)
let twoDist = (values: ts, labels: (string, string)): result<
(DistributionTypes.genericDist, DistributionTypes.genericDist),

View File

@ -1,27 +0,0 @@
// types are disabled until review and rewrite for 0.5 interpreter compatibility
/*
module ProjectAccessorsT = ReducerProject_ProjectAccessors_T
module T = Reducer_Dispatch_T
module TypeChecker = Reducer_Type_TypeChecker
open Reducer_Value
type errorValue = Reducer_ErrorValue.errorValue
let makeFromTypes = jumpTable => {
let dispatchChainPiece: T.dispatchChainPiece = (
(fnName, fnArgs): functionCall,
accessors: ProjectAccessorsT.t,
) => {
let jumpTableEntry = jumpTable->Js.Array2.find(elem => {
let (candidName, candidType, _) = elem
candidName == fnName && TypeChecker.checkITypeArgumentsBool(candidType, fnArgs)
})
switch jumpTableEntry {
| Some((_, _, bridgeFn)) => bridgeFn(fnArgs, accessors)->Some
| _ => None
}
}
dispatchChainPiece
}
*/

View File

@ -1,21 +0,0 @@
// module ExpressionT = Reducer_Expression_T
// module ProjectAccessorsT = ReducerProject_ProjectAccessors_T
// // Each piece of the dispatch chain computes the result or returns None so that the chain can continue
// type dispatchChainPiece = (
// Reducer_Value.functionCall,
// ProjectAccessorsT.t,
// ) => option<result<Reducer_T.value, Reducer_ErrorValue.errorValue>>
// type dispatchChainPieceWithReducer = (
// Reducer_Value.functionCall,
// ProjectAccessorsT.t,
// Reducer_T.reducerFn,
// ) => option<result<Reducer_T.value, Reducer_ErrorValue.errorValue>>
// // This is a switch statement case implementation: get the arguments and compute the result
// type genericIEvFunction = (
// array<Reducer_T.value>,
// ProjectAccessorsT.t,
// ) => result<Reducer_T.value, Reducer_ErrorValue.errorValue>

View File

@ -1,131 +0,0 @@
type location = Reducer_Peggy_Parse.location
@genType.opaque
type errorValue =
| REArityError(option<string>, int, int)
| REArrayIndexNotFound(string, int)
| REAssignmentExpected
| REDistributionError(DistributionTypes.error)
| REExpectedType(string, string)
| REExpressionExpected
| REFunctionExpected(string)
| REFunctionNotFound(string)
| REJavaScriptExn(option<string>, option<string>) // Javascript Exception
| REMacroNotFound(string)
| RENotAFunction(string)
| REOperationError(Operation.operationError)
| RERecordPropertyNotFound(string, string)
| RESymbolNotFound(string)
| RESyntaxError(string, option<location>)
| RETodo(string) // To do
| REUnitNotFound(string)
| RENeedToRun
| REOther(string)
type t = errorValue
exception ErrorException(errorValue)
type rec stackTrace = {
location: location,
parent: option<stackTrace>,
}
@genType.opaque
type error = {
error: t,
stackTrace: option<stackTrace>,
}
exception ExceptionWithStackTrace(error)
let fromParseError = (
SyntaxError(message, location): Reducer_Peggy_Parse.parseError,
) => RESyntaxError(message, location->Some)
let errorValueToString = (err: errorValue) =>
switch err {
| REArityError(_oFnName, arity, usedArity) =>
`${Js.String.make(arity)} arguments expected. Instead ${Js.String.make(
usedArity,
)} argument(s) were passed.`
| REArrayIndexNotFound(msg, index) => `${msg}: ${Js.String.make(index)}`
| REAssignmentExpected => "Assignment expected"
| REExpressionExpected => "Expression expected"
| REFunctionExpected(msg) => `Function expected: ${msg}`
| REFunctionNotFound(msg) => `Function not found: ${msg}`
| REDistributionError(err) => `Distribution Math Error: ${DistributionTypes.Error.toString(err)}`
| REOperationError(err) => `Math Error: ${Operation.Error.toString(err)}`
| REJavaScriptExn(omsg, oname) => {
let answer = "JS Exception:"
let answer = switch oname {
| Some(name) => `${answer} ${name}`
| _ => answer
}
let answer = switch omsg {
| Some(msg) => `${answer}: ${msg}`
| _ => answer
}
answer
}
| REMacroNotFound(macro) => `Macro not found: ${macro}`
| RENotAFunction(valueString) => `${valueString} is not a function`
| RERecordPropertyNotFound(msg, index) => `${msg}: ${index}`
| RESymbolNotFound(symbolName) => `${symbolName} is not defined`
| RESyntaxError(desc, _) => `Syntax Error: ${desc}`
| RETodo(msg) => `TODO: ${msg}`
| REExpectedType(typeName, valueString) => `Expected type: ${typeName} but got: ${valueString}`
| REUnitNotFound(unitName) => `Unit not found: ${unitName}`
| RENeedToRun => "Need to run"
| REOther(msg) => `Error: ${msg}`
}
let fromException = exn =>
switch exn {
| ErrorException(e) => e
| Js.Exn.Error(e) =>
switch Js.Exn.message(e) {
| Some(message) => REOther(message)
| None =>
switch Js.Exn.name(e) {
| Some(name) => REOther(name)
| None => REOther("Unknown error")
}
}
| _e => REOther("Unknown error")
}
let rec stackTraceToString = ({location, parent}: stackTrace) => {
` Line ${location.start.line->Js.Int.toString}, column ${location.start.column->Js.Int.toString}, source ${location.source}\n` ++
switch parent {
| Some(parent) => stackTraceToString(parent)
| None => ""
}
}
let errorToString = (err: error) =>
switch err.stackTrace {
| Some(stack) => "Traceback:\n" ++ stack->stackTraceToString
| None => ""
} ++
err.error->errorValueToString
let toException = (errorValue: t) => errorValue->ErrorException->raise
let attachEmptyStackTraceToErrorValue = (errorValue: t) => {
error: errorValue,
stackTrace: None,
}
let attachLocationToErrorValue = (errorValue: t, location: location): error => {
error: errorValue,
stackTrace: Some({location: location, parent: None}),
}
let raiseNewExceptionWithStackTrace = (errorValue: t, location: location) =>
errorValue->attachLocationToErrorValue(location)->ExceptionWithStackTrace->raise
let raiseExtendedExceptionWithStackTrace = ({error, stackTrace}: error, location: location) =>
{error: error, stackTrace: Some({location: location, parent: stackTrace})}
->ExceptionWithStackTrace
->raise

View File

@ -3,14 +3,12 @@ module Lambda = Reducer_Expression_Lambda
module Result = Belt.Result
module T = Reducer_T
type errorValue = Reducer_ErrorValue.errorValue
let toLocation = (expression: T.expression): Reducer_ErrorValue.location => {
let toLocation = (expression: T.expression): SqError.location => {
expression.ast.location
}
let throwFrom = (error: errorValue, expression: T.expression) =>
error->Reducer_ErrorValue.raiseNewExceptionWithStackTrace(expression->toLocation)
let throwFrom = (error: SqError.Message.t, expression: T.expression) =>
error->SqError.Error.fromMessageWithLocation(expression->toLocation)->SqError.Error.throw
/*
Recursively evaluate the expression
@ -110,11 +108,11 @@ let rec evaluate: T.reducerFn = (expression, context): (T.value, T.context) => {
let result = Lambda.doLambdaCall(lambda, argValues, context.environment, evaluate)
(result, context)
} catch {
| Reducer_ErrorValue.ErrorException(e) => e->throwFrom(expression) // function implementation returned an error without location
| Reducer_ErrorValue.ExceptionWithStackTrace(e) =>
Reducer_ErrorValue.raiseExtendedExceptionWithStackTrace(e, expression->toLocation) // function implementation probably called a lambda that threw an exception
| Js.Exn.Error(obj) =>
REJavaScriptExn(obj->Js.Exn.message, obj->Js.Exn.name)->throwFrom(expression)
| exn =>
exn
->SqError.Error.fromException
->SqError.Error.extend(expression->toLocation)
->SqError.Error.throw
}
| _ => RENotAFunction(lambda->Reducer_Value.toString)->throwFrom(expression)
}
@ -128,24 +126,18 @@ module BackCompatible = {
let parse = (peggyCode: string): result<T.expression, Reducer_Peggy_Parse.parseError> =>
peggyCode->Reducer_Peggy_Parse.parse("main")->Result.map(Reducer_Peggy_ToExpression.fromNode)
let evaluate = (expression: T.expression): result<T.value, Reducer_ErrorValue.error> => {
let evaluate = (expression: T.expression): result<T.value, SqError.Error.t> => {
let context = Reducer_Context.createDefaultContext()
try {
let (value, _) = expression->evaluate(context)
value->Ok
} catch {
| exn =>
exn
->Reducer_ErrorValue.fromException
->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue
->Error // TODO - this could be done better (see ReducerProject)
| exn => exn->SqError.Error.fromException->Error
}
}
let evaluateString = (peggyCode: string): result<T.value, Reducer_ErrorValue.error> =>
let evaluateString = (peggyCode: string): result<T.value, SqError.Error.t> =>
parse(peggyCode)
->E.R2.errMap(e =>
e->Reducer_ErrorValue.fromParseError->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue
)
->E.R2.errMap(e => e->SqError.Message.fromParseError->SqError.Error.fromMessage)
->Result.flatMap(evaluate)
}

View File

@ -1,7 +1,5 @@
module BErrorValue = Reducer_ErrorValue
module T = Reducer_T
type errorValue = BErrorValue.errorValue
type expression = Reducer_T.expression
type expressionContent = Reducer_T.expressionContent

View File

@ -1,5 +1,3 @@
module ErrorValue = Reducer_ErrorValue
let doLambdaCall = (
lambdaValue: Reducer_T.lambdaValue,
args,
@ -28,7 +26,7 @@ let makeLambda = (
let argsLength = arguments->Js.Array2.length
let parametersLength = parameters->Js.Array2.length
if argsLength !== parametersLength {
ErrorValue.REArityError(None, parametersLength, argsLength)->ErrorValue.ErrorException->raise
SqError.Message.REArityError(None, parametersLength, argsLength)->SqError.Message.toException
}
let localBindings = bindings->Reducer_Bindings.extend

View File

@ -1,7 +1,3 @@
// deprecated, use Reducer_T instead
// (value methods should be moved to Reducer_Value.res)
module ErrorValue = Reducer_ErrorValue
type environment = GenericDist.env
module T = Reducer_T
@ -76,13 +72,13 @@ let toStringFunctionCall = ((fn, args)): string => `${fn}(${argsToString(args)})
let toStringResult = x =>
switch x {
| Ok(a) => `Ok(${toString(a)})`
| Error(m) => `Error(${ErrorValue.errorToString(m)})`
| Error(m) => `Error(${SqError.Error.toString(m)})`
}
let toStringResultOkless = (codeResult: result<t, ErrorValue.error>): string =>
let toStringResultOkless = (codeResult: result<t, SqError.Error.t>): string =>
switch codeResult {
| Ok(a) => toString(a)
| Error(m) => `Error(${ErrorValue.errorToString(m)})`
| Error(m) => `Error(${SqError.Error.toString(m)})`
}
type internalExpressionValueType =
@ -144,10 +140,10 @@ let functionCallSignatureToString = (functionCallSignature: functionCallSignatur
let arrayToValueArray = (arr: array<t>): array<t> => arr
let resultToValue = (rExpression: result<t, Reducer_ErrorValue.t>): t =>
let resultToValue = (rExpression: result<t, SqError.Message.t>): t =>
switch rExpression {
| Ok(expression) => expression
| Error(errorValue) => Reducer_ErrorValue.toException(errorValue)
| Error(errorValue) => SqError.Message.toException(errorValue)
}
let recordToKeyValuePairs = (record: T.map): array<(string, t)> => record->Belt.Map.String.toArray

View File

@ -1,7 +1,6 @@
// TODO: Auto clean project based on topology
module Bindings = Reducer_Bindings
module ErrorValue = Reducer_ErrorValue
module ProjectItem = ReducerProject_ProjectItem
module T = ReducerProject_T
module Topology = ReducerProject_Topology
@ -117,7 +116,7 @@ let getResultOption = (project: t, sourceId: string): ProjectItem.T.resultType =
let getResult = (project: t, sourceId: string): ProjectItem.T.resultArgumentType =>
switch getResultOption(project, sourceId) {
| None => RENeedToRun->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue->Error
| None => RENeedToRun->SqError.Error.fromMessage->Error
| Some(result) => result
}
@ -171,7 +170,7 @@ let linkDependencies = (project: t, sourceId: string): Reducer_T.namespace => {
"__result__",
switch project->getResult(id) {
| Ok(result) => result
| Error(error) => error->Reducer_ErrorValue.ExceptionWithStackTrace->raise
| Error(error) => error->SqError.Error.throw
},
),
])

View File

@ -1,10 +1,7 @@
@module("./ReducerProject_IncludeParser.js")
external parse__: string => array<array<string>> = "parse"
let parseIncludes = (expr: string): result<
array<(string, string)>,
Reducer_ErrorValue.errorValue,
> =>
let parseIncludes = (expr: string): result<array<(string, string)>, SqError.Message.t> =>
try {
let answer = parse__(expr)
// let logEntry = answer->Js.Array2.joinWith(",")

View File

@ -155,7 +155,7 @@ let doRawParse = (this: t): T.rawParseArgumentType =>
this
->getSource
->Reducer_Peggy_Parse.parse(this.sourceId)
->E.R2.errMap(Reducer_ErrorValue.fromParseError)
->E.R2.errMap(SqError.Message.fromParseError)
let rawParse = (this: t): t =>
this->getRawParse->E.O2.defaultFn(() => doRawParse(this))->setRawParse(this, _)
@ -174,7 +174,7 @@ let buildExpression = (this: t): t => {
}
}
let failRun = (this: t, e: Reducer_ErrorValue.error): t =>
let failRun = (this: t, e: SqError.Error.t): t =>
this->setResult(e->Error)->setContinuation(Reducer_Namespace.make())
let doRun = (this: t, context: Reducer_T.context): t =>
@ -188,24 +188,11 @@ let doRun = (this: t, context: Reducer_T.context): t =>
->setResult(result->Ok)
->setContinuation(contextAfterEvaluation.bindings->Reducer_Bindings.locals)
} catch {
| Reducer_ErrorValue.ErrorException(e) =>
this->failRun(e->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue)
| Reducer_ErrorValue.ExceptionWithStackTrace(e) => this->failRun(e)
| _ =>
this->failRun(
RETodo(
"unhandled rescript exception",
)->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue,
)
| e => this->failRun(e->SqError.Error.fromException)
}
| Error(e) => this->failRun(e->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue)
| Error(e) => this->failRun(e->SqError.Error.fromMessage)
}
| None =>
this->failRun(
RETodo(
"attempt to run without expression",
)->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue,
)
| None => this->failRun(RETodo("attempt to run without expression")->SqError.Error.fromMessage)
}
let run = (this: t, context: Reducer_T.context): t => {

View File

@ -1,22 +1,21 @@
module Parse = Reducer_Peggy_Parse
module ExpressionT = Reducer_Expression_T
open Reducer_ErrorValue
type sourceArgumentType = string
type sourceType = string
type rawParseArgumentType = result<Parse.node, errorValue>
type rawParseArgumentType = result<Parse.node, SqError.Message.t>
type rawParseType = option<rawParseArgumentType>
type expressionArgumentType = result<ExpressionT.t, errorValue>
type expressionArgumentType = result<ExpressionT.t, SqError.Message.t>
type expressionType = option<expressionArgumentType>
type continuationArgumentType = Reducer_T.namespace
type continuationType = option<continuationArgumentType>
type continuationResultType = option<result<continuationArgumentType, errorValue>>
type resultArgumentType = result<Reducer_T.value, error>
type continuationResultType = option<result<continuationArgumentType, SqError.Message.t>>
type resultArgumentType = result<Reducer_T.value, SqError.Error.t>
type resultType = option<resultArgumentType>
type continuesArgumentType = array<string>
type continuesType = array<string>
type includesArgumentType = string
type includesType = result<array<string>, errorValue>
type includesType = result<array<string>, SqError.Message.t>
type importAsVariablesType = array<(string, string)>
type projectItem = {

View File

@ -0,0 +1,145 @@
type location = Reducer_Peggy_Parse.location
module Message = {
@genType.opaque
type t =
| REArityError(option<string>, int, int)
| REArrayIndexNotFound(string, int)
| REAssignmentExpected
| REDistributionError(DistributionTypes.error)
| REExpectedType(string, string)
| REExpressionExpected
| REFunctionExpected(string)
| REFunctionNotFound(string)
| REJavaScriptExn(option<string>, option<string>) // Javascript Exception
| REMacroNotFound(string)
| RENotAFunction(string)
| REOperationError(Operation.operationError)
| RERecordPropertyNotFound(string, string)
| RESymbolNotFound(string)
| RESyntaxError(string, option<location>)
| RETodo(string) // To do
| REUnitNotFound(string)
| RENeedToRun
| REOther(string)
exception MessageException(t)
let fromParseError = (
SyntaxError(message, location): Reducer_Peggy_Parse.parseError,
) => RESyntaxError(message, location->Some)
let toString = (err: t) =>
switch err {
| REArityError(_oFnName, arity, usedArity) =>
`${Js.String.make(arity)} arguments expected. Instead ${Js.String.make(
usedArity,
)} argument(s) were passed.`
| REArrayIndexNotFound(msg, index) => `${msg}: ${Js.String.make(index)}`
| REAssignmentExpected => "Assignment expected"
| REExpressionExpected => "Expression expected"
| REFunctionExpected(msg) => `Function expected: ${msg}`
| REFunctionNotFound(msg) => `Function not found: ${msg}`
| REDistributionError(err) =>
`Distribution Math Error: ${DistributionTypes.Error.toString(err)}`
| REOperationError(err) => `Math Error: ${Operation.Error.toString(err)}`
| REJavaScriptExn(omsg, oname) => {
let answer = "JS Exception:"
let answer = switch oname {
| Some(name) => `${answer} ${name}`
| _ => answer
}
let answer = switch omsg {
| Some(msg) => `${answer}: ${msg}`
| _ => answer
}
answer
}
| REMacroNotFound(macro) => `Macro not found: ${macro}`
| RENotAFunction(valueString) => `${valueString} is not a function`
| RERecordPropertyNotFound(msg, index) => `${msg}: ${index}`
| RESymbolNotFound(symbolName) => `${symbolName} is not defined`
| RESyntaxError(desc, _) => `Syntax Error: ${desc}`
| RETodo(msg) => `TODO: ${msg}`
| REExpectedType(typeName, valueString) => `Expected type: ${typeName} but got: ${valueString}`
| REUnitNotFound(unitName) => `Unit not found: ${unitName}`
| RENeedToRun => "Need to run"
| REOther(msg) => `Error: ${msg}`
}
let fromException = exn =>
switch exn {
| MessageException(e) => e
| Js.Exn.Error(e) =>
switch Js.Exn.message(e) {
| Some(message) => REOther(message)
| None =>
switch Js.Exn.name(e) {
| Some(name) => REOther(name)
| None => REOther("Unknown error")
}
}
| _e => REOther("Unknown error")
}
let toException = (errorValue: t) => errorValue->MessageException->raise
}
module StackTrace = {
type rec t = {
location: location,
parent: option<t>,
}
let rec toString = ({location, parent}: t) => {
` Line ${location.start.line->Js.Int.toString}, column ${location.start.column->Js.Int.toString}, source ${location.source}\n` ++
switch parent {
| Some(parent) => toString(parent)
| None => ""
}
}
}
module Error = {
@genType.opaque
type t = {
message: Message.t,
stackTrace: option<StackTrace.t>,
}
exception SqException(t)
let toString = (err: t) => err.message->Message.toString
let toStringWithStackTrace = (err: t) =>
switch err.stackTrace {
| Some(stack) => "Traceback:\n" ++ stack->StackTrace.toString
| None => ""
} ++
err->toString
let fromMessage = (errorMessage: Message.t) => {
message: errorMessage,
stackTrace: None,
}
let fromMessageWithLocation = (errorMessage: Message.t, location: location): t => {
message: errorMessage,
stackTrace: Some({location: location, parent: None}),
}
let extend = ({message, stackTrace}: t, location: location) => {
message: message,
stackTrace: Some({location: location, parent: stackTrace}),
}
let throw = (t: t) => t->SqException->raise
let fromException = exn =>
switch exn {
| SqException(e) => e
| Message.MessageException(e) => e->fromMessage
| Js.Exn.Error(obj) => REJavaScriptExn(obj->Js.Exn.message, obj->Js.Exn.name)->fromMessage
| _ => REOther("Unknown exception")->fromMessage
}
}

View File

@ -1,4 +1,4 @@
exception ErrorException = Reducer_ErrorValue.ErrorException
let throwMessage = SqError.Message.toException
let stdLib: Reducer_T.namespace = {
// constants
@ -17,16 +17,15 @@ let stdLib: Reducer_T.namespace = {
switch Belt.Array.get(aValueArray, index) {
| Some(value) => value
| None => REArrayIndexNotFound("Array index not found", index)->ErrorException->raise
| None => REArrayIndexNotFound("Array index not found", index)->throwMessage
}
}
| [IEvRecord(dict), IEvString(sIndex)] =>
switch Belt.Map.String.get(dict, sIndex) {
| Some(value) => value
| None =>
RERecordPropertyNotFound("Record property not found", sIndex)->ErrorException->raise
| None => RERecordPropertyNotFound("Record property not found", sIndex)->throwMessage
}
| _ => REOther("Trying to access key on wrong value")->ErrorException->raise
| _ => REOther("Trying to access key on wrong value")->throwMessage
}
})->Reducer_T.IEvLambda,
)
@ -49,7 +48,7 @@ let stdLib: Reducer_T.namespace = {
Reducer_Expression_Lambda.makeFFILambda((arguments, environment, reducer) => {
switch FunctionRegistry_Library.call(name, arguments, environment, reducer) {
| Ok(value) => value
| Error(error) => error->Reducer_ErrorValue.ErrorException->raise
| Error(error) => error->SqError.Message.toException
}
})->Reducer_T.IEvLambda,
)