From 69b32d0b93cf33e78e7d75055defff7fb869d32a Mon Sep 17 00:00:00 2001 From: Vyacheslav Matyukhin Date: Mon, 26 Sep 2022 04:44:08 +0400 Subject: [PATCH] refactor into SqError --- .../Reducer_Peggy_TestHelpers.res | 4 +- .../__tests__/Reducer/Reducer_TestHelpers.res | 3 +- .../__tests__/Reducer/Reducer_test.res | 2 +- .../ReducerProject_includes_test.res | 6 +- ...educerProject_tutorial_3_includes_test.res | 6 +- packages/squiggle-lang/src/js/SqError.ts | 8 +- packages/squiggle-lang/src/js/SqProject.ts | 12 +- .../src/rescript/FR/FR_Builtin.res | 4 +- .../src/rescript/FR/FR_Danger.res | 34 ++-- .../squiggle-lang/src/rescript/FR/FR_Date.res | 4 +- .../squiggle-lang/src/rescript/FR/FR_Dict.res | 21 +-- .../squiggle-lang/src/rescript/FR/FR_Dist.res | 14 +- .../src/rescript/FR/FR_GenericDist.res | 10 +- .../src/rescript/FR/FR_Pointset.res | 37 ++--- .../src/rescript/FR/FR_Sampleset.res | 13 +- .../src/rescript/FR/FR_Scoring.res | 18 ++- .../rescript/ForTS/ForTS_ReducerProject.res | 10 +- .../ForTS/ForTS_Reducer_ErrorValue.res | 21 --- .../src/rescript/ForTS/ForTS_SqError.res | 19 +++ .../ForTS_SquiggleValue.res | 4 +- .../src/rescript/ForTS/ForTS__Types.res | 3 +- .../FunctionRegistry_Core.res | 21 ++- .../FunctionRegistry_Helpers.res | 28 ++-- .../Reducer_Dispatch_ChainPiece.res | 27 ---- .../Reducer_Dispatch/Reducer_Dispatch_T.res | 21 --- .../rescript/Reducer/Reducer_ErrorValue.res | 131 ---------------- .../Reducer_Expression/Reducer_Expression.res | 32 ++-- .../Reducer_Expression_ExpressionBuilder.res | 2 - .../Reducer_Expression_Lambda.res | 4 +- .../src/rescript/Reducer/Reducer_Value.res | 14 +- .../ReducerProject/ReducerProject.res | 5 +- .../ReducerProject_ParseIncludes.res | 5 +- .../ReducerProject_ProjectItem.res | 23 +-- .../ReducerProject_ProjectItem_T.res | 11 +- .../squiggle-lang/src/rescript/SqError.res | 145 ++++++++++++++++++ .../SquiggleLibrary_StdLib.res | 11 +- 36 files changed, 329 insertions(+), 404 deletions(-) delete mode 100644 packages/squiggle-lang/src/rescript/ForTS/ForTS_Reducer_ErrorValue.res create mode 100644 packages/squiggle-lang/src/rescript/ForTS/ForTS_SqError.res delete mode 100644 packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_ChainPiece.res delete mode 100644 packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_T.res delete mode 100644 packages/squiggle-lang/src/rescript/Reducer/Reducer_ErrorValue.res create mode 100644 packages/squiggle-lang/src/rescript/SqError.res diff --git a/packages/squiggle-lang/__tests__/Reducer/Reducer_Peggy/Reducer_Peggy_TestHelpers.res b/packages/squiggle-lang/__tests__/Reducer/Reducer_Peggy/Reducer_Peggy_TestHelpers.res index 65d87565..e30d3274 100644 --- a/packages/squiggle-lang/__tests__/Reducer/Reducer_Peggy/Reducer_Peggy_TestHelpers.res +++ b/packages/squiggle-lang/__tests__/Reducer/Reducer_Peggy/Reducer_Peggy_TestHelpers.res @@ -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)) diff --git a/packages/squiggle-lang/__tests__/Reducer/Reducer_TestHelpers.res b/packages/squiggle-lang/__tests__/Reducer/Reducer_TestHelpers.res index 43de902e..efff179e 100644 --- a/packages/squiggle-lang/__tests__/Reducer/Reducer_TestHelpers.res +++ b/packages/squiggle-lang/__tests__/Reducer/Reducer_TestHelpers.res @@ -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 } ) diff --git a/packages/squiggle-lang/__tests__/Reducer/Reducer_test.res b/packages/squiggle-lang/__tests__/Reducer/Reducer_test.res index 49180135..0697d239 100644 --- a/packages/squiggle-lang/__tests__/Reducer/Reducer_test.res +++ b/packages/squiggle-lang/__tests__/Reducer/Reducer_test.res @@ -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", diff --git a/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_includes_test.res b/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_includes_test.res index a6b35ec4..6c6d46fe 100644 --- a/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_includes_test.res +++ b/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_includes_test.res @@ -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", () => { diff --git a/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_tutorial_3_includes_test.res b/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_tutorial_3_includes_test.res index 995ce4d3..bd06c481 100644 --- a/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_tutorial_3_includes_test.res +++ b/packages/squiggle-lang/__tests__/ReducerProject/ReducerProject_tutorial_3_includes_test.res @@ -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 } }) }) diff --git a/packages/squiggle-lang/src/js/SqError.ts b/packages/squiggle-lang/src/js/SqError.ts index c0c509b4..ea21dc11 100644 --- a/packages/squiggle-lang/src/js/SqError.ts +++ b/packages/squiggle-lang/src/js/SqError.ts @@ -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)); } } diff --git a/packages/squiggle-lang/src/js/SqProject.ts b/packages/squiggle-lang/src/js/SqProject.ts index 22f2f78a..30d8b245 100644 --- a/packages/squiggle-lang/src/js/SqProject.ts +++ b/packages/squiggle-lang/src/js/SqProject.ts @@ -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) ); } diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Builtin.res b/packages/squiggle-lang/src/rescript/FR/FR_Builtin.res index 84e6a50f..3e7a9e8b 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Builtin.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Builtin.res @@ -5,7 +5,7 @@ let nameSpace = "" // no namespaced versions type simpleDefinition = { inputs: array, - fn: array => result, + fn: array => result, } let makeFnMany = (name: string, definitions: array) => @@ -22,7 +22,7 @@ let makeFnMany = (name: string, definitions: array) => let makeFn = ( name: string, inputs: array, - fn: array => result, + fn: array => result, ) => makeFnMany(name, [{inputs: inputs, fn: fn}]) let library = [ diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Danger.res b/packages/squiggle-lang/src/rescript/FR/FR_Danger.res index 7767f8c1..0474c1f4 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Danger.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Danger.res @@ -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, - currentMarginalReturns: result, errorValue>, + currentMarginalReturns: result, errorMessage>, } let findBiggestElementIndex = (xs: array) => E.A.reducei(xs, 0, (acc, newElement, index) => { @@ -255,7 +255,7 @@ module DiminishingReturns = { | false => acc } }) - type diminishingReturnsAccumulator = result + type diminishingReturnsAccumulator = result // 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 }, (), diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Date.res b/packages/squiggle-lang/src/rescript/FR/FR_Date.res index c9732980..0e4b828d 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Date.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Date.res @@ -4,7 +4,7 @@ open FunctionRegistry_Helpers let makeFn = ( name: string, inputs: array, - fn: array => result, + fn: array => result, ) => 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) } diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Dict.res b/packages/squiggle-lang/src/rescript/FR/FR_Dict.res index 13bcfe33..f844ceac 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Dict.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Dict.res @@ -17,7 +17,7 @@ module Internals = { ->E.A2.fmap(((key, value)) => Wrappers.evArray([IEvString(key), value])) ->Wrappers.evArray - let fromList = (items: array): result => + let fromList = (items: array): result => items ->E.A2.fmap(item => { switch (item: Reducer_T.value) { @@ -59,7 +59,6 @@ let library = [ ], (), ), - Function.make( ~name="mergeMany", ~nameSpace, @@ -72,13 +71,17 @@ let library = [ ~inputs=[FRTypeArray(FRTypeDict(FRTypeAny))], ~run=(inputs, _, _) => { switch inputs { - | [IEvArray(dicts)] => { - dicts->Belt.Array.map(dictValue => switch dictValue { - | IEvRecord(dict) => dict - | _ => impossibleError->Reducer_ErrorValue.toException - })->Internals.mergeMany->Ok - } - | _ => impossibleError->Error + | [IEvArray(dicts)] => + dicts + ->Belt.Array.map(dictValue => + switch dictValue { + | IEvRecord(dict) => dict + | _ => impossibleError->SqError.Message.toException + } + ) + ->Internals.mergeMany + ->Ok + | _ => impossibleError->Error } }, (), diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Dist.res b/packages/squiggle-lang/src/rescript/FR/FR_Dist.res index 3a7504f2..270e2b4a 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Dist.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Dist.res @@ -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), (), ) } diff --git a/packages/squiggle-lang/src/rescript/FR/FR_GenericDist.res b/packages/squiggle-lang/src/rescript/FR/FR_GenericDist.res index 6f98d132..72249d19 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_GenericDist.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_GenericDist.res @@ -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 } }) diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Pointset.res b/packages/squiggle-lang/src/rescript/FR/FR_Pointset.res index 4babe231..28684f34 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Pointset.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Pointset.res @@ -7,31 +7,32 @@ let requiresNamespace = true let inputsToDist = (inputs: array, xyShapeToPointSetDist) => { // TODO - rewrite in more functional/functor-based style switch inputs { - | [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 - } + | [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->SqError.Message.toException } - | _ => 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->Reducer_ErrorValue.toException + | _ => impossibleError->SqError.Message.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 = { type t = PointSetDist.t - let toType = (r): result => + let toType = (r): result => 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) }, (), diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Sampleset.res b/packages/squiggle-lang/src/rescript/FR/FR_Sampleset.res index 5bbfb506..7f11ba7a 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Sampleset.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Sampleset.res @@ -18,7 +18,7 @@ module Internal = { | _ => Error(Operation.SampleMapNeedsNtoNFunction) } - let toType = (r): result => + let toType = (r): result => 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) => diff --git a/packages/squiggle-lang/src/rescript/FR/FR_Scoring.res b/packages/squiggle-lang/src/rescript/FR/FR_Scoring.res index 63589e83..60cb82e5 100644 --- a/packages/squiggle-lang/src/rescript/FR/FR_Scoring.res +++ b/packages/squiggle-lang/src/rescript/FR/FR_Scoring.res @@ -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)]) => diff --git a/packages/squiggle-lang/src/rescript/ForTS/ForTS_ReducerProject.res b/packages/squiggle-lang/src/rescript/ForTS/ForTS_ReducerProject.res index 857044d7..93581b15 100644 --- a/packages/squiggle-lang/src/rescript/ForTS/ForTS_ReducerProject.res +++ b/packages/squiggle-lang/src/rescript/ForTS/ForTS_ReducerProject.res @@ -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, - 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 => +let getResult = (project: reducerProject, sourceId: string): result => 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_Record) => +let evaluate = (sourceCode: string): (result, squiggleValue_Record) => Private.evaluate(sourceCode) @genType diff --git a/packages/squiggle-lang/src/rescript/ForTS/ForTS_Reducer_ErrorValue.res b/packages/squiggle-lang/src/rescript/ForTS/ForTS_Reducer_ErrorValue.res deleted file mode 100644 index 1392639b..00000000 --- a/packages/squiggle-lang/src/rescript/ForTS/ForTS_Reducer_ErrorValue.res +++ /dev/null @@ -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 => - 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) diff --git a/packages/squiggle-lang/src/rescript/ForTS/ForTS_SqError.res b/packages/squiggle-lang/src/rescript/ForTS/ForTS_SqError.res new file mode 100644 index 00000000..c6a4b131 --- /dev/null +++ b/packages/squiggle-lang/src/rescript/ForTS/ForTS_SqError.res @@ -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 => + 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 diff --git a/packages/squiggle-lang/src/rescript/ForTS/ForTS_SquiggleValue/ForTS_SquiggleValue.res b/packages/squiggle-lang/src/rescript/ForTS/ForTS_SquiggleValue/ForTS_SquiggleValue.res index ff029c95..2a8e8e1c 100644 --- a/packages/squiggle-lang/src/rescript/ForTS/ForTS_SquiggleValue/ForTS_SquiggleValue.res +++ b/packages/squiggle-lang/src/rescript/ForTS/ForTS_SquiggleValue/ForTS_SquiggleValue.res @@ -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) => +let toStringResult = (variantResult: result) => Reducer_Value.toStringResult(variantResult) @genType diff --git a/packages/squiggle-lang/src/rescript/ForTS/ForTS__Types.res b/packages/squiggle-lang/src/rescript/ForTS/ForTS__Types.res index 949801c7..cd6562b9 100644 --- a/packages/squiggle-lang/src/rescript/ForTS/ForTS__Types.res +++ b/packages/squiggle-lang/src/rescript/ForTS/ForTS__Types.res @@ -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 diff --git a/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Core.res b/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Core.res index e6929761..f39eecc4 100644 --- a/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Core.res +++ b/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Core.res @@ -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.environment, Reducer_T.reducerFn, - ) => result, + ) => result, } type function = { @@ -83,19 +83,17 @@ module FRType = { | (FRTypeNumeric, IEvNumber(_)) => true | (FRTypeNumeric, IEvDistribution(Symbolic(#Float(_)))) => true | (FRTypeLambda, IEvLambda(_)) => true - | (FRTypeArray(intendedType), IEvArray(elements)) => { - elements->Belt.Array.every(v => matchWithValue(intendedType, v)) - } + | (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 + | 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, env: Reducer_T.environment, reducer: Reducer_T.reducerFn, - ): result => { + ): result => { switch Belt.Map.String.get(registry.fnNameDict, fnName) { | Some(definitions) => { let showNameMatchDefinitions = () => { diff --git a/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Helpers.res b/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Helpers.res index a5a0f523..9ace7e20 100644 --- a/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Helpers.res +++ b/packages/squiggle-lang/src/rescript/FunctionRegistry/FunctionRegistry_Helpers.res @@ -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) @@ -30,21 +30,21 @@ module Prepare = { let twoArgs = (inputs: ts, (arg1: string, arg2: string)): result => switch inputs { | [IEvRecord(map)] => { - let n1 = map->Belt.Map.String.getExn(arg1) - let n2 = map->Belt.Map.String.getExn(arg2) - Ok([n1, n2]) - } + let n1 = map->Belt.Map.String.getExn(arg1) + let n2 = map->Belt.Map.String.getExn(arg2) + Ok([n1, n2]) + } | _ => Error(impossibleErrorString) } let threeArgs = (inputs: ts, (arg1: string, arg2: string, arg3: string)): result => switch inputs { | [IEvRecord(map)] => { - let n1 = map->Belt.Map.String.getExn(arg1) - let n2 = map->Belt.Map.String.getExn(arg2) - let n3 = map->Belt.Map.String.getExn(arg3) - Ok([n1, n2, n3]) - } + let n1 = map->Belt.Map.String.getExn(arg1) + let n2 = map->Belt.Map.String.getExn(arg2) + let n3 = map->Belt.Map.String.getExn(arg3) + Ok([n1, n2, n3]) + } | _ => Error(impossibleErrorString) } } @@ -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), diff --git a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_ChainPiece.res b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_ChainPiece.res deleted file mode 100644 index e545bb2d..00000000 --- a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_ChainPiece.res +++ /dev/null @@ -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 -} - -*/ diff --git a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_T.res b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_T.res deleted file mode 100644 index 0d852783..00000000 --- a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Dispatch/Reducer_Dispatch_T.res +++ /dev/null @@ -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> - -// type dispatchChainPieceWithReducer = ( -// Reducer_Value.functionCall, -// ProjectAccessorsT.t, -// Reducer_T.reducerFn, -// ) => option> - -// // This is a switch statement case implementation: get the arguments and compute the result -// type genericIEvFunction = ( -// array, -// ProjectAccessorsT.t, -// ) => result - diff --git a/packages/squiggle-lang/src/rescript/Reducer/Reducer_ErrorValue.res b/packages/squiggle-lang/src/rescript/Reducer/Reducer_ErrorValue.res deleted file mode 100644 index e2c1d495..00000000 --- a/packages/squiggle-lang/src/rescript/Reducer/Reducer_ErrorValue.res +++ /dev/null @@ -1,131 +0,0 @@ -type location = Reducer_Peggy_Parse.location - -@genType.opaque -type errorValue = - | REArityError(option, int, int) - | REArrayIndexNotFound(string, int) - | REAssignmentExpected - | REDistributionError(DistributionTypes.error) - | REExpectedType(string, string) - | REExpressionExpected - | REFunctionExpected(string) - | REFunctionNotFound(string) - | REJavaScriptExn(option, option) // Javascript Exception - | REMacroNotFound(string) - | RENotAFunction(string) - | REOperationError(Operation.operationError) - | RERecordPropertyNotFound(string, string) - | RESymbolNotFound(string) - | RESyntaxError(string, option) - | RETodo(string) // To do - | REUnitNotFound(string) - | RENeedToRun - | REOther(string) - -type t = errorValue - -exception ErrorException(errorValue) - -type rec stackTrace = { - location: location, - parent: option, -} - -@genType.opaque -type error = { - error: t, - stackTrace: option, -} - -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 diff --git a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression.res b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression.res index 714daffe..d0060982 100644 --- a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression.res +++ b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression.res @@ -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 => peggyCode->Reducer_Peggy_Parse.parse("main")->Result.map(Reducer_Peggy_ToExpression.fromNode) - let evaluate = (expression: T.expression): result => { + let evaluate = (expression: T.expression): result => { 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 => + let evaluateString = (peggyCode: string): result => 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) } diff --git a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_ExpressionBuilder.res b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_ExpressionBuilder.res index bd0a044a..965fc499 100644 --- a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_ExpressionBuilder.res +++ b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_ExpressionBuilder.res @@ -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 diff --git a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_Lambda.res b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_Lambda.res index e9a85a1a..36e43b25 100644 --- a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_Lambda.res +++ b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Expression/Reducer_Expression_Lambda.res @@ -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 diff --git a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Value.res b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Value.res index f7681ee7..ea0931f2 100644 --- a/packages/squiggle-lang/src/rescript/Reducer/Reducer_Value.res +++ b/packages/squiggle-lang/src/rescript/Reducer/Reducer_Value.res @@ -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): string => +let toStringResultOkless = (codeResult: result): 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): array => arr -let resultToValue = (rExpression: result): t => +let resultToValue = (rExpression: result): 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 diff --git a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject.res b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject.res index 082b620c..8ead6e32 100644 --- a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject.res +++ b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject.res @@ -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 }, ), ]) diff --git a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ParseIncludes.res b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ParseIncludes.res index 38370488..c0612be8 100644 --- a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ParseIncludes.res +++ b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ParseIncludes.res @@ -1,10 +1,7 @@ @module("./ReducerProject_IncludeParser.js") external parse__: string => array> = "parse" -let parseIncludes = (expr: string): result< - array<(string, string)>, - Reducer_ErrorValue.errorValue, -> => +let parseIncludes = (expr: string): result, SqError.Message.t> => try { let answer = parse__(expr) // let logEntry = answer->Js.Array2.joinWith(",") diff --git a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem.res b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem.res index 567ff29b..07ecac88 100644 --- a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem.res +++ b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem.res @@ -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 => { diff --git a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem_T.res b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem_T.res index 5d32a161..8ea3a814 100644 --- a/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem_T.res +++ b/packages/squiggle-lang/src/rescript/ReducerProject/ReducerProject_ProjectItem_T.res @@ -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 +type rawParseArgumentType = result type rawParseType = option -type expressionArgumentType = result +type expressionArgumentType = result type expressionType = option type continuationArgumentType = Reducer_T.namespace type continuationType = option -type continuationResultType = option> -type resultArgumentType = result +type continuationResultType = option> +type resultArgumentType = result type resultType = option type continuesArgumentType = array type continuesType = array type includesArgumentType = string -type includesType = result, errorValue> +type includesType = result, SqError.Message.t> type importAsVariablesType = array<(string, string)> type projectItem = { diff --git a/packages/squiggle-lang/src/rescript/SqError.res b/packages/squiggle-lang/src/rescript/SqError.res new file mode 100644 index 00000000..15f72d54 --- /dev/null +++ b/packages/squiggle-lang/src/rescript/SqError.res @@ -0,0 +1,145 @@ +type location = Reducer_Peggy_Parse.location + +module Message = { + @genType.opaque + type t = + | REArityError(option, int, int) + | REArrayIndexNotFound(string, int) + | REAssignmentExpected + | REDistributionError(DistributionTypes.error) + | REExpectedType(string, string) + | REExpressionExpected + | REFunctionExpected(string) + | REFunctionNotFound(string) + | REJavaScriptExn(option, option) // Javascript Exception + | REMacroNotFound(string) + | RENotAFunction(string) + | REOperationError(Operation.operationError) + | RERecordPropertyNotFound(string, string) + | RESymbolNotFound(string) + | RESyntaxError(string, option) + | 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, + } + + 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, + } + + 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 + } +} diff --git a/packages/squiggle-lang/src/rescript/SquiggleLibrary/SquiggleLibrary_StdLib.res b/packages/squiggle-lang/src/rescript/SquiggleLibrary/SquiggleLibrary_StdLib.res index 3be93851..57311827 100644 --- a/packages/squiggle-lang/src/rescript/SquiggleLibrary/SquiggleLibrary_StdLib.res +++ b/packages/squiggle-lang/src/rescript/SquiggleLibrary/SquiggleLibrary_StdLib.res @@ -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, )