Compare commits

..

No commits in common. "aa9565b40b09403abd92ed4d2faa2a80e6b7bf45" and "c7c333b71ad52df23e9ceb7f17caa3a7eae468b5" have entirely different histories.

16 changed files with 126 additions and 203 deletions

View File

@ -8,9 +8,9 @@ Import it when you need decimal arithmetic that should not inherit `Real`'s bina
import lyng.decimal
```
## What `Decimal` Is For
## What `BigDecimal` Is For
Use `Decimal` when values are fundamentally decimal:
Use `BigDecimal` when values are fundamentally decimal:
- money
- human-entered quantities
@ -38,8 +38,8 @@ assertEquals("2.2", c.toStringExpanded())
The three forms mean different things:
- `1.d`: convert `Int -> Decimal`
- `2.2.d`: convert `Real -> Decimal`
- `1.d`: convert `Int -> BigDecimal`
- `2.2.d`: convert `Real -> BigDecimal`
- `"2.2".d`: parse exact decimal text
That distinction is intentional.
@ -67,36 +67,16 @@ The explicit factory methods are:
```lyng
import lyng.decimal
Decimal.fromInt(10)
Decimal.fromReal(2.5)
Decimal.fromString("12.34")
BigDecimal.fromInt(10)
BigDecimal.fromReal(2.5)
BigDecimal.fromString("12.34")
```
These are equivalent to the conversion-property forms, but sometimes clearer in APIs or generated code.
## From Kotlin
If you already have an ionspin `BigDecimal` on the host side, the simplest supported way to create a Lyng `Decimal` is:
```kotlin
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import net.sergeych.lyng.Script
import net.sergeych.lyng.asFacade
import net.sergeych.lyng.newDecimal
val scope = Script.newScope()
val decimal = scope.asFacade().newDecimal(BigDecimal.parseStringWithMode("12.34"))
```
Notes:
- `newDecimal(...)` loads `lyng.decimal` if needed
- it returns a real Lyng `Decimal` object instance
- this is the preferred Kotlin-side construction path when you already hold a host `BigDecimal`
## Core Operations
`Decimal` supports:
`BigDecimal` supports:
- `+`
- `-`
@ -135,7 +115,7 @@ assert(2 == 2.d)
assert(3 > 2.d)
```
Without this registration mechanism, only the cases directly implemented on the left-hand class would work. The bridge fills the gap for expressions such as `Int + Decimal` and `Real + Decimal`.
Without this registration mechanism, only the cases directly implemented on the left-hand class would work. The bridge fills the gap for expressions such as `Int + BigDecimal` and `Real + BigDecimal`.
See [OperatorInterop.md](OperatorInterop.md) for the generic mechanism behind that.
@ -246,7 +226,7 @@ assertEquals("-0.12", withDecimalContext(2, DecimalRounding.HalfTowardsZero) { (
## Decimal With Stdlib Math Functions
Core math helpers such as `abs`, `floor`, `ceil`, `round`, `sin`, `exp`, `ln`, `sqrt`, `log10`, `log2`, and `pow`
now also accept `Decimal`.
now also accept `BigDecimal`.
Current behavior is intentionally split:
@ -255,7 +235,7 @@ Current behavior is intentionally split:
- `floor(x)`
- `ceil(x)`
- `round(x)`
- `pow(x, y)` when `x` is `Decimal` and `y` is an integral exponent
- `pow(x, y)` when `x` is `BigDecimal` and `y` is an integral exponent
- temporary bridge through `Real`:
- `sin`, `cos`, `tan`
- `asin`, `acos`, `atan`
@ -268,7 +248,7 @@ Current behavior is intentionally split:
The temporary bridge is:
```lyng
Decimal -> Real -> host math -> Decimal
BigDecimal -> Real -> host math -> BigDecimal
```
This is a compatibility step, not the long-term design. Native decimal implementations will replace these bridge-based
@ -279,12 +259,12 @@ Examples:
```lyng
import lyng.decimal
assertEquals("2.5", (abs("-2.5".d) as Decimal).toStringExpanded())
assertEquals("2", (floor("2.9".d) as Decimal).toStringExpanded())
assertEquals("2.5", (abs("-2.5".d) as BigDecimal).toStringExpanded())
assertEquals("2", (floor("2.9".d) as BigDecimal).toStringExpanded())
// Temporary Real bridge:
assertEquals((exp(1.25) as Real).d.toStringExpanded(), (exp("1.25".d) as Decimal).toStringExpanded())
assertEquals((sqrt(2.0) as Real).d.toStringExpanded(), (sqrt("2".d) as Decimal).toStringExpanded())
assertEquals((exp(1.25) as Real).d.toStringExpanded(), (exp("1.25".d) as BigDecimal).toStringExpanded())
assertEquals((sqrt(2.0) as Real).d.toStringExpanded(), (sqrt("2".d) as BigDecimal).toStringExpanded())
```
If you care about exact decimal source text:

View File

@ -160,15 +160,15 @@ import lyng.decimal
3 > 2.d
```
work naturally even though `Int` and `Real` themselves were not edited to know `Decimal`.
work naturally even though `Int` and `Real` themselves were not edited to know `BigDecimal`.
The shape is:
- `leftClass = Int` or `Real`
- `rightClass = Decimal`
- `commonClass = Decimal`
- convert built-ins into `Decimal`
- leave `Decimal` values unchanged
- `rightClass = BigDecimal`
- `commonClass = BigDecimal`
- convert built-ins into `BigDecimal`
- leave `BigDecimal` values unchanged
## Step-By-Step Pattern For Your Own Type

View File

@ -15,9 +15,9 @@ Sources: `lynglib/src/commonMain/kotlin/net/sergeych/lyng/Script.kt`, `lynglib/s
- Preconditions: `require`, `check`.
- Async/concurrency: `launch`, `yield`, `flow`, `delay`.
- Math: `floor`, `ceil`, `round`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, `exp`, `ln`, `log10`, `log2`, `pow`, `sqrt`, `abs`, `clamp`.
- These helpers also accept `lyng.decimal.Decimal`.
- These helpers also accept `lyng.decimal.BigDecimal`.
- Exact Decimal path today: `abs`, `floor`, `ceil`, `round`, and `pow` with integral exponent.
- Temporary Decimal path for the rest: convert `Decimal -> Real`, compute, then convert back to `Decimal`.
- Temporary Decimal path for the rest: convert `BigDecimal -> Real`, compute, then convert back to `BigDecimal`.
- Treat that bridge as temporary; prefer native Decimal implementations when they become available.
## 3. Core Global Constants/Types
@ -60,9 +60,6 @@ Sources: `lynglib/src/commonMain/kotlin/net/sergeych/lyng/Script.kt`, `lynglib/s
## 5. Additional Built-in Modules (import explicitly)
- `import lyng.observable`
- `Observable`, `Subscription`, `ObservableList`, `ListChange` and change subtypes, `ChangeRejectionException`.
- `import lyng.decimal`
- `Decimal`, `DecimalContext`, `DecimalRounding`, `withDecimalContext(...)`.
- Kotlin host helper: `ScopeFacade.newDecimal(BigDecimal)` wraps an ionspin host decimal as a Lyng `Decimal`.
- `import lyng.complex`
- `Complex`, `complex(re, im)`, `cis(angle)`, and numeric embedding extensions such as `2.i` / `3.re`.
- `import lyng.matrix`

View File

@ -62,9 +62,9 @@ but:
The following functions return the argument unchanged if it is `Int`.
For `Decimal`:
For `BigDecimal`:
- `floor(x)`, `ceil(x)`, and `round(x)` currently use exact decimal operations
- the result stays `Decimal`
- the result stays `BigDecimal`
For `Real`, the result is a transformed `Real`.
@ -78,11 +78,11 @@ For `Real`, the result is a transformed `Real`.
## Lyng math functions
Decimal note:
- all scalar math helpers accept `Decimal`
- `abs(x)` stays exact for `Decimal`
- `pow(x, y)` is exact for `Decimal` when `y` is an integral exponent
- the remaining `Decimal` cases currently use a temporary bridge:
`Decimal -> Real -> host math -> Decimal`
- all scalar math helpers accept `BigDecimal`
- `abs(x)` stays exact for `BigDecimal`
- `pow(x, y)` is exact for `BigDecimal` when `y` is an integral exponent
- the remaining `BigDecimal` cases currently use a temporary bridge:
`BigDecimal -> Real -> host math -> BigDecimal`
- this is temporary; native decimal implementations are planned
| name | meaning |
@ -104,7 +104,7 @@ Decimal note:
| log10(x) | $log_{10}(x)$ |
| pow(x, y) | ${x^y}$ |
| sqrt(x) | $ \sqrt {x}$ |
| abs(x) | absolute value of x. Int if x is Int, Decimal if x is Decimal, Real otherwise |
| abs(x) | absolute value of x. Int if x is Int, BigDecimal if x is BigDecimal, Real otherwise |
| clamp(x, range) | limit x to be inside range boundaries |
For example:
@ -120,9 +120,9 @@ For example:
import lyng.decimal
// Decimal-aware math works too. Some functions are exact, some still bridge through Real temporarily:
assert( (abs("-2.5".d) as Decimal).toStringExpanded() == "2.5" )
assert( (floor("2.9".d) as Decimal).toStringExpanded() == "2" )
assert( sin("0.5".d) is Decimal )
assert( (abs("-2.5".d) as BigDecimal).toStringExpanded() == "2.5" )
assert( (floor("2.9".d) as BigDecimal).toStringExpanded() == "2" )
assert( sin("0.5".d) is BigDecimal )
// clamp() limits value to the range:
assert( clamp(15, 0..10) == 10 )

View File

@ -57,7 +57,7 @@ Lyng now ships a first-class decimal module built as a regular extension library
It provides:
- `Decimal`
- `BigDecimal`
- convenient `.d` conversions from `Int`, `Real`, and `String`
- mixed arithmetic with `Int` and `Real`
- local division precision and rounding control via `withDecimalContext(...)`

View File

@ -17,7 +17,6 @@
package net.sergeych.lyng
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import net.sergeych.lyng.obj.*
/**
@ -134,6 +133,3 @@ fun ScopeFacade.raiseIllegalOperation(message: String = "Operation is illegal"):
fun ScopeFacade.raiseIterationFinished(): Nothing =
raiseError(ObjIterationFinishedException(requireScope()))
suspend fun ScopeFacade.newDecimal(value: BigDecimal): ObjInstance =
ObjDecimalSupport.newDecimal(this, value)

View File

@ -253,7 +253,7 @@ class Script(
companion object {
private suspend fun ScopeFacade.numberToDouble(value: Obj): Double =
ObjDecimalSupport.toDoubleOrNull(value) ?: value.toDouble()
ObjBigDecimalSupport.toDoubleOrNull(value) ?: value.toDouble()
private suspend fun ScopeFacade.decimalAwareUnaryMath(
value: Obj,
@ -263,9 +263,9 @@ class Script(
exactDecimal?.let { exact ->
exact(value)?.let { return it }
}
if (ObjDecimalSupport.isDecimalValue(value)) {
return ObjDecimalSupport.fromRealLike(this, value, fallback(numberToDouble(value)))
?: raiseIllegalState("failed to convert Real result back to Decimal")
if (ObjBigDecimalSupport.isDecimalValue(value)) {
return ObjBigDecimalSupport.fromRealLike(this, value, fallback(numberToDouble(value)))
?: raiseIllegalState("failed to convert Real result back to BigDecimal")
}
return ObjReal(fallback(numberToDouble(value)))
}
@ -281,11 +281,11 @@ class Script(
}
private suspend fun ScopeFacade.decimalAwarePow(base: Obj, exponent: Obj): Obj {
ObjDecimalSupport.exactPow(this, base, exponent)?.let { return it }
if (ObjDecimalSupport.isDecimalValue(base) || ObjDecimalSupport.isDecimalValue(exponent)) {
return ObjDecimalSupport.fromRealLike(this, base, numberToDouble(base).pow(numberToDouble(exponent)))
?: ObjDecimalSupport.fromRealLike(this, exponent, numberToDouble(base).pow(numberToDouble(exponent)))
?: raiseIllegalState("failed to convert Real pow result back to Decimal")
ObjBigDecimalSupport.exactPow(this, base, exponent)?.let { return it }
if (ObjBigDecimalSupport.isDecimalValue(base) || ObjBigDecimalSupport.isDecimalValue(exponent)) {
return ObjBigDecimalSupport.fromRealLike(this, base, numberToDouble(base).pow(numberToDouble(exponent)))
?: ObjBigDecimalSupport.fromRealLike(this, exponent, numberToDouble(base).pow(numberToDouble(exponent)))
?: raiseIllegalState("failed to convert Real pow result back to BigDecimal")
}
return ObjReal(numberToDouble(base).pow(numberToDouble(exponent)))
}
@ -327,15 +327,15 @@ class Script(
}
addFn("floor") {
val x = args.firstAndOnly()
decimalAwareRoundLike(x, ObjDecimalSupport::exactFloor, ::floor)
decimalAwareRoundLike(x, ObjBigDecimalSupport::exactFloor, ::floor)
}
addFn("ceil") {
val x = args.firstAndOnly()
decimalAwareRoundLike(x, ObjDecimalSupport::exactCeil, ::ceil)
decimalAwareRoundLike(x, ObjBigDecimalSupport::exactCeil, ::ceil)
}
addFn("round") {
val x = args.firstAndOnly()
decimalAwareRoundLike(x, ObjDecimalSupport::exactRound, ::round)
decimalAwareRoundLike(x, ObjBigDecimalSupport::exactRound, ::round)
}
addFn("sin") {
@ -401,7 +401,7 @@ class Script(
addFn("abs") {
val x = args.firstAndOnly()
if (x is ObjInt) ObjInt(x.value.absoluteValue)
else decimalAwareUnaryMath(x, ObjDecimalSupport::exactAbs) { it.absoluteValue }
else decimalAwareUnaryMath(x, ObjBigDecimalSupport::exactAbs) { it.absoluteValue }
}
addFnDoc(
@ -661,15 +661,15 @@ class Script(
)
ensureFn("floor") {
val x = args.firstAndOnly()
decimalAwareRoundLike(x, ObjDecimalSupport::exactFloor, ::floor)
decimalAwareRoundLike(x, ObjBigDecimalSupport::exactFloor, ::floor)
}
ensureFn("ceil") {
val x = args.firstAndOnly()
decimalAwareRoundLike(x, ObjDecimalSupport::exactCeil, ::ceil)
decimalAwareRoundLike(x, ObjBigDecimalSupport::exactCeil, ::ceil)
}
ensureFn("round") {
val x = args.firstAndOnly()
decimalAwareRoundLike(x, ObjDecimalSupport::exactRound, ::round)
decimalAwareRoundLike(x, ObjBigDecimalSupport::exactRound, ::round)
}
ensureFn("sin") {
decimalAwareUnaryMath(args.firstAndOnly(), fallback = ::sin)
@ -729,7 +729,7 @@ class Script(
ensureFn("abs") {
val x = args.firstAndOnly()
if (x is ObjInt) ObjInt(x.value.absoluteValue)
else decimalAwareUnaryMath(x, ObjDecimalSupport::exactAbs) { it.absoluteValue }
else decimalAwareUnaryMath(x, ObjBigDecimalSupport::exactAbs) { it.absoluteValue }
}
}
}
@ -867,7 +867,7 @@ class Script(
}
addPackage("lyng.decimal") { module ->
module.eval(Source("lyng.decimal", decimalLyng))
ObjDecimalSupport.bindTo(module)
ObjBigDecimalSupport.bindTo(module)
}
addPackage("lyng.matrix") { module ->
module.eval(Source("lyng.matrix", matrixLyng))

View File

@ -448,37 +448,37 @@ private fun buildStdlibDocs(): List<MiniDecl> {
// Math helpers (scalar versions)
fun math1(name: String) = mod.funDoc(
name = name,
doc = StdlibInlineDocIndex.topFunDoc(name) ?: "Compute $name(x). Accepts Int, Real, and Decimal. Decimal currently uses a temporary Real bridge and will get native decimal implementations later.",
doc = StdlibInlineDocIndex.topFunDoc(name) ?: "Compute $name(x). Accepts Int, Real, and BigDecimal. BigDecimal currently uses a temporary Real bridge and will get native decimal implementations later.",
params = listOf(ParamDoc("x", type("lyng.Number")))
)
math1("sin"); math1("cos"); math1("tan"); math1("asin"); math1("acos"); math1("atan")
mod.funDoc(name = "floor", doc = StdlibInlineDocIndex.topFunDoc("floor") ?: "Round down the number to the nearest integer. Decimal is handled directly and stays Decimal.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "ceil", doc = StdlibInlineDocIndex.topFunDoc("ceil") ?: "Round up the number to the nearest integer. Decimal is handled directly and stays Decimal.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "round", doc = StdlibInlineDocIndex.topFunDoc("round") ?: "Round the number to the nearest integer. Decimal is handled directly and stays Decimal.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "floor", doc = StdlibInlineDocIndex.topFunDoc("floor") ?: "Round down the number to the nearest integer. BigDecimal is handled directly and stays BigDecimal.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "ceil", doc = StdlibInlineDocIndex.topFunDoc("ceil") ?: "Round up the number to the nearest integer. BigDecimal is handled directly and stays BigDecimal.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "round", doc = StdlibInlineDocIndex.topFunDoc("round") ?: "Round the number to the nearest integer. BigDecimal is handled directly and stays BigDecimal.", params = listOf(ParamDoc("x", type("lyng.Number"))))
// Hyperbolic and inverse hyperbolic
math1("sinh"); math1("cosh"); math1("tanh"); math1("asinh"); math1("acosh"); math1("atanh")
// Exponentials and logarithms
mod.funDoc(name = "exp", doc = StdlibInlineDocIndex.topFunDoc("exp") ?: "Euler's exponential e^x. Decimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "ln", doc = StdlibInlineDocIndex.topFunDoc("ln") ?: "Natural logarithm (base e). Decimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "log10", doc = StdlibInlineDocIndex.topFunDoc("log10") ?: "Logarithm base 10. Decimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "log2", doc = StdlibInlineDocIndex.topFunDoc("log2") ?: "Logarithm base 2. Decimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "exp", doc = StdlibInlineDocIndex.topFunDoc("exp") ?: "Euler's exponential e^x. BigDecimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "ln", doc = StdlibInlineDocIndex.topFunDoc("ln") ?: "Natural logarithm (base e). BigDecimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "log10", doc = StdlibInlineDocIndex.topFunDoc("log10") ?: "Logarithm base 10. BigDecimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
mod.funDoc(name = "log2", doc = StdlibInlineDocIndex.topFunDoc("log2") ?: "Logarithm base 2. BigDecimal currently uses a temporary Real bridge and will get a native decimal implementation later.", params = listOf(ParamDoc("x", type("lyng.Number"))))
// Power/roots and absolute value
mod.funDoc(
name = "pow",
doc = StdlibInlineDocIndex.topFunDoc("pow") ?: "Raise `x` to the power `y`. Decimal with integral `y` is handled directly; other Decimal cases currently use a temporary Real bridge.",
doc = StdlibInlineDocIndex.topFunDoc("pow") ?: "Raise `x` to the power `y`. BigDecimal with integral `y` is handled directly; other BigDecimal cases currently use a temporary Real bridge.",
params = listOf(ParamDoc("x", type("lyng.Number")), ParamDoc("y", type("lyng.Number")))
)
mod.funDoc(
name = "sqrt",
doc = StdlibInlineDocIndex.topFunDoc("sqrt") ?: "Square root of `x`. Decimal currently uses a temporary Real bridge and will get a native decimal implementation later.",
doc = StdlibInlineDocIndex.topFunDoc("sqrt") ?: "Square root of `x`. BigDecimal currently uses a temporary Real bridge and will get a native decimal implementation later.",
params = listOf(ParamDoc("x", type("lyng.Number")))
)
mod.funDoc(
name = "abs",
doc = StdlibInlineDocIndex.topFunDoc("abs") ?: "Absolute value of a number. Int stays Int, and Decimal stays Decimal.",
doc = StdlibInlineDocIndex.topFunDoc("abs") ?: "Absolute value of a number. Int stays Int, and BigDecimal stays BigDecimal.",
params = listOf(ParamDoc("x", type("lyng.Number")))
)

View File

@ -26,16 +26,16 @@ import net.sergeych.lyng.miniast.type
import net.sergeych.lyng.requiredArg
import com.ionspin.kotlin.bignum.decimal.BigDecimal as IonBigDecimal
object ObjDecimalSupport {
object ObjBigDecimalSupport {
private const val decimalContextVar = "__lyng_decimal_context__"
// For Real -> Decimal, preserve the actual IEEE-754 Double value using a
// For Real -> BigDecimal, preserve the actual IEEE-754 Double value using a
// round-trip-safe precision. This intentionally does not try to recover source text.
private val realConversionMode = DecimalMode(17L, RoundingMode.ROUND_HALF_TO_EVEN)
// Division needs an explicit stopping rule for non-terminating results. Use a
// decimal128-like default context until Lyng exposes per-operation contexts.
private val defaultDivisionMode = DecimalMode(34L, RoundingMode.ROUND_HALF_TO_EVEN)
private val zero: IonBigDecimal = IonBigDecimal.ZERO
private val decimalTypeDecl = TypeDecl.Simple("lyng.decimal.Decimal", false)
private val decimalTypeDecl = TypeDecl.Simple("lyng.decimal.BigDecimal", false)
private object BoundMarker
private data class DecimalRuntimeContext(
val precision: Long,
@ -43,7 +43,7 @@ object ObjDecimalSupport {
) : Obj()
suspend fun bindTo(module: ModuleScope) {
val decimalClass = module.requireClass("Decimal")
val decimalClass = module.requireClass("BigDecimal")
if (decimalClass.kotlinClassData === BoundMarker) return
decimalClass.kotlinClassData = BoundMarker
decimalClass.isAbstract = false
@ -99,7 +99,7 @@ object ObjDecimalSupport {
try {
newInstance(decimalClass, IonBigDecimal.parseStringWithMode(value))
} catch (e: Throwable) {
requireScope().raiseIllegalArgument("invalid Decimal string: $value")
requireScope().raiseIllegalArgument("invalid BigDecimal string: $value")
}
}
module.addFn("withDecimalContext") {
@ -129,7 +129,7 @@ object ObjDecimalSupport {
}
fun isDecimalValue(value: Obj): Boolean =
value is ObjInstance && value.objClass.className == "Decimal"
value is ObjInstance && value.objClass.className == "BigDecimal"
suspend fun exactAbs(scope: ScopeFacade, value: Obj): Obj? =
decimalValueOrNull(value)?.let { scope.newInstanceLikeDecimal(value, it.abs()) }
@ -159,14 +159,8 @@ object ObjDecimalSupport {
fun toDoubleOrNull(value: Obj): Double? =
decimalValueOrNull(value)?.doubleValue(false)
suspend fun newDecimal(scope: ScopeFacade, value: IonBigDecimal): ObjInstance {
val decimalModule = scope.requireScope().currentImportProvider.createModuleScope(scope.pos, "lyng.decimal")
val decimalClass = decimalModule.requireClass("Decimal")
return scope.newInstance(decimalClass, value)
}
private fun valueOf(obj: Obj): IonBigDecimal {
val instance = obj as? ObjInstance ?: error("Decimal receiver must be an object instance")
val instance = obj as? ObjInstance ?: error("BigDecimal receiver must be an object instance")
return instance.kotlinInstanceData as? IonBigDecimal ?: zero
}
@ -192,14 +186,14 @@ object ObjDecimalSupport {
private suspend fun ScopeFacade.newInstance(decimalClass: ObjClass, value: IonBigDecimal): ObjInstance {
val instance = call(decimalClass) as? ObjInstance
?: raiseIllegalState("Decimal() did not return an object instance")
?: raiseIllegalState("BigDecimal() did not return an object instance")
instance.kotlinInstanceData = value
return instance
}
private suspend fun ScopeFacade.newInstanceLikeDecimal(sample: Obj, value: IonBigDecimal): ObjInstance {
val decimalClass = (sample as? ObjInstance)?.objClass
?: raiseIllegalState("Decimal sample must be an object instance")
?: raiseIllegalState("BigDecimal sample must be an object instance")
return newInstance(decimalClass, value)
}
@ -207,12 +201,12 @@ object ObjDecimalSupport {
is ObjInt -> IonBigDecimal.fromLongAsSignificand(value.value)
is ObjReal -> IonBigDecimal.fromDouble(value.value, realConversionMode)
is ObjInstance -> {
if (value.objClass.className != "Decimal") {
scope.raiseIllegalArgument("expected Decimal-compatible value, got ${value.objClass.className}")
if (value.objClass.className != "BigDecimal") {
scope.raiseIllegalArgument("expected BigDecimal-compatible value, got ${value.objClass.className}")
}
value.kotlinInstanceData as? IonBigDecimal ?: zero
}
else -> scope.raiseIllegalArgument("expected Decimal-compatible value, got ${value.objClass.className}")
else -> scope.raiseIllegalArgument("expected BigDecimal-compatible value, got ${value.objClass.className}")
}
private suspend fun normalizeContext(scope: Scope, value: Obj): DecimalRuntimeContext {
@ -300,31 +294,31 @@ object ObjDecimalSupport {
private fun registerBuiltinConversions(decimalClass: ObjClass) {
ObjInt.type.addPropertyDoc(
name = "d",
doc = "Convert this integer to a Decimal.",
type = type("lyng.decimal.Decimal"),
doc = "Convert this integer to a BigDecimal.",
type = type("lyng.decimal.BigDecimal"),
moduleName = "lyng.decimal",
getter = { newInstance(decimalClass, IonBigDecimal.fromLongAsSignificand(thisAs<ObjInt>().value)) }
)
ObjInt.type.members["d"] = ObjInt.type.members.getValue("d").copy(typeDecl = decimalTypeDecl)
ObjReal.type.addPropertyDoc(
name = "d",
doc = "Convert this real number to a Decimal by preserving the current IEEE-754 value with 17 significant digits and half-even rounding.",
type = type("lyng.decimal.Decimal"),
doc = "Convert this real number to a BigDecimal by preserving the current IEEE-754 value with 17 significant digits and half-even rounding.",
type = type("lyng.decimal.BigDecimal"),
moduleName = "lyng.decimal",
getter = { newInstance(decimalClass, IonBigDecimal.fromDouble(thisAs<ObjReal>().value, realConversionMode)) }
)
ObjReal.type.members["d"] = ObjReal.type.members.getValue("d").copy(typeDecl = decimalTypeDecl)
ObjString.type.addPropertyDoc(
name = "d",
doc = "Parse this string as a Decimal.",
type = type("lyng.decimal.Decimal"),
doc = "Parse this string as a BigDecimal.",
type = type("lyng.decimal.BigDecimal"),
moduleName = "lyng.decimal",
getter = {
val value = thisAs<ObjString>().value
try {
newInstance(decimalClass, IonBigDecimal.parseStringWithMode(value))
} catch (e: Throwable) {
requireScope().raiseIllegalArgument("invalid Decimal string: $value")
requireScope().raiseIllegalArgument("invalid BigDecimal string: $value")
}
}
)

View File

@ -587,10 +587,6 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
}
override suspend fun compareTo(scope: Scope, other: Obj): Int {
val explicitCompare = objClass.getInstanceMemberOrNull("compareTo", includeStatic = false)
if (explicitCompare != null) {
return invokeInstanceMethod(scope, "compareTo", Arguments(other)).cast<ObjInt>(scope).toInt()
}
if (other !is ObjInstance || other.objClass != objClass) {
OperatorInteropRegistry.invokeCompare(scope, this, other)?.let { return it }
return -1

View File

@ -48,7 +48,7 @@ enum DecimalRounding {
/**
* Dynamic decimal arithmetic settings.
*
* A decimal context is not attached permanently to a `Decimal` value. Instead, it is applied dynamically
* A decimal context is not attached permanently to a `BigDecimal` value. Instead, it is applied dynamically
* inside `withDecimalContext(...)`, which makes the rule local to a block of code.
*
* Default context:
@ -76,7 +76,7 @@ class DecimalContext(
/**
* Arbitrary-precision decimal value.
*
* `Decimal` is intended for decimal arithmetic where binary floating-point (`Real`) is the wrong tool:
* `BigDecimal` is intended for decimal arithmetic where binary floating-point (`Real`) is the wrong tool:
* - money
* - human-entered decimal values
* - ratios that should round in decimal, not in binary
@ -84,10 +84,10 @@ class DecimalContext(
*
* Creating values:
*
* - `1.d` converts `Int -> Decimal`
* - `2.2.d` converts `Real -> Decimal` by preserving the current IEEE-754 value
* - `1.d` converts `Int -> BigDecimal`
* - `2.2.d` converts `Real -> BigDecimal` by preserving the current IEEE-754 value
* - `"2.2".d` parses exact decimal text
* - `Decimal.fromInt(...)`, `fromReal(...)`, `fromString(...)` are explicit factory forms
* - `BigDecimal.fromInt(...)`, `fromReal(...)`, `fromString(...)` are explicit factory forms
*
* Important distinction:
*
@ -109,7 +109,7 @@ class DecimalContext(
*
* Mixed arithmetic:
*
* `Decimal` defines its own operators against decimal-compatible values, and the decimal module also registers
* `BigDecimal` defines its own operators against decimal-compatible values, and the decimal module also registers
* interop bridges so built-in left-hand operands work naturally:
*
* import lyng.decimal
@ -134,15 +134,15 @@ class DecimalContext(
*
* "2.2".d
*
* That is the precise form. `2.2.d` remains a `Real -> Decimal` conversion by design.
* That is the precise form. `2.2.d` remains a `Real -> BigDecimal` conversion by design.
*/
extern class Decimal() {
extern class BigDecimal() {
/** Add another decimal-compatible value. */
extern fun plus(other: Object): Decimal
extern fun plus(other: Object): BigDecimal
/** Subtract another decimal-compatible value. */
extern fun minus(other: Object): Decimal
extern fun minus(other: Object): BigDecimal
/** Multiply by another decimal-compatible value. */
extern fun mul(other: Object): Decimal
extern fun mul(other: Object): BigDecimal
/**
* Divide by another decimal-compatible value.
*
@ -150,13 +150,13 @@ extern class Decimal() {
* - by default: `34` significant digits, `HalfEven`
* - inside `withDecimalContext(...)`: the context active for the current block
*/
extern fun div(other: Object): Decimal
extern fun div(other: Object): BigDecimal
/** Remainder with another decimal-compatible value. */
extern fun mod(other: Object): Decimal
extern fun mod(other: Object): BigDecimal
/** Compare with another decimal-compatible value. */
extern fun compareTo(other: Object): Int
/** Unary minus. */
extern fun negate(): Decimal
extern fun negate(): BigDecimal
/** Convert to `Int` by dropping the fractional part according to backend conversion rules. */
extern fun toInt(): Int
/** Convert to `Real`. */
@ -169,16 +169,16 @@ extern class Decimal() {
extern fun toStringExpanded(): String
/** Create a decimal from an `Int`. */
static extern fun fromInt(value: Int): Decimal
static extern fun fromInt(value: Int): BigDecimal
/**
* Create a decimal from a `Real`.
*
* This preserves the current IEEE-754 value using a round-trip-safe decimal conversion.
* It does not try to recover the original source text.
*/
static extern fun fromReal(value: Real): Decimal
static extern fun fromReal(value: Real): BigDecimal
/** Parse exact decimal text. */
static extern fun fromString(value: String): Decimal
static extern fun fromString(value: String): BigDecimal
}
/**

View File

@ -97,7 +97,7 @@ enum BinaryOperator {
* The registry is symmetric for the converted values, but not for the original syntax.
* Its job is specifically to fill the gap where your custom type appears on the right:
*
* - `myDecimal + 1` usually already works if `Decimal.plus(Int)` exists
* - `myDecimal + 1` usually already works if `BigDecimal.plus(Int)` exists
* - `1 + myDecimal` needs registration because `Int` itself is not rewritten
*
* Typical pattern for a custom type:
@ -135,7 +135,7 @@ enum BinaryOperator {
* - `3 > Rational(5, 2)` works
* - `2 == Rational(2, 1)` works
*
* Decimal uses the same mechanism internally to make `Int + Decimal` and `Real + Decimal`
* Decimal uses the same mechanism internally to make `Int + BigDecimal` and `Real + BigDecimal`
* work without changing the built-in `Int` or `Real` classes.
*/
extern object OperatorInterop {

View File

@ -17,12 +17,10 @@
package net.sergeych.lyng
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
class DecimalModuleTest {
class BigDecimalModuleTest {
@Test
fun testDecimalModuleFactoriesAndConversions() = runTest {
val scope = Script.newScope()
@ -30,8 +28,8 @@ class DecimalModuleTest {
"""
import lyng.decimal
assertEquals("12.34", Decimal.fromString("12.34").toStringExpanded())
assertEquals("1", Decimal.fromInt(1).toStringExpanded())
assertEquals("12.34", BigDecimal.fromString("12.34").toStringExpanded())
assertEquals("1", BigDecimal.fromInt(1).toStringExpanded())
assertEquals("2.5", "2.5".d.toStringExpanded())
assertEquals("1", 1.d.toStringExpanded())
assertEquals("2.2", 2.2.d.toStringExpanded())
@ -156,14 +154,14 @@ class DecimalModuleTest {
"""
import lyng.decimal
val absValue = abs("-2.5".d) as Decimal
val floorPos = floor("2.9".d) as Decimal
val floorNeg = floor("-2.1".d) as Decimal
val ceilPos = ceil("2.1".d) as Decimal
val ceilNeg = ceil("-2.1".d) as Decimal
val roundPos = round("2.5".d) as Decimal
val roundNeg = round("-2.5".d) as Decimal
val powInt = pow("1.5".d, 2) as Decimal
val absValue = abs("-2.5".d) as BigDecimal
val floorPos = floor("2.9".d) as BigDecimal
val floorNeg = floor("-2.1".d) as BigDecimal
val ceilPos = ceil("2.1".d) as BigDecimal
val ceilNeg = ceil("-2.1".d) as BigDecimal
val roundPos = round("2.5".d) as BigDecimal
val roundNeg = round("-2.5".d) as BigDecimal
val powInt = pow("1.5".d, 2) as BigDecimal
assertEquals("2.5", absValue.toStringExpanded())
assertEquals("2", floorPos.toStringExpanded())
@ -184,13 +182,13 @@ class DecimalModuleTest {
"""
import lyng.decimal
val sinDecimal = sin("0.5".d) as Decimal
val expDecimal = exp("1.25".d) as Decimal
val sqrtDecimal = sqrt("2".d) as Decimal
val lnDecimal = ln("2".d) as Decimal
val log10Decimal = log10("2".d) as Decimal
val log2Decimal = log2("2".d) as Decimal
val powDecimal = pow("2".d, "0.5".d) as Decimal
val sinDecimal = sin("0.5".d) as BigDecimal
val expDecimal = exp("1.25".d) as BigDecimal
val sqrtDecimal = sqrt("2".d) as BigDecimal
val lnDecimal = ln("2".d) as BigDecimal
val log10Decimal = log10("2".d) as BigDecimal
val log2Decimal = log2("2".d) as BigDecimal
val powDecimal = pow("2".d, "0.5".d) as BigDecimal
assertEquals((sin(0.5) as Real).d.toStringExpanded(), sinDecimal.toStringExpanded())
assertEquals((exp(1.25) as Real).d.toStringExpanded(), expDecimal.toStringExpanded())
@ -211,8 +209,8 @@ class DecimalModuleTest {
val decimal = 42.d
val context = DecimalContext(12)
assert(decimal is Decimal)
assertEquals(Decimal, decimal::class)
assert(decimal is BigDecimal)
assertEquals(BigDecimal, decimal::class)
assert(context is DecimalContext)
assertEquals(DecimalContext, context::class)
@ -228,25 +226,4 @@ class DecimalModuleTest {
assertEquals(53.d, X)
""")
}
@Test
fun kotlinHelperCanWrapIonBigDecimal() = runTest {
val scope = Script.newScope()
val decimal = scope.asFacade().newDecimal(BigDecimal.parseStringWithMode("12.34"))
assertEquals("Decimal", decimal.objClass.className)
assertEquals("12.34", decimal.toString(scope).value)
assertEquals("12.34", decimal.invokeInstanceMethod(scope, "toStringExpanded").cast<net.sergeych.lyng.obj.ObjString>(scope).value)
}
@Test
fun testDecimalComparisons() = runTest {
eval("""
import lyng.decimal
val X = 42.d
assert(X < 43.d)
assert(X < 43)
assert(X == 42)
""".trimIndent())
}
}

View File

@ -168,21 +168,4 @@ class MatrixModuleTest {
assertEquals(Vector, vectorValue::class)
""".trimIndent())
}
@Test
fun testMatrixAndVectorComparisons() = runTest {
eval("""
import lyng.matrix
val v0 = vector([1, 2, 3])
val v1 = vector([1, 2, 4])
assert(v0 < v1)
assert(v0 == vector([1, 2, 3]))
val m0 = matrix([[1, 2], [3, 4]])
val m1 = matrix([[1, 2], [3, 5]])
assert(m0 < m1)
assert(m0 == matrix([[1, 2], [3, 4]]))
""".trimIndent())
}
}

View File

@ -79,10 +79,10 @@ extern class MapEntry<K,V> : Array<Object> {
// Built-in math helpers (implemented in host runtime).
//
// Decimal note:
// - these helpers accept `Decimal` values too
// - these helpers accept `BigDecimal` values too
// - `abs`, `floor`, `ceil`, `round`, and `pow(x, y)` with integral `y` keep decimal arithmetic
// - the remaining decimal cases currently use a temporary bridge:
// `Decimal -> Real -> host math -> Decimal`
// `BigDecimal -> Real -> host math -> BigDecimal`
// - this is temporary and will be replaced with dedicated decimal implementations
extern fun abs(x: Object): Object
extern fun ln(x: Object): Object

View File

@ -1,8 +1,8 @@
# Decimal Math TODO
These stdlib math helpers currently accept `Decimal`, but some still use the temporary compatibility path
These stdlib math helpers currently accept `BigDecimal`, but some still use the temporary compatibility path
`Decimal -> Real -> host math -> Decimal`
`BigDecimal -> Real -> host math -> BigDecimal`
instead of a native decimal implementation.