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 { } else {
let a2 = let a2 =
rExpr rExpr
->E.R2.errMap(e => ->E.R2.errMap(e => e->SqError.Message.fromParseError->SqError.Error.fromMessage)
e->Reducer_ErrorValue.fromParseError->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue
)
->Result.flatMap(expr => Expression.BackCompatible.evaluate(expr)) ->Result.flatMap(expr => Expression.BackCompatible.evaluate(expr))
->Reducer_Value.toStringResultOkless ->Reducer_Value.toStringResultOkless
(a1, a2)->expect->toEqual((answer, v)) (a1, a2)->expect->toEqual((answer, v))

View File

@ -1,4 +1,3 @@
module ErrorValue = Reducer_ErrorValue
module Expression = Reducer_Expression module Expression = Reducer_Expression
module ExpressionT = Reducer_Expression_T module ExpressionT = Reducer_Expression_T
@ -9,7 +8,7 @@ let unwrapRecord = rValue =>
rValue->Belt.Result.flatMap(value => rValue->Belt.Result.flatMap(value =>
switch value { switch value {
| Reducer_T.IEvRecord(aRecord) => Ok(aRecord) | 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( testDescriptionEvalToBe(
"javascript exception", "javascript exception",
"javascriptraise('div by 0')", "javascriptraise('div by 0')",
"Error(Error: 'div by 0')", "Error(JS Exception: Error: 'div by 0')",
) )
// testDescriptionEvalToBe( // testDescriptionEvalToBe(
// "rescript exception", // "rescript exception",

View File

@ -25,7 +25,7 @@ x=1`,
let mainIncludes = Project.getIncludes(project, "main") let mainIncludes = Project.getIncludes(project, "main")
switch mainIncludes { switch mainIncludes {
| Ok(includes) => expect(includes) == ["common"] | Ok(includes) => expect(includes) == ["common"]
| Error(error) => fail(error->Reducer_ErrorValue.errorValueToString) | Error(error) => fail(error->SqError.Message.toString)
} }
}) })
test("past chain", () => { test("past chain", () => {
@ -60,7 +60,7 @@ x=1`,
let mainIncludes = Project.getIncludes(project, "main") let mainIncludes = Project.getIncludes(project, "main")
switch mainIncludes { switch mainIncludes {
| Ok(includes) => expect(includes) == ["common", "myModule"] | 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") let mainIncludes = Project.getIncludes(project, "main")
switch mainIncludes { switch mainIncludes {
| Ok(includes) => expect(includes) == ["common", "common2", "myModule"] | 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", () => { 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 */ /* Parse includes has set the includes */
switch project->Project.getIncludes("main") { switch project->Project.getIncludes("main") {
| Ok(includes) => includes->expect == ["common"] | 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. /* If the includes cannot be parsed then you get a syntax error.
Otherwise you get the includes. 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) let rIncludes = project->Project.getIncludes(sourceName)
switch rIncludes { switch rIncludes {
/* Maybe there is an include syntax error */ /* 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) => | Ok(includes) =>
includes->Belt.Array.forEach(newIncludeName => { includes->Belt.Array.forEach(newIncludeName => {
@ -169,7 +169,7 @@ Here we will finally proceed to a real life scenario. */
test("getIncludes", () => { test("getIncludes", () => {
switch Project.getIncludes(project, "main") { switch Project.getIncludes(project, "main") {
| Ok(includes) => includes->expect == ["common"] | 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 { export class SqError {
constructor(private _value: RSErrorValue.reducerError) {} constructor(private _value: RSError.error) {}
toString() { toString() {
return RSErrorValue.toString(this._value); return RSError.toString(this._value);
} }
static createOtherError(v: string) { 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 * as RSProject from "../rescript/ForTS/ForTS_ReducerProject.gen";
import { import * as RSError from "../rescript/ForTS/ForTS_SqError.gen";
reducerError,
reducerErrorValue,
attachEmptyStackTraceToErrorValue,
} from "../rescript/ForTS/ForTS_Reducer_ErrorValue.gen";
import { environment } from "../rescript/ForTS/ForTS_Distribution/ForTS_Distribution_Environment.gen"; import { environment } from "../rescript/ForTS/ForTS_Distribution/ForTS_Distribution_Environment.gen";
import { SqError } from "./SqError"; import { SqError } from "./SqError";
import { SqRecord } from "./SqRecord"; import { SqRecord } from "./SqRecord";
import { wrapValue } from "./SqValue"; import { wrapValue } from "./SqValue";
import { resultMap2 } from "./types"; import { resultMap2 } from "./types";
import { SqValueLocation } from "./SqValueLocation"; import { SqValueLocation } from "./SqValueLocation";
import { errorFromMessage } from "../rescript/ForTS/ForTS_SqError.gen";
export class SqProject { export class SqProject {
constructor(private _value: RSProject.reducerProject) {} constructor(private _value: RSProject.reducerProject) {}
@ -54,8 +51,7 @@ export class SqProject {
return resultMap2( return resultMap2(
RSProject.getIncludes(this._value, sourceId), RSProject.getIncludes(this._value, sourceId),
(a) => a, (a) => a,
(v: reducerErrorValue) => (v: RSError.errorMessage) => new SqError(errorFromMessage(v))
new SqError(attachEmptyStackTraceToErrorValue(v))
); );
} }
@ -109,7 +105,7 @@ export class SqProject {
items: [], 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 = { type simpleDefinition = {
inputs: array<frType>, 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>) => let makeFnMany = (name: string, definitions: array<simpleDefinition>) =>
@ -22,7 +22,7 @@ let makeFnMany = (name: string, definitions: array<simpleDefinition>) =>
let makeFn = ( let makeFn = (
name: string, name: string,
inputs: array<frType>, 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}]) ) => makeFnMany(name, [{inputs: inputs, fn: fn}])
let library = [ let library = [

View File

@ -77,7 +77,7 @@ module Integration = {
| Reducer_T.IEvNumber(x) => Ok(x) | Reducer_T.IEvNumber(x) => Ok(x)
| _ => | _ =>
Error( 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 result
@ -143,8 +143,8 @@ module Integration = {
| Error(b) => | 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." ++ ("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: " ++ "Original error: " ++
b->Reducer_ErrorValue.errorValueToString) b->SqError.Message.toString)
->Reducer_ErrorValue.REOther ->SqError.Message.REOther
->Error ->Error
} }
result result
@ -169,7 +169,7 @@ module Integration = {
let result = switch inputs { let result = switch inputs {
| [_, _, _, IEvNumber(0.0)] => | [_, _, _, IEvNumber(0.0)] =>
"Integration error 4 in Danger.integrate: Increment can't be 0." "Integration error 4 in Danger.integrate: Increment can't be 0."
->Reducer_ErrorValue.REOther ->SqError.Message.REOther
->Error ->Error
| [ | [
IEvLambda(aLambda), IEvLambda(aLambda),
@ -187,7 +187,7 @@ module Integration = {
) )
| _ => | _ =>
Error( Error(
Reducer_ErrorValue.REOther( SqError.Message.REOther(
"Integration error 5 in Danger.integrate. Remember that inputs are (function, number (min), number (max), number(increment))", "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 { let result = switch inputs {
| [_, _, _, IEvNumber(0.0)] => | [_, _, _, IEvNumber(0.0)] =>
"Integration error in Danger.integrate: Increment can't be 0." "Integration error in Danger.integrate: Increment can't be 0."
->Reducer_ErrorValue.REOther ->SqError.Message.REOther
->Error ->Error
| [IEvLambda(aLambda), IEvNumber(min), IEvNumber(max), IEvNumber(epsilon)] => | [IEvLambda(aLambda), IEvNumber(min), IEvNumber(max), IEvNumber(epsilon)] =>
Helpers.integrateFunctionBetweenWithNumIntegrationPoints( Helpers.integrateFunctionBetweenWithNumIntegrationPoints(
@ -225,11 +225,11 @@ module Integration = {
reducer, reducer,
)->E.R2.errMap(b => )->E.R2.errMap(b =>
("Integration error 7 in Danger.integrate. Something went wrong along the way: " ++ ("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))" "Integration error 8 in Danger.integrate. Remember that inputs are (function, number (min), number (max), number(increment))"
->Reducer_ErrorValue.REOther ->SqError.Message.REOther
->Error ->Error
} }
result result
@ -246,7 +246,7 @@ module DiminishingReturns = {
module Helpers = { module Helpers = {
type diminishingReturnsAccumulatorInner = { type diminishingReturnsAccumulatorInner = {
optimalAllocations: array<float>, optimalAllocations: array<float>,
currentMarginalReturns: result<array<float>, errorValue>, currentMarginalReturns: result<array<float>, errorMessage>,
} }
let findBiggestElementIndex = (xs: array<float>) => let findBiggestElementIndex = (xs: array<float>) =>
E.A.reducei(xs, 0, (acc, newElement, index) => { E.A.reducei(xs, 0, (acc, newElement, index) => {
@ -255,7 +255,7 @@ module DiminishingReturns = {
| false => acc | 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. // 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 The key idea for this function is that
@ -290,19 +290,19 @@ module DiminishingReturns = {
) { ) {
| (false, _, _, _) => | (false, _, _, _) =>
Error( 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, _, _) => | (_, false, _, _) =>
Error( 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, _) => | (_, _, false, _) =>
Error( 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) => | (_, _, _, false) =>
Error( 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) => { | (true, true, true, true) => {
let applyFunctionAtPoint = (lambda, point: float) => { let applyFunctionAtPoint = (lambda, point: float) => {
@ -318,7 +318,7 @@ module DiminishingReturns = {
| Reducer_T.IEvNumber(x) => Ok(x) | Reducer_T.IEvNumber(x) => Ok(x)
| _ => | _ =>
Error( 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) | Reducer_T.IEvLambda(lambda) => Ok(lambda)
| _ => | _ =>
"Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions. A member of the array wasn't a function" "Error in Danger.optimalAllocationGivenDiminishingMarginalReturnsForManyFunctions. A member of the array wasn't a function"
->Reducer_ErrorValue.REOther ->SqError.Message.REOther
->Error ->Error
} }
}, innerlambdas) }, innerlambdas)
@ -433,7 +433,7 @@ module DiminishingReturns = {
} }
| _ => | _ =>
"Error in Danger.diminishingMarginalReturnsForTwoFunctions" "Error in Danger.diminishingMarginalReturnsForTwoFunctions"
->Reducer_ErrorValue.REOther ->SqError.Message.REOther
->Error ->Error
}, },
(), (),

View File

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

View File

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

View File

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

View File

@ -296,7 +296,7 @@ module Old = {
let genericOutputToReducerValue = (o: DistributionOperation.outputType): result< let genericOutputToReducerValue = (o: DistributionOperation.outputType): result<
Reducer_T.value, Reducer_T.value,
Reducer_ErrorValue.errorValue, SqError.Message.t,
> => > =>
switch o { switch o {
| Dist(d) => Ok(Reducer_T.IEvDistribution(d)) | Dist(d) => Ok(Reducer_T.IEvDistribution(d))
@ -311,9 +311,9 @@ module Old = {
switch dispatchToGenericOutput(call, environment) { switch dispatchToGenericOutput(call, environment) {
| Some(o) => genericOutputToReducerValue(o) | Some(o) => genericOutputToReducerValue(o)
| None => | None =>
Reducer_ErrorValue.REOther("Internal error in FR_GenericDist implementation") SqError.Message.REOther(
->Reducer_ErrorValue.ErrorException "Internal error in FR_GenericDist implementation",
->raise )->SqError.Message.toException
} }
} }
@ -405,6 +405,6 @@ let library = E.A.concatMany([
let mxLambda = Reducer_Expression_Lambda.makeFFILambda((inputs, env, _) => { let mxLambda = Reducer_Expression_Lambda.makeFFILambda((inputs, env, _) => {
switch Old.dispatch(("mx", inputs), env) { switch Old.dispatch(("mx", inputs), env) {
| Ok(value) => value | 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) => { let inputsToDist = (inputs: array<Reducer_T.value>, xyShapeToPointSetDist) => {
// TODO - rewrite in more functional/functor-based style // TODO - rewrite in more functional/functor-based style
switch inputs { switch inputs {
| [IEvArray(items)] => { | [IEvArray(items)] =>
items->Belt.Array.map( items
item => ->Belt.Array.map(item =>
switch item { switch item {
| IEvRecord(map) => { | IEvRecord(map) => {
let xValue = map->Belt.Map.String.get("x") let xValue = map->Belt.Map.String.get("x")
let yValue = map->Belt.Map.String.get("y") let yValue = map->Belt.Map.String.get("y")
switch (xValue, yValue) { switch (xValue, yValue) {
| (Some(IEvNumber(x)), Some(IEvNumber(y))) => (x, y) | (Some(IEvNumber(x)), Some(IEvNumber(y))) => (x, y)
| _ => impossibleError->Reducer_ErrorValue.toException | _ => impossibleError->SqError.Message.toException
}
} }
| _ => impossibleError->Reducer_ErrorValue.toException
} }
)->Ok->E.R.bind(r => r->XYShape.T.makeFromZipped->E.R2.errMap(XYShape.Error.toString)) | _ => impossibleError->SqError.Message.toException
->E.R2.fmap(r => Reducer_T.IEvDistribution(PointSet(r->xyShapeToPointSetDist))) }
} )
| _ => impossibleError->Reducer_ErrorValue.toException ->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->SqError.Message.toException
} }
} }
module Internal = { module Internal = {
type t = PointSetDist.t 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 { switch r {
| Ok(r) => Ok(Wrappers.evDistribution(PointSet(r))) | Ok(r) => Ok(Wrappers.evDistribution(PointSet(r)))
| Error(err) => Error(REOperationError(err)) | Error(err) => Error(REOperationError(err))
@ -71,7 +72,7 @@ let library = [
) )
->E.R2.fmap(Wrappers.pointSet) ->E.R2.fmap(Wrappers.pointSet)
->E.R2.fmap(Wrappers.evDistribution) ->E.R2.fmap(Wrappers.evDistribution)
->E.R2.errMap(e => Reducer_ErrorValue.REDistributionError(e)) ->E.R2.errMap(e => SqError.Message.REDistributionError(e))
| _ => Error(impossibleError) | _ => Error(impossibleError)
}, },
(), (),

View File

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

View File

@ -6,7 +6,7 @@ let requiresNamespace = true
let runScoring = (estimate, answer, prior, env) => { let runScoring = (estimate, answer, prior, env) => {
GenericDist.Score.logScore(~estimate, ~answer, ~prior, ~env) GenericDist.Score.logScore(~estimate, ~answer, ~prior, ~env)
->E.R2.fmap(FunctionRegistry_Helpers.Wrappers.evNumber) ->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 = [ let library = [
@ -31,14 +31,13 @@ let library = [
]), ]),
], ],
~run=(inputs, environment, _) => { ~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)]) => | Ok([IEvDistribution(estimate), IEvDistribution(d), IEvDistribution(prior)]) =>
runScoring(estimate, Score_Dist(d), Some(prior), environment) runScoring(estimate, Score_Dist(d), Some(prior), environment)
| Ok([ | Ok([IEvDistribution(estimate), IEvNumber(d), IEvDistribution(prior)]) =>
IEvDistribution(estimate),
IEvNumber(d),
IEvDistribution(prior),
]) =>
runScoring(estimate, Score_Scalar(d), Some(prior), environment) runScoring(estimate, Score_Scalar(d), Some(prior), environment)
| Error(e) => Error(e->FunctionRegistry_Helpers.wrapError) | Error(e) => Error(e->FunctionRegistry_Helpers.wrapError)
| _ => Error(FunctionRegistry_Helpers.impossibleError) | _ => Error(FunctionRegistry_Helpers.impossibleError)
@ -50,7 +49,10 @@ let library = [
~name="logScore", ~name="logScore",
~inputs=[FRTypeRecord([("estimate", FRTypeDist), ("answer", FRTypeDistOrNumber)])], ~inputs=[FRTypeRecord([("estimate", FRTypeDist), ("answer", FRTypeDistOrNumber)])],
~run=(inputs, environment, _) => { ~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)]) => | Ok([IEvDistribution(estimate), IEvDistribution(d)]) =>
runScoring(estimate, Score_Dist(d), None, environment) runScoring(estimate, Score_Dist(d), None, environment)
| Ok([IEvDistribution(estimate), IEvNumber(d)]) => | Ok([IEvDistribution(estimate), IEvNumber(d)]) =>

View File

@ -1,7 +1,7 @@
@genType type reducerProject = ReducerProject_T.project //re-export @genType type reducerProject = ReducerProject_T.project //re-export
type reducerError = ForTS_Reducer_ErrorValue.reducerError //use type error = ForTS_SqError.error //use
type reducerErrorValue = ForTS_Reducer_ErrorValue.reducerErrorValue //use type errorMessage = ForTS_SqError.errorMessage //use
type squiggleValue = ForTS_SquiggleValue.squiggleValue //use type squiggleValue = ForTS_SquiggleValue.squiggleValue //use
type squiggleValue_Record = ForTS_SquiggleValue.squiggleValue_Record //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 @genType
let getIncludes = (project: reducerProject, sourceId: string): result< let getIncludes = (project: reducerProject, sourceId: string): result<
array<string>, array<string>,
reducerErrorValue, errorMessage,
> => project->Private.getIncludes(sourceId) > => project->Private.getIncludes(sourceId)
/* Other sources contributing to the global namespace of this source. */ /* 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 Get the result after running this source file or the project
*/ */
@genType @genType
let getResult = (project: reducerProject, sourceId: string): result<squiggleValue, reducerError> => let getResult = (project: reducerProject, sourceId: string): result<squiggleValue, error> =>
project->Private.getResult(sourceId) project->Private.getResult(sourceId)
/* /*
@ -201,7 +201,7 @@ However, without a project, you cannot handle include directives.
The source has to be include free The source has to be include free
*/ */
@genType @genType
let evaluate = (sourceCode: string): (result<squiggleValue, reducerError>, squiggleValue_Record) => let evaluate = (sourceCode: string): (result<squiggleValue, error>, squiggleValue_Record) =>
Private.evaluate(sourceCode) Private.evaluate(sourceCode)
@genType @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 @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_Array = Reducer_T.arrayValue //re-export recursive type
@genType type squiggleValue_Record = Reducer_T.map //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. // This is a useful method for unit tests.
// Convert the result along with the error message to a string. // Convert the result along with the error message to a string.
@genType @genType
let toStringResult = (variantResult: result<squiggleValue, reducerError>) => let toStringResult = (variantResult: result<squiggleValue, error>) =>
Reducer_Value.toStringResult(variantResult) Reducer_Value.toStringResult(variantResult)
@genType @genType

View File

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

View File

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

View File

@ -2,8 +2,8 @@ open FunctionRegistry_Core
open Reducer_T open Reducer_T
let impossibleErrorString = "Wrong inputs / Logically impossible" let impossibleErrorString = "Wrong inputs / Logically impossible"
let impossibleError: errorValue = impossibleErrorString->Reducer_ErrorValue.REOther let impossibleError: errorMessage = impossibleErrorString->SqError.Message.REOther
let wrapError = e => Reducer_ErrorValue.REOther(e) let wrapError = e => SqError.Message.REOther(e)
module Wrappers = { module Wrappers = {
let symbolic = r => DistributionTypes.Symbolic(r) let symbolic = r => DistributionTypes.Symbolic(r)
@ -30,21 +30,21 @@ module Prepare = {
let twoArgs = (inputs: ts, (arg1: string, arg2: string)): result<ts, err> => let twoArgs = (inputs: ts, (arg1: string, arg2: string)): result<ts, err> =>
switch inputs { switch inputs {
| [IEvRecord(map)] => { | [IEvRecord(map)] => {
let n1 = map->Belt.Map.String.getExn(arg1) let n1 = map->Belt.Map.String.getExn(arg1)
let n2 = map->Belt.Map.String.getExn(arg2) let n2 = map->Belt.Map.String.getExn(arg2)
Ok([n1, n2]) Ok([n1, n2])
} }
| _ => Error(impossibleErrorString) | _ => Error(impossibleErrorString)
} }
let threeArgs = (inputs: ts, (arg1: string, arg2: string, arg3: string)): result<ts, err> => let threeArgs = (inputs: ts, (arg1: string, arg2: string, arg3: string)): result<ts, err> =>
switch inputs { switch inputs {
| [IEvRecord(map)] => { | [IEvRecord(map)] => {
let n1 = map->Belt.Map.String.getExn(arg1) let n1 = map->Belt.Map.String.getExn(arg1)
let n2 = map->Belt.Map.String.getExn(arg2) let n2 = map->Belt.Map.String.getExn(arg2)
let n3 = map->Belt.Map.String.getExn(arg3) let n3 = map->Belt.Map.String.getExn(arg3)
Ok([n1, n2, n3]) Ok([n1, n2, n3])
} }
| _ => Error(impossibleErrorString) | _ => Error(impossibleErrorString)
} }
} }
@ -108,8 +108,10 @@ module Prepare = {
} }
module Record = { module Record = {
let twoDistOrNumber = (values: ts, labels: (string, string)): result<(frValueDistOrNumber, frValueDistOrNumber), err> => let twoDistOrNumber = (values: ts, labels: (string, string)): result<
values->ToValueArray.Record.twoArgs(labels)->E.R.bind(twoDistOrNumber) (frValueDistOrNumber, frValueDistOrNumber),
err,
> => values->ToValueArray.Record.twoArgs(labels)->E.R.bind(twoDistOrNumber)
let twoDist = (values: ts, labels: (string, string)): result< let twoDist = (values: ts, labels: (string, string)): result<
(DistributionTypes.genericDist, DistributionTypes.genericDist), (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 Result = Belt.Result
module T = Reducer_T module T = Reducer_T
type errorValue = Reducer_ErrorValue.errorValue let toLocation = (expression: T.expression): SqError.location => {
let toLocation = (expression: T.expression): Reducer_ErrorValue.location => {
expression.ast.location expression.ast.location
} }
let throwFrom = (error: errorValue, expression: T.expression) => let throwFrom = (error: SqError.Message.t, expression: T.expression) =>
error->Reducer_ErrorValue.raiseNewExceptionWithStackTrace(expression->toLocation) error->SqError.Error.fromMessageWithLocation(expression->toLocation)->SqError.Error.throw
/* /*
Recursively evaluate the expression 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) let result = Lambda.doLambdaCall(lambda, argValues, context.environment, evaluate)
(result, context) (result, context)
} catch { } catch {
| Reducer_ErrorValue.ErrorException(e) => e->throwFrom(expression) // function implementation returned an error without location | exn =>
| Reducer_ErrorValue.ExceptionWithStackTrace(e) => exn
Reducer_ErrorValue.raiseExtendedExceptionWithStackTrace(e, expression->toLocation) // function implementation probably called a lambda that threw an exception ->SqError.Error.fromException
| Js.Exn.Error(obj) => ->SqError.Error.extend(expression->toLocation)
REJavaScriptExn(obj->Js.Exn.message, obj->Js.Exn.name)->throwFrom(expression) ->SqError.Error.throw
} }
| _ => RENotAFunction(lambda->Reducer_Value.toString)->throwFrom(expression) | _ => RENotAFunction(lambda->Reducer_Value.toString)->throwFrom(expression)
} }
@ -128,24 +126,18 @@ module BackCompatible = {
let parse = (peggyCode: string): result<T.expression, Reducer_Peggy_Parse.parseError> => let parse = (peggyCode: string): result<T.expression, Reducer_Peggy_Parse.parseError> =>
peggyCode->Reducer_Peggy_Parse.parse("main")->Result.map(Reducer_Peggy_ToExpression.fromNode) 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() let context = Reducer_Context.createDefaultContext()
try { try {
let (value, _) = expression->evaluate(context) let (value, _) = expression->evaluate(context)
value->Ok value->Ok
} catch { } catch {
| exn => | exn => exn->SqError.Error.fromException->Error
exn
->Reducer_ErrorValue.fromException
->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue
->Error // TODO - this could be done better (see ReducerProject)
} }
} }
let evaluateString = (peggyCode: string): result<T.value, Reducer_ErrorValue.error> => let evaluateString = (peggyCode: string): result<T.value, SqError.Error.t> =>
parse(peggyCode) parse(peggyCode)
->E.R2.errMap(e => ->E.R2.errMap(e => e->SqError.Message.fromParseError->SqError.Error.fromMessage)
e->Reducer_ErrorValue.fromParseError->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue
)
->Result.flatMap(evaluate) ->Result.flatMap(evaluate)
} }

View File

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

View File

@ -1,5 +1,3 @@
module ErrorValue = Reducer_ErrorValue
let doLambdaCall = ( let doLambdaCall = (
lambdaValue: Reducer_T.lambdaValue, lambdaValue: Reducer_T.lambdaValue,
args, args,
@ -28,7 +26,7 @@ let makeLambda = (
let argsLength = arguments->Js.Array2.length let argsLength = arguments->Js.Array2.length
let parametersLength = parameters->Js.Array2.length let parametersLength = parameters->Js.Array2.length
if argsLength !== parametersLength { 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 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 type environment = GenericDist.env
module T = Reducer_T module T = Reducer_T
@ -76,13 +72,13 @@ let toStringFunctionCall = ((fn, args)): string => `${fn}(${argsToString(args)})
let toStringResult = x => let toStringResult = x =>
switch x { switch x {
| Ok(a) => `Ok(${toString(a)})` | 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 { switch codeResult {
| Ok(a) => toString(a) | Ok(a) => toString(a)
| Error(m) => `Error(${ErrorValue.errorToString(m)})` | Error(m) => `Error(${SqError.Error.toString(m)})`
} }
type internalExpressionValueType = type internalExpressionValueType =
@ -144,10 +140,10 @@ let functionCallSignatureToString = (functionCallSignature: functionCallSignatur
let arrayToValueArray = (arr: array<t>): array<t> => arr 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 { switch rExpression {
| Ok(expression) => expression | 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 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 // TODO: Auto clean project based on topology
module Bindings = Reducer_Bindings module Bindings = Reducer_Bindings
module ErrorValue = Reducer_ErrorValue
module ProjectItem = ReducerProject_ProjectItem module ProjectItem = ReducerProject_ProjectItem
module T = ReducerProject_T module T = ReducerProject_T
module Topology = ReducerProject_Topology 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 => let getResult = (project: t, sourceId: string): ProjectItem.T.resultArgumentType =>
switch getResultOption(project, sourceId) { switch getResultOption(project, sourceId) {
| None => RENeedToRun->Reducer_ErrorValue.attachEmptyStackTraceToErrorValue->Error | None => RENeedToRun->SqError.Error.fromMessage->Error
| Some(result) => result | Some(result) => result
} }
@ -171,7 +170,7 @@ let linkDependencies = (project: t, sourceId: string): Reducer_T.namespace => {
"__result__", "__result__",
switch project->getResult(id) { switch project->getResult(id) {
| Ok(result) => result | 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") @module("./ReducerProject_IncludeParser.js")
external parse__: string => array<array<string>> = "parse" external parse__: string => array<array<string>> = "parse"
let parseIncludes = (expr: string): result< let parseIncludes = (expr: string): result<array<(string, string)>, SqError.Message.t> =>
array<(string, string)>,
Reducer_ErrorValue.errorValue,
> =>
try { try {
let answer = parse__(expr) let answer = parse__(expr)
// let logEntry = answer->Js.Array2.joinWith(",") // let logEntry = answer->Js.Array2.joinWith(",")

View File

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

View File

@ -1,22 +1,21 @@
module Parse = Reducer_Peggy_Parse module Parse = Reducer_Peggy_Parse
module ExpressionT = Reducer_Expression_T module ExpressionT = Reducer_Expression_T
open Reducer_ErrorValue
type sourceArgumentType = string type sourceArgumentType = string
type sourceType = string type sourceType = string
type rawParseArgumentType = result<Parse.node, errorValue> type rawParseArgumentType = result<Parse.node, SqError.Message.t>
type rawParseType = option<rawParseArgumentType> type rawParseType = option<rawParseArgumentType>
type expressionArgumentType = result<ExpressionT.t, errorValue> type expressionArgumentType = result<ExpressionT.t, SqError.Message.t>
type expressionType = option<expressionArgumentType> type expressionType = option<expressionArgumentType>
type continuationArgumentType = Reducer_T.namespace type continuationArgumentType = Reducer_T.namespace
type continuationType = option<continuationArgumentType> type continuationType = option<continuationArgumentType>
type continuationResultType = option<result<continuationArgumentType, errorValue>> type continuationResultType = option<result<continuationArgumentType, SqError.Message.t>>
type resultArgumentType = result<Reducer_T.value, error> type resultArgumentType = result<Reducer_T.value, SqError.Error.t>
type resultType = option<resultArgumentType> type resultType = option<resultArgumentType>
type continuesArgumentType = array<string> type continuesArgumentType = array<string>
type continuesType = array<string> type continuesType = array<string>
type includesArgumentType = string type includesArgumentType = string
type includesType = result<array<string>, errorValue> type includesType = result<array<string>, SqError.Message.t>
type importAsVariablesType = array<(string, string)> type importAsVariablesType = array<(string, string)>
type projectItem = { 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 = { let stdLib: Reducer_T.namespace = {
// constants // constants
@ -17,16 +17,15 @@ let stdLib: Reducer_T.namespace = {
switch Belt.Array.get(aValueArray, index) { switch Belt.Array.get(aValueArray, index) {
| Some(value) => value | Some(value) => value
| None => REArrayIndexNotFound("Array index not found", index)->ErrorException->raise | None => REArrayIndexNotFound("Array index not found", index)->throwMessage
} }
} }
| [IEvRecord(dict), IEvString(sIndex)] => | [IEvRecord(dict), IEvString(sIndex)] =>
switch Belt.Map.String.get(dict, sIndex) { switch Belt.Map.String.get(dict, sIndex) {
| Some(value) => value | Some(value) => value
| None => | None => RERecordPropertyNotFound("Record property not found", sIndex)->throwMessage
RERecordPropertyNotFound("Record property not found", sIndex)->ErrorException->raise
} }
| _ => REOther("Trying to access key on wrong value")->ErrorException->raise | _ => REOther("Trying to access key on wrong value")->throwMessage
} }
})->Reducer_T.IEvLambda, })->Reducer_T.IEvLambda,
) )
@ -49,7 +48,7 @@ let stdLib: Reducer_T.namespace = {
Reducer_Expression_Lambda.makeFFILambda((arguments, environment, reducer) => { Reducer_Expression_Lambda.makeFFILambda((arguments, environment, reducer) => {
switch FunctionRegistry_Library.call(name, arguments, environment, reducer) { switch FunctionRegistry_Library.call(name, arguments, environment, reducer) {
| Ok(value) => value | Ok(value) => value
| Error(error) => error->Reducer_ErrorValue.ErrorException->raise | Error(error) => error->SqError.Message.toException
} }
})->Reducer_T.IEvLambda, })->Reducer_T.IEvLambda,
) )