diff --git a/CHANGELOG.md b/CHANGELOG.md index 50bf684c4..71166a9b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,8 @@ - IRI validation now detects multiple # fragments so these IRI's are skipped during toRDF. Fixes [toRdf#te111](https://w3c.github.io/json-ld-api/tests/toRdf-manifest#te111) and [toRdf#te112](https://w3c.github.io/json-ld-api/tests/toRdf-manifest#te112). - In `_create_node_map()`, ignored `@id: None` subjects are now dropped before they enter the node map to prevent `_graph_to_rdf()` from crashing when sorting mixed `None` and string keys. Fixes [toRdf#te122](https://w3c.github.io/json-ld-api/tests/toRdf-manifest#te122). - Use a helper for generalized N-Quads normalization in the test runner, since rdflib cannot parse blank-node predicates. Fixes [toRdf#te075](https://w3c.github.io/json-ld-api/tests/toRdf-manifest#te075). +- `jsonld.expand()`, `jsonld.to_rdf()` and the other operations no longer fail with an `OverflowError` for an integer too large for a double. `jsonld.to_rdf()` writes it as `INF` or `-INF`, the infinite `xsd:double` values, or, in `json-ld-1.0` mode and not typed as `xsd:double`, as an exact `xsd:integer`. Inside `@json` literals, `jsonld.to_rdf()` and `jsonld.normalize()` still raise `OverflowError` for such numbers, as RFC 8785 only allows numbers that fit in a double. +- `jsonld.to_rdf()` writes the `xsd:double` NaN as `NaN`, its XSD canonical form, instead of `NAN`, so `jsonld.normalize()` output changes for documents with such a value. ### Changed - **BREAKING**: Developer install, command execution, documentation, and release artifact diff --git a/lib/pyld/jsonld.py b/lib/pyld/jsonld.py index f8ffb1f72..cdc9159f8 100644 --- a/lib/pyld/jsonld.py +++ b/lib/pyld/jsonld.py @@ -4016,17 +4016,11 @@ def _object_to_rdf(self, item, issuer, triples, options): elif datatype == str(XSD.double): # since the previous branch did not activate, we know that `value` is not a float number. try: - float_value = float(value) + lexical = _canonicalize_double(value) except (ValueError, TypeError): # if `value` is not convertible to float, we will return it as-is. - return Literal(value, datatype=XSD.double, normalize=False) - else: - # we have a float, and canonicalization may proceed. - return Literal( - _canonicalize_double(float_value), - datatype=XSD.double, - normalize=False, - ) + lexical = value + return Literal(lexical, datatype=XSD.double, normalize=False) elif ( options['processingMode'] == 'json-ld-1.1' and _is_integer(value) @@ -6460,8 +6454,47 @@ def _is_double(v): return not isinstance(v, Integral) and isinstance(v, Real) and not float(v).is_integer() -def _canonicalize_double(value: float) -> str: - """Convert a float value to canonical lexical form of `xsd:double`.""" +def _to_double(value) -> float: + """ + Converts a number to a double. + + An integer that rounds beyond the largest double becomes positive or + negative infinity, as the lexical mapping of `xsd:double` in XML Schema + 1.1 Part 2 rounds it with floatingPointRound: + https://www.w3.org/TR/xmlschema11-2/#f-doubleLexmap + + :param value: the number or numeric string to convert; anything else + raises ValueError or TypeError, as float() does. + + :return: the double. + """ + try: + return float(value) + except OverflowError: + return math.inf if value > 0 else -math.inf + + +def _canonicalize_double(value: float | int | str) -> str: + """ + Converts a number to the canonical lexical form of `xsd:double`. + + A finite number is written as JSON-LD 1.1 describes it: + https://www.w3.org/TR/json-ld11-api/#data-round-tripping + + The special values are written 'INF', '-INF' and 'NaN', as + specialRepCanonicalMap in XML Schema 1.1 Part 2 maps them: + https://www.w3.org/TR/xmlschema11-2/#f-specValCanMap + + :param value: the number or numeric string to convert, as for + _to_double(). + + :return: the canonical lexical form. + """ + value = _to_double(value) + if math.isnan(value): + return 'NaN' + if math.isinf(value): + return 'INF' if value > 0 else '-INF' return re.sub(r'(\d)0*E\+?(-)?0*(\d)', r'\1E\2\3', (f'{value:1.15E}')) @@ -6474,7 +6507,7 @@ def _is_numeric(v): :return: True if the value is numeric, False if not. """ try: - float(v) + _to_double(v) return True except (TypeError, ValueError): return False diff --git a/tests/jsonld/test_expand.py b/tests/jsonld/test_expand.py index 6e63ceebc..05af4999c 100644 --- a/tests/jsonld/test_expand.py +++ b/tests/jsonld/test_expand.py @@ -692,3 +692,20 @@ def test_default_direction_null_reset_is_noop_when_unset(): ] assert jsonld.expand(input) == expected + + +def test_integer_beyond_double_range_is_kept(): + """ + Integers too large for a double should be kept as numbers during expansion + instead of raising OverflowError. + """ + input = {"@id": "http://example.com/s", "http://example.com/p": 10**309} + + expected = [ + { + "@id": "http://example.com/s", + "http://example.com/p": [{"@value": 10**309}], + }, + ] + + assert jsonld.expand(input) == expected diff --git a/tests/jsonld/test_to_rdf.py b/tests/jsonld/test_to_rdf.py index 4e080fea3..860752778 100644 --- a/tests/jsonld/test_to_rdf.py +++ b/tests/jsonld/test_to_rdf.py @@ -124,6 +124,85 @@ def test_large_integer_to_rdf_double_conversion_processing_mode(): """ assert nquads == expected + +def test_integer_beyond_double_range_to_rdf_is_infinite(): + """ + Integers too large for a double should be converted to INF and -INF + xsd:double values instead of raising OverflowError. + """ + for value, lexical in ((10**309, 'INF'), (-(10**309), '-INF')): + input = {'@id': 'http://example.com/s', 'http://example.com/p': value} + + nquads = jsonld.to_rdf(input, options={'format': 'application/n-quads'}) + + assert nquads == ( + f' "{lexical}"' + '^^ .\n\n' + ) + + +def test_integer_beyond_double_range_typed_as_double_to_rdf_is_infinite(): + """ + Integers too large for a double, typed as xsd:double, should be marked as infinite. + """ + input = { + '@id': 'http://example.com/s', + 'http://example.com/p': { + '@value': 10**309, + '@type': 'http://www.w3.org/2001/XMLSchema#double', + }, + } + + nquads = jsonld.to_rdf(input, options={'format': 'application/n-quads'}) + + assert nquads == ( + ' "INF"' + '^^ .\n\n' + ) + + +def test_integer_beyond_double_range_in_json_ld_1_0_stays_an_integer(): + """ + In json-ld-1.0 processing mode, integers too large for a double should be + kept as exact xsd:integer values. + """ + input = {'@id': 'http://example.com/s', 'http://example.com/p': 10**309} + + nquads = jsonld.to_rdf( + input, + options={'format': 'application/n-quads', 'processingMode': 'json-ld-1.0'}, + ) + + assert nquads == ( + f' "{10**309}"' + '^^ .\n\n' + ) + + +def test_double_special_values_to_rdf_use_xsd_canonical_forms(): + """ + The special xsd:double values should be written as NaN, INF and -INF, their + XSD canonical forms, whether given as floats or as xsd:double typed strings. + """ + double = 'http://www.w3.org/2001/XMLSchema#double' + for value, lexical in ( + (float('nan'), 'NaN'), + (float('inf'), 'INF'), + (float('-inf'), '-INF'), + ({'@value': 'NaN', '@type': double}, 'NaN'), + ({'@value': 'INF', '@type': double}, 'INF'), + ({'@value': '-INF', '@type': double}, '-INF'), + ): + input = {'@id': 'http://example.com/s', 'http://example.com/p': value} + + nquads = jsonld.to_rdf(input, options={'format': 'application/n-quads'}) + + assert nquads == ( + f' "{lexical}"' + f'^^<{double}> .\n\n' + ) + + def test_to_rdf_uses_identifier_issuer_option(): input = {'http://example.org/p': [{'@list': ['a', 'b']}]} issuer = IdentifierIssuer('_:custom')