Skip to content

Commit e6cdad7

Browse files
samuelcolvinclaude
andauthored
Add the decimal module (#1119)
Co-authored-by: Claude <[email protected]>
1 parent 3e191a8 commit e6cdad7

94 files changed

Lines changed: 11245 additions & 192 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/monty-js/__test__/external.spec.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,8 @@ const exceptionTypes: Array<[string, string]> = [
241241
['binascii.Error', 'binascii.Error'],
242242
['binascii.Incomplete', 'binascii.Incomplete'],
243243
['_csv.Error', '_csv.Error'],
244+
['decimal.InvalidOperation', 'decimal.InvalidOperation'],
245+
['decimal.DivisionByZero', 'decimal.DivisionByZero'],
244246
['SomeCustomError', 'RuntimeError'],
245247
]
246248

‎crates/monty-js/__test__/types.spec.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,33 @@ test('complex input round-trips', async () => {
433433
t.is(Object.is(back.real, -0) && Object.is(back.imag, -0), true)
434434
})
435435

436+
test('decimal output from sandbox', async () => {
437+
t.deepEqual(await run("import decimal\ndecimal.Decimal('19.990')"), { __monty_type__: 'Decimal', value: '19.990' })
438+
t.deepEqual(await run("import decimal\ndecimal.Decimal('-1e-30')"), { __monty_type__: 'Decimal', value: '-1E-30' })
439+
})
440+
441+
test('decimal input round-trips', async () => {
442+
const price = { __monty_type__: 'Decimal', value: '19.99' }
443+
t.deepEqual(await run('x', { inputs: { x: price } }), price)
444+
t.deepEqual(await run('(str(x), x > 1)', { inputs: { x: price } }), ['19.99', true])
445+
// Any numeric string `Decimal()` accepts comes back in canonical form.
446+
t.deepEqual(await run('x', { inputs: { x: { __monty_type__: 'Decimal', value: 'nan' } } }), {
447+
__monty_type__: 'Decimal',
448+
value: 'NaN',
449+
})
450+
})
451+
452+
test('malformed decimal marker is rejected by the wasm encoder', () => {
453+
t.deepEqual(encodeValue({ __monty_type__: 'Decimal', value: '1.5' }), {
454+
root: 0,
455+
nodes: [{ tag: 'decimal', val: '1.5' }],
456+
})
457+
t.throws(() => encodeValue({ __monty_type__: 'Decimal', value: 1.5 }), {
458+
instanceOf: TypeError,
459+
message: 'Decimal marker requires a string value',
460+
})
461+
})
462+
436463
test('malformed complex marker is rejected by the wasm encoder', () => {
437464
t.deepEqual(encodeValue({ __monty_type__: 'Complex', real: 1.5, imag: -2 }), {
438465
root: 0,

‎crates/monty-js/src/convert.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
//! - `Module` ↔ `{ __monty_type__: 'Module', name, id, attrs }`
2929
//! - `FileHandle` ↔ `{ __monty_type__: 'FileHandle', path, mode, position }`
3030
//! - `Complex` ↔ `{ __monty_type__: 'Complex', real, imag }`
31+
//! - `Decimal` ↔ `{ __monty_type__: 'Decimal', value }`, `value` being `str(d)`
3132
//! - `Repr` → plain `string`
3233
//! - `Cycle` → placeholder `string`
3334
#![expect(unsafe_code, reason = "napi API is unsafe")]
@@ -106,6 +107,7 @@ fn decode_node<'e>(node: &MontyNode, graph: &MontyGraph, built: &[Unknown<'e>],
106107
MontyNode::BigInt(bi) => create_js_bigint(bi, env),
107108
MontyNode::Float(f) => env.create_double(*f)?.into_unknown(env),
108109
MontyNode::Complex(c) => create_js_complex(c, env),
110+
MontyNode::Decimal(d) => create_js_decimal(d, env),
109111
MontyNode::String(s) => env.create_string(s)?.into_unknown(env),
110112
MontyNode::Bytes(bytes) => create_js_buffer(bytes, env),
111113
MontyNode::List(items) => create_js_array(&children(items), env)?.into_unknown(env),
@@ -343,6 +345,14 @@ fn create_js_complex<'e>(c: &MontyComplex, env: &'e Env) -> Result<Unknown<'e>>
343345
obj.into_unknown(env)
344346
}
345347

348+
/// Creates a JS object representing a Python `decimal.Decimal` by its exact string form.
349+
fn create_js_decimal<'e>(value: &str, env: &'e Env) -> Result<Unknown<'e>> {
350+
let mut obj = Object::new(env)?;
351+
obj.set_named_property("__monty_type__", "Decimal")?;
352+
obj.set_named_property("value", value)?;
353+
obj.into_unknown(env)
354+
}
355+
346356
/// Creates a JS object representing a Python `datetime.timedelta`.
347357
fn create_js_timedelta<'e>(delta: &MontyTimeDelta, env: &'e Env) -> Result<Unknown<'e>> {
348358
let mut obj = Object::new(env)?;
@@ -753,6 +763,7 @@ impl<'e> GraphEncoder<'e> {
753763
real: obj.get_named_property::<f64>("real")?,
754764
imag: obj.get_named_property::<f64>("imag")?,
755765
}),
766+
"Decimal" => MontyNode::Decimal(obj.get_named_property::<String>("value")?),
756767
"TimeDelta" => MontyNode::TimeDelta(MontyTimeDelta {
757768
days: obj.get_named_property::<i32>("days")?,
758769
seconds: obj.get_named_property::<i32>("seconds")?,

‎crates/monty-js/ts/errors.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,20 @@ export const PYTHON_EXC_NAMES: ReadonlySet<string> = new Set([
308308
'binascii.Error',
309309
'binascii.Incomplete',
310310
'_csv.Error',
311+
'decimal.DecimalException',
312+
'decimal.Clamped',
313+
'decimal.InvalidOperation',
314+
'decimal.ConversionSyntax',
315+
'decimal.DivisionByZero',
316+
'decimal.DivisionImpossible',
317+
'decimal.DivisionUndefined',
318+
'decimal.Inexact',
319+
'decimal.InvalidContext',
320+
'decimal.Rounded',
321+
'decimal.Subnormal',
322+
'decimal.Overflow',
323+
'decimal.Underflow',
324+
'decimal.FloatOperation',
311325
])
312326

313327
/**

‎crates/monty-js/ts/externalModule.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ const SANDBOX_MODULES = new Set([
123123
'csv',
124124
'dataclasses',
125125
'datetime',
126+
'decimal',
126127
'functools',
127128
'gc',
128129
'hashlib',

‎crates/monty-js/ts/shared.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ export {
5555
export {
5656
type MontyDate,
5757
type MontyDateTime,
58+
type MontyDecimal,
5859
type MontyException,
5960
MontyFileHandle,
6061
type MontyFileHandleOptions,

‎crates/monty-js/ts/types.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,18 @@ export interface MontyTimeDelta {
4545
microseconds: number
4646
}
4747

48+
/**
49+
* Marker object representing a Python `decimal.Decimal`.
50+
*
51+
* `value` is the exact string form, `str(d)` in Python (`'1.20'`, `'1E+5'`, `'NaN'`);
52+
* pass it to a JS decimal library to compute with it. Sending one into the
53+
* sandbox parses `value` as `Decimal(value)` does.
54+
*/
55+
export interface MontyDecimal {
56+
__monty_type__: 'Decimal'
57+
value: string
58+
}
59+
4860
/** Marker object representing a Python `datetime.timezone`. */
4961
export interface MontyTimeZone {
5062
__monty_type__: 'TimeZone'

‎crates/monty-js/ts/worker/component/interfaces/pydantic-monty-worker.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ export type ValueNode =
120120
| ValueNodeRepr
121121
| ValueNodeCycle
122122
| ValueNodeModule
123+
| ValueNodeDecimal
123124
export interface ValueNodeEllipsis {
124125
tag: 'ellipsis'
125126
}
@@ -245,6 +246,10 @@ export interface ValueNodeModule {
245246
tag: 'module'
246247
val: ModuleNode
247248
}
249+
export interface ValueNodeDecimal {
250+
tag: 'decimal'
251+
val: string
252+
}
248253
export interface Arena {
249254
nodes: Array<ValueNode>
250255
}

‎crates/monty-js/ts/worker/value.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,11 @@ export class ArenaEncoder {
180180
throw new TypeError('Complex marker requires numeric real and imag')
181181
}
182182
return this.leaf({ tag: 'complex', val: { real: object.real, imag: object.imag } })
183+
case 'Decimal':
184+
if (typeof object.value !== 'string') {
185+
throw new TypeError('Decimal marker requires a string value')
186+
}
187+
return this.leaf({ tag: 'decimal', val: object.value })
183188
case 'TimeDelta':
184189
return this.leaf({
185190
tag: 'timedelta',
@@ -537,6 +542,8 @@ function decodeNode(node: ValueNode, holder: number, child: (index: number, hold
537542
return { [TYPE_MARKER]: 'TimeDelta', ...node.val }
538543
case 'complex':
539544
return { [TYPE_MARKER]: 'Complex', ...node.val }
545+
case 'decimal':
546+
return { [TYPE_MARKER]: 'Decimal', value: node.val }
540547
case 'timezone':
541548
return { [TYPE_MARKER]: 'TimeZone', ...node.val }
542549
case 'exception':

‎crates/monty-pool/src/telemetry/tracing_json.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,8 @@ impl Serialize for JsonEncoded<'_> {
253253
// like logfire: `str(exc)`, which in Python is the message alone
254254
MontyNode::Exception { arg, .. } => s.serialize_str(arg.as_deref().unwrap_or_default()),
255255
MontyNode::Path(p) => s.serialize_str(p),
256+
// like logfire: `str(d)`, which keeps every digit a JSON number would round
257+
MontyNode::Decimal(d) => s.serialize_str(d),
256258
MontyNode::Cycle(_) => s.serialize_str("<circular reference>"),
257259
MontyNode::Repr(r) => s.serialize_str(r),
258260
MontyNode::Ellipsis => s.serialize_str("Ellipsis"),

0 commit comments

Comments
 (0)