@geastack/compiler 1.0.62 → 1.0.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/cli-emit.js +14 -5
  2. package/dist/conversion/dictionary-view.js +13 -2
  3. package/dist/conversion/document-record-view.d.ts +0 -1
  4. package/dist/conversion/document-record-view.js +30 -3
  5. package/dist/conversion/impossible-field-read.d.ts +9 -0
  6. package/dist/conversion/impossible-field-read.js +26 -0
  7. package/dist/conversion/nodes.d.ts +12 -0
  8. package/dist/conversion/nodes.js +106 -2
  9. package/dist/conversion/record-view.js +21 -0
  10. package/dist/ir/build.d.ts +5 -2
  11. package/dist/ir/build.js +9 -2
  12. package/dist/ir/callable-class-flow.js +233 -13
  13. package/dist/ir/certify/parallel-region.js +1 -0
  14. package/dist/ir/certify.js +32 -2
  15. package/dist/ir/dense-loops.js +8 -1
  16. package/dist/ir/hoist.js +15 -1
  17. package/dist/ir/host-template-conversions.js +12 -0
  18. package/dist/ir/lower-invocation.js +42 -2
  19. package/dist/ir/lower-property.js +2 -2
  20. package/dist/ir/model.d.ts +18 -6
  21. package/dist/ir/native-callable-data-reads.js +15 -2
  22. package/dist/ir/native-field-view-domains.d.ts +8 -0
  23. package/dist/ir/native-field-view-domains.js +44 -3
  24. package/dist/ir/native-field-view-facts.d.ts +2 -2
  25. package/dist/ir/native-field-view-facts.js +57 -13
  26. package/dist/ir/native-own-assignment.js +20 -2
  27. package/dist/ir/program-conversions.js +38 -7
  28. package/dist/ir/property-read-conversions.js +14 -5
  29. package/dist/ir/publish-native-field-view-facts.js +1 -1
  30. package/dist/ir/queries.js +2 -0
  31. package/dist/ir/read-only-dictionary.js +138 -15
  32. package/dist/ir/reflection-demand.js +7 -1
  33. package/dist/ir/shake.js +26 -6
  34. package/dist/ir/typed-property-access.d.ts +20 -0
  35. package/dist/ir/typed-property-access.js +56 -0
  36. package/dist/projection/bindings.js +14 -19
  37. package/dist/projection/fields.js +7 -1
  38. package/dist/projection/native-object-data.d.ts +8 -1
  39. package/dist/projection/native-object-data.js +16 -4
  40. package/dist/representation/derive.js +67 -1
  41. package/dist/representation/proxy-carriers.js +17 -2
  42. package/dist/representation/publish.js +34 -0
  43. package/dist/semantics/callable-own-data-slots.js +71 -6
  44. package/dist/semantics/model/operations.d.ts +15 -4
  45. package/dist/semantics/native-own-assignment.d.ts +3 -0
  46. package/dist/semantics/normalize/collection-bindings.js +2 -2
  47. package/dist/semantics/normalize/flow/array-element-continuation.d.ts +1 -1
  48. package/dist/semantics/normalize/flow/array-element-continuation.js +32 -9
  49. package/dist/semantics/normalize/flow/callable-reach.d.ts +3 -5
  50. package/dist/semantics/normalize/flow/callable-reach.js +3 -5
  51. package/dist/semantics/normalize/flow/component-solver.d.ts +2 -0
  52. package/dist/semantics/normalize/flow/component-solver.js +32 -6
  53. package/dist/semantics/normalize/flow/computed-key-set.js +53 -1
  54. package/dist/semantics/normalize/flow/source-value-session.js +16 -14
  55. package/dist/semantics/normalize/producers/invocations.js +40 -1
  56. package/dist/semantics/normalize/producers/native-own-assignment.js +12 -4
  57. package/dist/semantics/normalize/reachability.js +18 -8
  58. package/dist/semantics/normalize/structural-mutable-field.d.ts +1 -0
  59. package/dist/semantics/normalize/structural-mutable-field.js +170 -4
  60. package/dist/semantics/normalize/structural-parts.js +6 -1
  61. package/dist/semantics/normalize/structural-self-reference.d.ts +1 -1
  62. package/dist/semantics/normalize/structural-self-reference.js +9 -1
  63. package/dist/semantics/normalize/structural.js +10 -1
  64. package/dist/semantics/program.js +102 -1
  65. package/dist/targets/cpp/class-properties/emit-class-properties.js +9 -0
  66. package/dist/targets/cpp/emit-allocation.js +22 -1
  67. package/dist/targets/cpp/emit-callable.js +3 -3
  68. package/dist/targets/cpp/emit-exceptions.js +6 -0
  69. package/dist/targets/cpp/emit-narrowing.js +24 -2
  70. package/dist/targets/cpp/emit-native-field-view.d.ts +1 -1
  71. package/dist/targets/cpp/emit-native-field-view.js +37 -5
  72. package/dist/targets/cpp/emit-native-own-assignment.js +5 -1
  73. package/dist/targets/cpp/emit-record-view.js +6 -1
  74. package/dist/targets/cpp/emit-tonumber.d.ts +22 -11
  75. package/dist/targets/cpp/emit-tonumber.js +86 -25
  76. package/dist/targets/cpp/emit.js +3 -0
  77. package/dist/targets/cpp/host/emit-host-invoke.js +6 -6
  78. package/dist/targets/cpp/prototype/emit-prototype-array.js +13 -1
  79. package/dist/targets/cpp/records.js +15 -7
  80. package/dist/targets/cpp/recursive-containers.js +5 -1
  81. package/dist/targets/cpp/translation-unit.js +17 -2
  82. package/package.json +4 -2
  83. package/src/targets/cpp/runtime/gea_runtime.h +212 -7
@@ -2282,10 +2282,25 @@ const renderTranslationUnitSession = (input) => {
2282
2282
  // the session is open and named by address, which needs only its
2283
2283
  // declaration: the struct it returns is incomplete where the hook is.
2284
2284
  const dynamicArgumentViews = () => (input.programConversionRecipes ?? []).flatMap((recipe) => {
2285
- if (recipe.role !== 'dynamic-call-argument' || !('shapeId' in recipe.target))
2285
+ if (recipe.role !== 'dynamic-call-argument' || recipe.slot !== '' || !('shapeId' in recipe.target))
2286
2286
  return [];
2287
2287
  const { role, owner, slot, source, target } = recipe;
2288
- const load = programConversionText(programSite, role, owner, slot, source, target, 'gea_value');
2288
+ // A view boxed as its original arrives as the original's layout: each
2289
+ // origin the program views as this record reads back through that view.
2290
+ const origins = (input.programConversionRecipes ?? []).flatMap((candidate) => {
2291
+ if (candidate.role !== role || candidate.owner !== owner || !candidate.slot.startsWith('origin:'))
2292
+ return [];
2293
+ const type = cppTypeOf(candidate.source);
2294
+ const unboxed = `gea::detail::unboxValue<${type}>(gea_value, gea::Value::Tag::Object, "a dynamic call argument")`;
2295
+ const viewed = programConversionText(programSite, role, owner, candidate.slot, candidate.source, target, unboxed);
2296
+ if (viewed === null)
2297
+ throw createCppEmitBlockedError('runtime-helper:program-conversion-recipes', `${owner} has no view from ${type}`);
2298
+ return [
2299
+ `if (gea_value.tag() == gea::Value::Tag::Object && gea_value.payloadType() == gea::detail::payloadTypeTagFor<${type}>()) return ${viewed};`
2300
+ ];
2301
+ });
2302
+ const exact = programConversionText(programSite, role, owner, slot, source, target, 'gea_value');
2303
+ const load = exact === null ? null : origins.length === 0 ? exact : `([&]() -> ${cppTypeOf(target)} { ${origins.join(' ')} return ${exact}; })()`;
2289
2304
  const name = unitFunctionName('gea_dynamic_argument', (named) => `${cppTypeOf(target)} ${named}(const gea::Value& gea_value)`, `return ${load};`);
2290
2305
  if (name === null)
2291
2306
  throw createCppEmitBlockedError('runtime-helper:program-conversion-recipes', `${owner} has no unit for its argument view`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.62",
3
+ "version": "1.0.64",
4
4
  "description": "The geastack TypeScript-to-C++ compiler: one semantic spine, no source-shaped authority, no boxing of statically typed values.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -70,7 +70,9 @@
70
70
  "test:declaration-overlays": "node --import ./scripts/host-toolchain.mjs --test dist/semantics/declaration-overlay-transform.test.js",
71
71
  "test:recursive-native-carriers": "node test/recursive-native-carriers.mjs",
72
72
  "test:hot-path-shapes": "node test/hot-path-shapes.mjs",
73
- "build": "npm run architecture && tsc -p tsconfig.json && node scripts/mark-bins-executable.mjs && node scripts/build-checks.mjs",
73
+ "lint": "prettier --write --cache --log-level warn .",
74
+ "prepare": "node scripts/install-git-hooks.mjs",
75
+ "build": "npm run lint && npm run architecture && tsc -p tsconfig.json && node scripts/mark-bins-executable.mjs && node scripts/build-checks.mjs",
74
76
  "gate": "node scripts/emitted-gate.mjs",
75
77
  "test:release": "node scripts/release-suite.mjs",
76
78
  "release:check": "npm run check && npm run build && npm run gate && npm run test:release",
@@ -8729,6 +8729,15 @@ struct IsNativeCallableObject : std::false_type {};
8729
8729
  template <typename Result, typename... Arguments>
8730
8730
  struct IsNativeCallableObject<CallableObject<Result(Arguments...)>> : std::true_type {};
8731
8731
 
8732
+ /**
8733
+ * A recursive callable's named wrapper (`targets/cpp/recursive-containers.ts`:
8734
+ * `struct W final : CallableObject<R(A...)> { using Base = ...; }`). It adds
8735
+ * only a declaration name, so every boundary crossing is its base callable's.
8736
+ */
8737
+ template <typename T>
8738
+ concept RecursiveCallableWrapper = requires { typename T::Base; } && !std::is_same_v<T, typename T::Base> &&
8739
+ IsNativeCallableObject<typename T::Base>::value && std::is_base_of_v<typename T::Base, T>;
8740
+
8732
8741
 
8733
8742
  /**
8734
8743
  * `CallableObject`'s trailing-argument drop with the source thunk named in the
@@ -20116,6 +20125,10 @@ class Value {
20116
20125
  /** Boxes a value of any shape. The tag is stated by the caller because C++ type identity is not JavaScript type identity -- a `std::string` is a JS string, but a `gea::Optional<double>` is a JS number or `undefined` depending on the presence flag, and only the emitter knows which. */
20117
20126
  template <typename T>
20118
20127
  static Value box(Tag tag, T&& value) {
20128
+ // A recursive callable wrapper boxes as the callable it is: its base
20129
+ // carries the call table and the function identity.
20130
+ if constexpr (detail::RecursiveCallableWrapper<std::decay_t<T>>)
20131
+ return box(tag, static_cast<const typename std::decay_t<T>::Base&>(value));
20119
20132
  // A Document that views another object (`gea::dictionary::aliasOf`) boxes
20120
20133
  // as that object: `any` sees the instance itself -- its identity, its
20121
20134
  // class, its prototype -- and not a table standing in for it.
@@ -23418,6 +23431,18 @@ inline Value getBuiltinModule(std::string_view specifier) {
23418
23431
  return Value();
23419
23432
  }
23420
23433
 
23434
+ template <auto Loader, typename Namespace>
23435
+ struct ModuleNamespaceSlot {};
23436
+
23437
+ // An ES module has one namespace object per realm: the first record built
23438
+ // from its export cells is the one every later lookup answers.
23439
+ template <auto Loader, typename Namespace>
23440
+ inline Namespace moduleNamespace(const Namespace& fresh) {
23441
+ auto& slot = ::gea::detail::realmSlot<ModuleNamespaceSlot<Loader, Namespace>, std::optional<Namespace>>();
23442
+ if (!slot) slot = fresh;
23443
+ return *slot;
23444
+ }
23445
+
23421
23446
  inline Value requireBinding() {
23422
23447
  // Static calls lower to module-record edges. A require value that escapes
23423
23448
  // that proof is still a real wrapper cell, but it cannot consult a process
@@ -25029,6 +25054,51 @@ struct DynamicCarrier<AsyncGenerator<T, TReturn, TNext>> {
25029
25054
  }
25030
25055
  };
25031
25056
 
25057
+ /**
25058
+ * A sync iterator read out of a box: the exact `Iterator<E>` another native
25059
+ * frame boxed comes back as itself; any other object is a hand-written
25060
+ * iterator, viewed through `Iterator::ProtocolSteps` over that object's own
25061
+ * `next`/`return` (ECMA-262 7.4.4 IteratorNext, 7.4.11 IteratorClose), with
25062
+ * each yielded value read as `E` by its own exact carrier. A generator method
25063
+ * a runtime-keyed write shadowed is the shape: its shadow is whatever function
25064
+ * the program stored, and the typed call site needs the cursor its declared
25065
+ * type names.
25066
+ */
25067
+ template <typename E, typename TReturn, typename TNext>
25068
+ struct DynamicCarrier<Iterator<E, TReturn, TNext>> {
25069
+ using Self = Iterator<E, TReturn, TNext>;
25070
+ using Completion = typename Self::ReturnStorage;
25071
+ static constexpr bool supported = DynamicCarrier<E>::supported && (std::is_void_v<TReturn> || DynamicCarrier<TReturn>::supported);
25072
+ static Value out(const Self& value) { return Value::box(Value::Tag::Object, value); }
25073
+ static bool accepts(const Value& value) { return value.tag() == Value::Tag::Object && value.payloadType() == payloadTypeTagFor<Self>(); }
25074
+ static Self in(const Value& value, std::size_t position) {
25075
+ if (value.tag() == Value::Tag::Undefined) refuseMissingCallArgument(position);
25076
+ if (accepts(value)) return value.as<Self>();
25077
+ if (value.tag() != Value::Tag::Object && value.tag() != Value::Tag::Function) refusePayloadMismatch("an iterator read out of a dynamic value");
25078
+ auto steps = gea::makeRef<typename Self::ProtocolSteps>();
25079
+ steps->next = [value](E& out, [[maybe_unused]] Completion& completion) -> bool {
25080
+ const Value result = value.getProperty(PropertyKey::string("next")).callWithReceiver(NativeCallReceiver::fromValue(value), {});
25081
+ if (result.tag() != Value::Tag::Object && result.tag() != Value::Tag::Function)
25082
+ gea::host::throwRuntimeError("TypeError", "Iterator result is not an object");
25083
+ const Value item = result.getProperty(PropertyKey::string("value"));
25084
+ if (gea::host::detail::toBoolean(result.getProperty(PropertyKey::string("done")))) {
25085
+ if constexpr (!std::is_void_v<TReturn>) {
25086
+ if (item.tag() != Value::Tag::Undefined) completion = DynamicCarrier<TReturn>::in(item, 0);
25087
+ }
25088
+ return false;
25089
+ }
25090
+ out = DynamicCarrier<E>::in(item, 0);
25091
+ return true;
25092
+ };
25093
+ steps->finish = [value]() {
25094
+ const Value close = value.getProperty(PropertyKey::string("return"));
25095
+ if (close.tag() != Value::Tag::Undefined && close.tag() != Value::Tag::Null)
25096
+ (void)close.callWithReceiver(NativeCallReceiver::fromValue(value), {});
25097
+ };
25098
+ return Self(std::move(steps));
25099
+ }
25100
+ };
25101
+
25032
25102
  template <>
25033
25103
  struct DynamicCarrier<gea::Undefined> {
25034
25104
  static constexpr bool supported = true;
@@ -25504,6 +25574,35 @@ struct DynamicCallableCarrier<TaggedUnion<Arms...>> {
25504
25574
  }
25505
25575
  };
25506
25576
 
25577
+ /**
25578
+ * A recursive callable's named wrapper (`targets/cpp/recursive-containers.ts`:
25579
+ * `struct W final : CallableObject<R(A...)>`, the name a self-referencing
25580
+ * function type needs to close its own equation). It crosses the boundary
25581
+ * exactly as its base callable does -- the wrapper adds no state, only the
25582
+ * declaration name -- so every rule is the base's, and a read rewraps.
25583
+ */
25584
+ template <typename T>
25585
+ requires RecursiveCallableWrapper<T>
25586
+ struct DynamicCarrier<T> {
25587
+ using Base = typename T::Base;
25588
+ static constexpr bool supported = DynamicCarrier<Base>::supported;
25589
+ static Value out(const T& value) { return DynamicCarrier<Base>::out(value); }
25590
+ static bool accepts(const Value& value) { return DynamicCarrier<Base>::accepts(value); }
25591
+ static T in(const Value& value, std::size_t position) { return T(DynamicCarrier<Base>::in(value, position)); }
25592
+ template <typename... Factory>
25593
+ static T inWithReceiver(const Value& value, std::size_t position, Factory... factory) {
25594
+ return T(DynamicCarrier<Base>::inWithReceiver(value, position, factory...));
25595
+ }
25596
+ template <std::size_t RestFrom, bool ActualArguments = false>
25597
+ static T inWithRest(const Value& value, std::size_t position) {
25598
+ return T(DynamicCarrier<Base>::template inWithRest<RestFrom, ActualArguments>(value, position));
25599
+ }
25600
+ template <std::size_t RestFrom, bool ActualArguments = false, typename... Factory>
25601
+ static T inWithReceiverAndRest(const Value& value, std::size_t position, Factory... factory) {
25602
+ return T(DynamicCarrier<Base>::template inWithReceiverAndRest<RestFrom, ActualArguments>(value, position, factory...));
25603
+ }
25604
+ };
25605
+
25507
25606
  /**
25508
25607
  * A class constructor object crossing the boundary: the `this` of a static
25509
25608
  * method reached through a computed read (`C[String(k)](...)` boxes the
@@ -30556,7 +30655,16 @@ bool nativeObjectDataReadNative(const gea::Ref<Receiver>& object, const Property
30556
30655
  const auto table = detail::expandoFor(nativePropertyAnchor(object), false);
30557
30656
  const PropertyDescriptor* found = table ? table->ownProperty(key) : nullptr;
30558
30657
  if (found == nullptr) return read.assign(Undefined{});
30559
- if (!found->isAccessor()) return found->nativeValue && found->nativeValue.read(read);
30658
+ // A key the source layout lacks was installed by a write through a dynamic
30659
+ // receiver, so no reader's routes can name the carrier it was stored in.
30660
+ // The stored carrier answers when the reader takes it; otherwise a reader
30661
+ // certified for a `Value` route reads the property as `[[Get]]` would and
30662
+ // unboxes it checked. Any other reader still refuses.
30663
+ if (!found->isAccessor()) {
30664
+ if (!found->nativeValue) return read.assign(found->value);
30665
+ if (found->nativeValue.read(read)) return true;
30666
+ return read.acceptsExact<Value, NativeFieldLeafPolicy>() && read.assign(found->nativeValue.materialize());
30667
+ }
30560
30668
  const auto handled = table->readNativeAccessor(key, NativeCallReceiver::object(object), read);
30561
30669
  return handled && *handled;
30562
30670
  }
@@ -40821,6 +40929,99 @@ inline std::string formatDouble(const char *fmt, int precision, double value) {
40821
40929
  return std::string(buf.data(), static_cast<std::size_t>(written));
40822
40930
  }
40823
40931
 
40932
+ // How many digits follow the point in the exact decimal expansion of a finite
40933
+ // non-negative double: one per binary fraction bit, since 2^-n has exactly n.
40934
+ inline int binaryFractionDigits(double magnitude) {
40935
+ if (magnitude == 0.0) return 0;
40936
+ int exponent = 0;
40937
+ const double fraction = std::frexp(magnitude, &exponent);
40938
+ const auto mantissa = static_cast<std::uint64_t>(std::ldexp(fraction, 53));
40939
+ const int digits = 53 - exponent - std::countr_zero(mantissa);
40940
+ return digits > 0 ? digits : 0;
40941
+ }
40942
+
40943
+ /**
40944
+ * `formatDouble` of a finite non-negative `magnitude`, except that an exact tie
40945
+ * rounds up. `toFixed`, `toExponential` and `toPrecision` each say "if there
40946
+ * are two such n, pick the larger n"; printf (and the compact formatter, which
40947
+ * matches it) breaks that tie to even, so `(2.5).toPrecision(1)` would read "2".
40948
+ *
40949
+ * Nothing else may be adjusted: printf already rounds the exact binary value
40950
+ * once. Pre-scaling (`round(x * 10^d) / 10^d`) rounds the product as well and
40951
+ * manufactures ties that are not there -- 260042689.0618805 is below the
40952
+ * midpoint by 9e-10, its product with 1e6 lands on .5, and toFixed(6) read
40953
+ * "...881" where the clause gives "...880".
40954
+ *
40955
+ * The rounding digit sits at 10^-(fractionPlace) and a tie means the exact
40956
+ * expansion ends there, on a 5. Only a value with exactly that many binary
40957
+ * fraction bits can (or none, when the place is integral), so almost every
40958
+ * call returns after one print. A real tie is rounded up on the exact digits
40959
+ * themselves. Printing the next double up instead would be wrong: above 2^40 or
40960
+ * so its distance is itself a kept digit, and 1143989562988.28125 read ".2815".
40961
+ */
40962
+ inline bool incrementDecimal(std::string &digits) {
40963
+ for (std::size_t at = digits.size(); at-- > 0;) {
40964
+ if (digits[at] == '.') continue;
40965
+ if (digits[at] != '9') {
40966
+ ++digits[at];
40967
+ return false;
40968
+ }
40969
+ digits[at] = '0';
40970
+ }
40971
+ return true;
40972
+ }
40973
+
40974
+ inline std::string formatMagnitudeTiesUp(bool scientific, int precision, double magnitude) {
40975
+ const char *fmt = scientific ? "%.*e" : "%.*f";
40976
+ std::string out = formatDouble(fmt, precision, magnitude);
40977
+ if (magnitude == 0.0) return out;
40978
+ const int fractionDigits = binaryFractionDigits(magnitude);
40979
+ if (!scientific) {
40980
+ if (fractionDigits != precision + 1) return out;
40981
+ // Exactly as many digits as the expansion has, so this print is exact.
40982
+ std::string kept = formatDouble(fmt, precision + 1, magnitude);
40983
+ if (kept.back() != '5') return out;
40984
+ kept.pop_back();
40985
+ if (kept.back() == '.') kept.pop_back();
40986
+ if (incrementDecimal(kept)) kept.insert(kept.begin(), '1');
40987
+ return kept;
40988
+ }
40989
+ // Digit p+1 of d.ddd x 10^E sits at fraction place p+1-E. `out`'s exponent
40990
+ // is E, or E+1 when its rounding carried out of the first digit.
40991
+ const int printed = std::atoi(out.c_str() + out.find('e') + 1);
40992
+ const auto tiePossible = [&](int exponent) {
40993
+ const int place = precision + 1 - exponent;
40994
+ return place > 0 ? fractionDigits == place : fractionDigits == 0;
40995
+ };
40996
+ if (!tiePossible(printed) && !tiePossible(printed - 1)) return out;
40997
+ std::string mantissa;
40998
+ int exponent = 0;
40999
+ if (fractionDigits > 0) {
41000
+ // Exact (it carries the whole expansion), so its exponent is the true E.
41001
+ const std::string wider = formatDouble(fmt, precision + 1, magnitude);
41002
+ const std::size_t marker = wider.find('e');
41003
+ exponent = std::atoi(wider.c_str() + marker + 1);
41004
+ if (wider[marker - 1] != '5' || precision + 1 - exponent != fractionDigits) return out;
41005
+ mantissa = wider.substr(0, marker - 1);
41006
+ } else {
41007
+ // An integer: its full digits decide, the rounding digit at index p+1.
41008
+ const std::string whole = formatDouble("%.*f", 0, magnitude);
41009
+ const std::size_t at = static_cast<std::size_t>(precision) + 1;
41010
+ if (at >= whole.size() || whole[at] != '5' || whole.find_first_not_of('0', at + 1) != std::string::npos) return out;
41011
+ exponent = static_cast<int>(whole.size()) - 1;
41012
+ mantissa = whole.substr(0, 1);
41013
+ if (precision > 0) mantissa += "." + whole.substr(1, static_cast<std::size_t>(precision));
41014
+ }
41015
+ if (mantissa.back() == '.') mantissa.pop_back();
41016
+ if (incrementDecimal(mantissa)) {
41017
+ // "9.99" carried out to "0.00": it is 1.00 one decade up.
41018
+ mantissa[0] = '1';
41019
+ ++exponent;
41020
+ }
41021
+ const int absolute = exponent < 0 ? -exponent : exponent;
41022
+ return mantissa + (exponent < 0 ? "e-" : "e+") + (absolute < 10 ? "0" : "") + std::to_string(absolute);
41023
+ }
41024
+
40824
41025
  /**
40825
41026
  * Whether `std::to_chars(char*, char*, double, std::chars_format)` may be NAMED.
40826
41027
  *
@@ -41149,12 +41350,14 @@ inline std::string toFixed(double value, double digits) {
41149
41350
  // Taking the sign off before the comparison is the specification's own
41150
41351
  // order, and it matters: `(-1e21).toFixed(2)` is "-1e+21", not the fixed
41151
41352
  // expansion a `value >= 1e21` test would leave it with.
41353
+ //
41354
+ // `fabs` rather than `-value`: -0 is not < 0, so it prints "0.00", and its
41355
+ // sign bit must not reach printf.
41152
41356
  const bool negative = value < 0;
41153
- const double magnitude = negative ? -value : value;
41357
+ const double magnitude = std::fabs(value);
41154
41358
  if (magnitude >= 1e21) return negative ? std::string("-") + toString(magnitude) : toString(magnitude);
41155
- double scale = std::pow(10.0, d);
41156
- double rounded = std::round(value * scale) / scale;
41157
- return internal::formatDouble("%.*f", d, rounded);
41359
+ const std::string out = internal::formatMagnitudeTiesUp(false, d, magnitude);
41360
+ return negative ? "-" + out : out;
41158
41361
  }
41159
41362
 
41160
41363
  inline std::string toExponential(double value, double digits) {
@@ -41163,7 +41366,9 @@ inline std::string toExponential(double value, double digits) {
41163
41366
  int d = static_cast<int>(digits);
41164
41367
  if (d < 0) d = 0;
41165
41368
  if (d > 100) d = 100;
41166
- std::string out = internal::formatDouble("%.*e", d, value);
41369
+ // Sign handled as in `toFixed`: (-0).toExponential(1) is "0.0e+0".
41370
+ std::string out = internal::formatMagnitudeTiesUp(true, d, std::fabs(value));
41371
+ if (value < 0) out.insert(out.begin(), '-');
41167
41372
  internal::normalizeExponent(out);
41168
41373
  return out;
41169
41374
  }
@@ -41205,7 +41410,7 @@ inline std::string toPrecision(double value, double digits) {
41205
41410
  } else {
41206
41411
  // "%.*e" with p-1 fractional digits is exactly step 7's n and e: p
41207
41412
  // significant digits, correctly rounded once, plus the decimal exponent.
41208
- const std::string scientific = internal::formatDouble("%.*e", p - 1, magnitude);
41413
+ const std::string scientific = internal::formatMagnitudeTiesUp(true, p - 1, magnitude);
41209
41414
  const std::size_t marker = scientific.find('e');
41210
41415
  if (marker == std::string::npos) return negative ? std::string("-") + scientific : scientific;
41211
41416
  exponent = std::atoi(scientific.c_str() + marker + 1);