llvm-project
972 строки · 35.2 Кб
1//===-- runtime/edit-output.cpp -------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "edit-output.h"
10#include "emit-encoded.h"
11#include "utf.h"
12#include "flang/Common/real.h"
13#include "flang/Common/uint128.h"
14#include <algorithm>
15
16namespace Fortran::runtime::io {
17RT_OFFLOAD_API_GROUP_BEGIN
18
19// In output statement, add a space between numbers and characters.
20static RT_API_ATTRS void addSpaceBeforeCharacter(IoStatementState &io) {
21if (auto *list{io.get_if<ListDirectedStatementState<Direction::Output>>()}) {
22list->set_lastWasUndelimitedCharacter(false);
23}
24}
25
26// B/O/Z output of arbitrarily sized data emits a binary/octal/hexadecimal
27// representation of what is interpreted to be a single unsigned integer value.
28// When used with character data, endianness is exposed.
29template <int LOG2_BASE>
30static RT_API_ATTRS bool EditBOZOutput(IoStatementState &io,
31const DataEdit &edit, const unsigned char *data0, std::size_t bytes) {
32addSpaceBeforeCharacter(io);
33int digits{static_cast<int>((bytes * 8) / LOG2_BASE)};
34int get{static_cast<int>(bytes * 8) - digits * LOG2_BASE};
35if (get > 0) {
36++digits;
37} else {
38get = LOG2_BASE;
39}
40int shift{7};
41int increment{isHostLittleEndian ? -1 : 1};
42const unsigned char *data{data0 + (isHostLittleEndian ? bytes - 1 : 0)};
43int skippedZeroes{0};
44int digit{0};
45// The same algorithm is used to generate digits for real (below)
46// as well as for generating them only to skip leading zeroes (here).
47// Bits are copied one at a time from the source data.
48// TODO: Multiple bit copies for hexadecimal, where misalignment
49// is not possible; or for octal when all 3 bits come from the
50// same byte.
51while (bytes > 0) {
52if (get == 0) {
53if (digit != 0) {
54break; // first nonzero leading digit
55}
56++skippedZeroes;
57get = LOG2_BASE;
58} else if (shift < 0) {
59data += increment;
60--bytes;
61shift = 7;
62} else {
63digit = 2 * digit + ((*data >> shift--) & 1);
64--get;
65}
66}
67// Emit leading spaces and zeroes; detect field overflow
68int leadingZeroes{0};
69int editWidth{edit.width.value_or(0)};
70int significant{digits - skippedZeroes};
71if (edit.digits && significant <= *edit.digits) { // Bw.m, Ow.m, Zw.m
72if (*edit.digits == 0 && bytes == 0) {
73editWidth = std::max(1, editWidth);
74} else {
75leadingZeroes = *edit.digits - significant;
76}
77} else if (bytes == 0) {
78leadingZeroes = 1;
79}
80int subTotal{leadingZeroes + significant};
81int leadingSpaces{std::max(0, editWidth - subTotal)};
82if (editWidth > 0 && leadingSpaces + subTotal > editWidth) {
83return EmitRepeated(io, '*', editWidth);
84}
85if (!(EmitRepeated(io, ' ', leadingSpaces) &&
86EmitRepeated(io, '0', leadingZeroes))) {
87return false;
88}
89// Emit remaining digits
90while (bytes > 0) {
91if (get == 0) {
92char ch{static_cast<char>(digit >= 10 ? 'A' + digit - 10 : '0' + digit)};
93if (!EmitAscii(io, &ch, 1)) {
94return false;
95}
96get = LOG2_BASE;
97digit = 0;
98} else if (shift < 0) {
99data += increment;
100--bytes;
101shift = 7;
102} else {
103digit = 2 * digit + ((*data >> shift--) & 1);
104--get;
105}
106}
107return true;
108}
109
110template <int KIND>
111bool RT_API_ATTRS EditIntegerOutput(IoStatementState &io, const DataEdit &edit,
112common::HostSignedIntType<8 * KIND> n) {
113addSpaceBeforeCharacter(io);
114char buffer[130], *end{&buffer[sizeof buffer]}, *p{end};
115bool isNegative{n < 0};
116using Unsigned = common::HostUnsignedIntType<8 * KIND>;
117Unsigned un{static_cast<Unsigned>(n)};
118int signChars{0};
119switch (edit.descriptor) {
120case DataEdit::ListDirected:
121case 'G':
122case 'I':
123if (isNegative) {
124un = -un;
125}
126if (isNegative || (edit.modes.editingFlags & signPlus)) {
127signChars = 1; // '-' or '+'
128}
129while (un > 0) {
130auto quotient{un / 10u};
131*--p = '0' + static_cast<int>(un - Unsigned{10} * quotient);
132un = quotient;
133}
134break;
135case 'B':
136return EditBOZOutput<1>(
137io, edit, reinterpret_cast<const unsigned char *>(&n), KIND);
138case 'O':
139return EditBOZOutput<3>(
140io, edit, reinterpret_cast<const unsigned char *>(&n), KIND);
141case 'Z':
142return EditBOZOutput<4>(
143io, edit, reinterpret_cast<const unsigned char *>(&n), KIND);
144case 'L':
145return EditLogicalOutput(io, edit, n != 0 ? true : false);
146case 'A': // legacy extension
147return EditCharacterOutput(
148io, edit, reinterpret_cast<char *>(&n), sizeof n);
149default:
150io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
151"Data edit descriptor '%c' may not be used with an INTEGER data item",
152edit.descriptor);
153return false;
154}
155
156int digits = end - p;
157int leadingZeroes{0};
158int editWidth{edit.width.value_or(0)};
159if (edit.descriptor == 'I' && edit.digits && digits <= *edit.digits) {
160// Only Iw.m can produce leading zeroes, not Gw.d (F'202X 13.7.5.2.2)
161if (*edit.digits == 0 && n == 0) {
162// Iw.0 with zero value: output field must be blank. For I0.0
163// and a zero value, emit one blank character.
164signChars = 0; // in case of SP
165editWidth = std::max(1, editWidth);
166} else {
167leadingZeroes = *edit.digits - digits;
168}
169} else if (n == 0) {
170leadingZeroes = 1;
171}
172int subTotal{signChars + leadingZeroes + digits};
173int leadingSpaces{std::max(0, editWidth - subTotal)};
174if (editWidth > 0 && leadingSpaces + subTotal > editWidth) {
175return EmitRepeated(io, '*', editWidth);
176}
177if (edit.IsListDirected()) {
178int total{std::max(leadingSpaces, 1) + subTotal};
179if (io.GetConnectionState().NeedAdvance(static_cast<std::size_t>(total)) &&
180!io.AdvanceRecord()) {
181return false;
182}
183leadingSpaces = 1;
184}
185return EmitRepeated(io, ' ', leadingSpaces) &&
186EmitAscii(io, n < 0 ? "-" : "+", signChars) &&
187EmitRepeated(io, '0', leadingZeroes) && EmitAscii(io, p, digits);
188}
189
190// Formats the exponent (see table 13.1 for all the cases)
191RT_API_ATTRS const char *RealOutputEditingBase::FormatExponent(
192int expo, const DataEdit &edit, int &length) {
193char *eEnd{&exponent_[sizeof exponent_]};
194char *exponent{eEnd};
195for (unsigned e{static_cast<unsigned>(std::abs(expo))}; e > 0;) {
196unsigned quotient{e / 10u};
197*--exponent = '0' + e - 10 * quotient;
198e = quotient;
199}
200bool overflow{false};
201if (edit.expoDigits) {
202if (int ed{*edit.expoDigits}) { // Ew.dEe with e > 0
203overflow = exponent + ed < eEnd;
204while (exponent > exponent_ + 2 /*E+*/ && exponent + ed > eEnd) {
205*--exponent = '0';
206}
207} else if (exponent == eEnd) {
208*--exponent = '0'; // Ew.dE0 with zero-valued exponent
209}
210} else if (edit.variation == 'X') {
211if (expo == 0) {
212*--exponent = '0'; // EX without Ee and zero-valued exponent
213}
214} else {
215// Ensure at least two exponent digits unless EX
216while (exponent + 2 > eEnd) {
217*--exponent = '0';
218}
219}
220*--exponent = expo < 0 ? '-' : '+';
221if (edit.variation == 'X') {
222*--exponent = 'P';
223} else if (edit.expoDigits || edit.IsListDirected() || exponent + 3 == eEnd) {
224*--exponent = edit.descriptor == 'D' ? 'D' : 'E'; // not 'G' or 'Q'
225}
226length = eEnd - exponent;
227return overflow ? nullptr : exponent;
228}
229
230RT_API_ATTRS bool RealOutputEditingBase::EmitPrefix(
231const DataEdit &edit, std::size_t length, std::size_t width) {
232if (edit.IsListDirected()) {
233int prefixLength{edit.descriptor == DataEdit::ListDirectedRealPart ? 2
234: edit.descriptor == DataEdit::ListDirectedImaginaryPart ? 0
235: 1};
236int suffixLength{edit.descriptor == DataEdit::ListDirectedRealPart ||
237edit.descriptor == DataEdit::ListDirectedImaginaryPart
238? 1
239: 0};
240length += prefixLength + suffixLength;
241ConnectionState &connection{io_.GetConnectionState()};
242return (!connection.NeedAdvance(length) || io_.AdvanceRecord()) &&
243EmitAscii(io_, " (", prefixLength);
244} else if (width > length) {
245return EmitRepeated(io_, ' ', width - length);
246} else {
247return true;
248}
249}
250
251RT_API_ATTRS bool RealOutputEditingBase::EmitSuffix(const DataEdit &edit) {
252if (edit.descriptor == DataEdit::ListDirectedRealPart) {
253return EmitAscii(
254io_, edit.modes.editingFlags & decimalComma ? ";" : ",", 1);
255} else if (edit.descriptor == DataEdit::ListDirectedImaginaryPart) {
256return EmitAscii(io_, ")", 1);
257} else {
258return true;
259}
260}
261
262template <int KIND>
263RT_API_ATTRS decimal::ConversionToDecimalResult
264RealOutputEditing<KIND>::ConvertToDecimal(
265int significantDigits, enum decimal::FortranRounding rounding, int flags) {
266auto converted{decimal::ConvertToDecimal<binaryPrecision>(buffer_,
267sizeof buffer_, static_cast<enum decimal::DecimalConversionFlags>(flags),
268significantDigits, rounding, x_)};
269if (!converted.str) { // overflow
270io_.GetIoErrorHandler().Crash(
271"RealOutputEditing::ConvertToDecimal: buffer size %zd was insufficient",
272sizeof buffer_);
273}
274return converted;
275}
276
277static RT_API_ATTRS bool IsInfOrNaN(const char *p, int length) {
278if (!p || length < 1) {
279return false;
280}
281if (*p == '-' || *p == '+') {
282if (length == 1) {
283return false;
284}
285++p;
286}
287return *p == 'I' || *p == 'N';
288}
289
290// 13.7.2.3.3 in F'2018
291template <int KIND>
292RT_API_ATTRS bool RealOutputEditing<KIND>::EditEorDOutput(
293const DataEdit &edit) {
294addSpaceBeforeCharacter(io_);
295int editDigits{edit.digits.value_or(0)}; // 'd' field
296int editWidth{edit.width.value_or(0)}; // 'w' field
297int significantDigits{editDigits};
298int flags{0};
299if (edit.modes.editingFlags & signPlus) {
300flags |= decimal::AlwaysSign;
301}
302int scale{edit.modes.scale}; // 'kP' value
303if (editWidth == 0) { // "the processor selects the field width"
304if (edit.digits.has_value()) { // E0.d
305if (editDigits == 0 && scale <= 0) { // E0.0
306significantDigits = 1;
307}
308} else { // E0
309flags |= decimal::Minimize;
310significantDigits =
311sizeof buffer_ - 5; // sign, NUL, + 3 extra for EN scaling
312}
313}
314bool isEN{edit.variation == 'N'};
315bool isES{edit.variation == 'S'};
316int zeroesAfterPoint{0};
317if (isEN) {
318scale = IsZero() ? 1 : 3;
319significantDigits += scale;
320} else if (isES) {
321scale = 1;
322++significantDigits;
323} else if (scale < 0) {
324if (scale <= -editDigits) {
325io_.GetIoErrorHandler().SignalError(IostatBadScaleFactor,
326"Scale factor (kP) %d cannot be less than -d (%d)", scale,
327-editDigits);
328return false;
329}
330zeroesAfterPoint = -scale;
331significantDigits = std::max(0, significantDigits - zeroesAfterPoint);
332} else if (scale > 0) {
333if (scale >= editDigits + 2) {
334io_.GetIoErrorHandler().SignalError(IostatBadScaleFactor,
335"Scale factor (kP) %d cannot be greater than d+2 (%d)", scale,
336editDigits + 2);
337return false;
338}
339++significantDigits;
340scale = std::min(scale, significantDigits + 1);
341} else if (edit.digits.value_or(1) == 0 && !edit.variation) {
342// F'2023 13.7.2.3.3 p5; does not apply to Gw.0(Ee) or E0(no d)
343io_.GetIoErrorHandler().SignalError(IostatErrorInFormat,
344"Output edit descriptor %cw.d must have d>0", edit.descriptor);
345return false;
346}
347// In EN editing, multiple attempts may be necessary, so this is a loop.
348while (true) {
349decimal::ConversionToDecimalResult converted{
350ConvertToDecimal(significantDigits, edit.modes.round, flags)};
351if (IsInfOrNaN(converted.str, static_cast<int>(converted.length))) {
352return editWidth > 0 &&
353converted.length + trailingBlanks_ >
354static_cast<std::size_t>(editWidth)
355? EmitRepeated(io_, '*', editWidth)
356: EmitPrefix(edit, converted.length, editWidth) &&
357EmitAscii(io_, converted.str, converted.length) &&
358EmitRepeated(io_, ' ', trailingBlanks_) && EmitSuffix(edit);
359}
360if (!IsZero()) {
361converted.decimalExponent -= scale;
362}
363if (isEN) {
364// EN mode: we need an effective exponent field that is
365// a multiple of three.
366if (int modulus{converted.decimalExponent % 3}; modulus != 0) {
367if (significantDigits > 1) {
368--significantDigits;
369--scale;
370continue;
371}
372// Rounded nines up to a 1.
373scale += modulus;
374converted.decimalExponent -= modulus;
375}
376if (scale > 3) {
377int adjust{3 * (scale / 3)};
378scale -= adjust;
379converted.decimalExponent += adjust;
380} else if (scale < 1) {
381int adjust{3 - 3 * (scale / 3)};
382scale += adjust;
383converted.decimalExponent -= adjust;
384}
385significantDigits = editDigits + scale;
386}
387// Format the exponent (see table 13.1 for all the cases)
388int expoLength{0};
389const char *exponent{
390FormatExponent(converted.decimalExponent, edit, expoLength)};
391int signLength{*converted.str == '-' || *converted.str == '+' ? 1 : 0};
392int convertedDigits{static_cast<int>(converted.length) - signLength};
393int zeroesBeforePoint{std::max(0, scale - convertedDigits)};
394int digitsBeforePoint{std::max(0, scale - zeroesBeforePoint)};
395int digitsAfterPoint{convertedDigits - digitsBeforePoint};
396int trailingZeroes{flags & decimal::Minimize
397? 0
398: std::max(0,
399significantDigits - (convertedDigits + zeroesBeforePoint))};
400int totalLength{signLength + digitsBeforePoint + zeroesBeforePoint +
4011 /*'.'*/ + zeroesAfterPoint + digitsAfterPoint + trailingZeroes +
402expoLength};
403int width{editWidth > 0 ? editWidth : totalLength};
404if (totalLength > width || !exponent) {
405return EmitRepeated(io_, '*', width);
406}
407if (totalLength < width && digitsBeforePoint == 0 &&
408zeroesBeforePoint == 0) {
409zeroesBeforePoint = 1;
410++totalLength;
411}
412if (totalLength < width && editWidth == 0) {
413width = totalLength;
414}
415return EmitPrefix(edit, totalLength, width) &&
416EmitAscii(io_, converted.str, signLength + digitsBeforePoint) &&
417EmitRepeated(io_, '0', zeroesBeforePoint) &&
418EmitAscii(io_, edit.modes.editingFlags & decimalComma ? "," : ".", 1) &&
419EmitRepeated(io_, '0', zeroesAfterPoint) &&
420EmitAscii(io_, converted.str + signLength + digitsBeforePoint,
421digitsAfterPoint) &&
422EmitRepeated(io_, '0', trailingZeroes) &&
423EmitAscii(io_, exponent, expoLength) && EmitSuffix(edit);
424}
425}
426
427// 13.7.2.3.2 in F'2018
428template <int KIND>
429RT_API_ATTRS bool RealOutputEditing<KIND>::EditFOutput(const DataEdit &edit) {
430addSpaceBeforeCharacter(io_);
431int fracDigits{edit.digits.value_or(0)}; // 'd' field
432const int editWidth{edit.width.value_or(0)}; // 'w' field
433enum decimal::FortranRounding rounding{edit.modes.round};
434int flags{0};
435if (edit.modes.editingFlags & signPlus) {
436flags |= decimal::AlwaysSign;
437}
438if (editWidth == 0) { // "the processor selects the field width"
439if (!edit.digits.has_value()) { // F0
440flags |= decimal::Minimize;
441fracDigits = sizeof buffer_ - 2; // sign & NUL
442}
443}
444bool emitTrailingZeroes{!(flags & decimal::Minimize)};
445// Multiple conversions may be needed to get the right number of
446// effective rounded fractional digits.
447bool canIncrease{true};
448for (int extraDigits{fracDigits == 0 ? 1 : 0};;) {
449decimal::ConversionToDecimalResult converted{
450ConvertToDecimal(extraDigits + fracDigits, rounding, flags)};
451const char *convertedStr{converted.str};
452if (IsInfOrNaN(convertedStr, static_cast<int>(converted.length))) {
453return editWidth > 0 &&
454converted.length > static_cast<std::size_t>(editWidth)
455? EmitRepeated(io_, '*', editWidth)
456: EmitPrefix(edit, converted.length, editWidth) &&
457EmitAscii(io_, convertedStr, converted.length) &&
458EmitSuffix(edit);
459}
460int expo{converted.decimalExponent + edit.modes.scale /*kP*/};
461int signLength{*convertedStr == '-' || *convertedStr == '+' ? 1 : 0};
462int convertedDigits{static_cast<int>(converted.length) - signLength};
463if (IsZero()) { // don't treat converted "0" as significant digit
464expo = 0;
465convertedDigits = 0;
466}
467bool isNegative{*convertedStr == '-'};
468char one[2];
469if (expo > extraDigits && extraDigits >= 0 && canIncrease) {
470extraDigits = expo;
471if (!edit.digits.has_value()) { // F0
472fracDigits = sizeof buffer_ - extraDigits - 2; // sign & NUL
473}
474canIncrease = false; // only once
475continue;
476} else if (expo == -fracDigits && convertedDigits > 0) {
477// Result will be either a signed zero or power of ten, depending
478// on rounding.
479char leading{convertedStr[signLength]};
480bool roundToPowerOfTen{false};
481switch (edit.modes.round) {
482case decimal::FortranRounding::RoundUp:
483roundToPowerOfTen = !isNegative;
484break;
485case decimal::FortranRounding::RoundDown:
486roundToPowerOfTen = isNegative;
487break;
488case decimal::FortranRounding::RoundToZero:
489break;
490case decimal::FortranRounding::RoundNearest:
491if (leading == '5' &&
492rounding == decimal::FortranRounding::RoundNearest) {
493// Try again, rounding away from zero.
494rounding = isNegative ? decimal::FortranRounding::RoundDown
495: decimal::FortranRounding::RoundUp;
496extraDigits = 1 - fracDigits; // just one digit needed
497continue;
498}
499roundToPowerOfTen = leading > '5';
500break;
501case decimal::FortranRounding::RoundCompatible:
502roundToPowerOfTen = leading >= '5';
503break;
504}
505if (roundToPowerOfTen) {
506++expo;
507convertedDigits = 1;
508if (signLength > 0) {
509one[0] = *convertedStr;
510one[1] = '1';
511} else {
512one[0] = '1';
513}
514convertedStr = one;
515} else {
516expo = 0;
517convertedDigits = 0;
518}
519} else if (expo < extraDigits && extraDigits > -fracDigits) {
520extraDigits = std::max(expo, -fracDigits);
521continue;
522}
523int digitsBeforePoint{std::max(0, std::min(expo, convertedDigits))};
524int zeroesBeforePoint{std::max(0, expo - digitsBeforePoint)};
525if (zeroesBeforePoint > 0 && (flags & decimal::Minimize)) {
526// If a minimized result looks like an integer, emit all of
527// its digits rather than clipping some to zeroes.
528// This can happen with HUGE(0._2) == 65504._2.
529flags &= ~decimal::Minimize;
530continue;
531}
532int zeroesAfterPoint{std::min(fracDigits, std::max(0, -expo))};
533int digitsAfterPoint{convertedDigits - digitsBeforePoint};
534int trailingZeroes{emitTrailingZeroes
535? std::max(0, fracDigits - (zeroesAfterPoint + digitsAfterPoint))
536: 0};
537if (digitsBeforePoint + zeroesBeforePoint + zeroesAfterPoint +
538digitsAfterPoint + trailingZeroes ==
5390) {
540zeroesBeforePoint = 1; // "." -> "0."
541}
542int totalLength{signLength + digitsBeforePoint + zeroesBeforePoint +
5431 /*'.'*/ + zeroesAfterPoint + digitsAfterPoint + trailingZeroes +
544trailingBlanks_ /* G editing converted to F */};
545int width{editWidth > 0 || trailingBlanks_ ? editWidth : totalLength};
546if (totalLength > width) {
547return EmitRepeated(io_, '*', width);
548}
549if (totalLength < width && digitsBeforePoint + zeroesBeforePoint == 0) {
550zeroesBeforePoint = 1;
551++totalLength;
552}
553return EmitPrefix(edit, totalLength, width) &&
554EmitAscii(io_, convertedStr, signLength + digitsBeforePoint) &&
555EmitRepeated(io_, '0', zeroesBeforePoint) &&
556EmitAscii(io_, edit.modes.editingFlags & decimalComma ? "," : ".", 1) &&
557EmitRepeated(io_, '0', zeroesAfterPoint) &&
558EmitAscii(io_, convertedStr + signLength + digitsBeforePoint,
559digitsAfterPoint) &&
560EmitRepeated(io_, '0', trailingZeroes) &&
561EmitRepeated(io_, ' ', trailingBlanks_) && EmitSuffix(edit);
562}
563}
564
565// 13.7.5.2.3 in F'2018
566template <int KIND>
567RT_API_ATTRS DataEdit RealOutputEditing<KIND>::EditForGOutput(DataEdit edit) {
568edit.descriptor = 'E';
569edit.variation = 'G'; // to suppress error for Ew.0
570int editWidth{edit.width.value_or(0)};
571int significantDigits{edit.digits.value_or(
572static_cast<int>(BinaryFloatingPoint::decimalPrecision))}; // 'd'
573if (editWidth > 0 && significantDigits == 0) {
574return edit; // Gw.0Ee -> Ew.0Ee for w > 0
575}
576int flags{0};
577if (edit.modes.editingFlags & signPlus) {
578flags |= decimal::AlwaysSign;
579}
580decimal::ConversionToDecimalResult converted{
581ConvertToDecimal(significantDigits, edit.modes.round, flags)};
582if (IsInfOrNaN(converted.str, static_cast<int>(converted.length))) {
583return edit; // Inf/Nan -> Ew.d (same as Fw.d)
584}
585int expo{IsZero() ? 1 : converted.decimalExponent}; // 's'
586if (expo < 0 || expo > significantDigits) {
587if (editWidth == 0 && !edit.expoDigits) { // G0.d -> G0.dE0
588edit.expoDigits = 0;
589}
590return edit; // Ew.dEe
591}
592edit.descriptor = 'F';
593edit.modes.scale = 0; // kP is ignored for G when no exponent field
594trailingBlanks_ = 0;
595if (editWidth > 0) {
596int expoDigits{edit.expoDigits.value_or(0)};
597// F'2023 13.7.5.2.3 p5: "If 0 <= s <= d, the scale factor has no effect
598// and F(w − n).(d − s),n(’b’) editing is used where b is a blank and
599// n is 4 for Gw.d editing, e + 2 for Gw.dEe editing if e > 0, and
600// 4 for Gw.dE0 editing."
601trailingBlanks_ = expoDigits > 0 ? expoDigits + 2 : 4; // 'n'
602}
603if (edit.digits.has_value()) {
604*edit.digits = std::max(0, *edit.digits - expo);
605}
606return edit;
607}
608
609// 13.10.4 in F'2018
610template <int KIND>
611RT_API_ATTRS bool RealOutputEditing<KIND>::EditListDirectedOutput(
612const DataEdit &edit) {
613decimal::ConversionToDecimalResult converted{
614ConvertToDecimal(1, edit.modes.round)};
615if (IsInfOrNaN(converted.str, static_cast<int>(converted.length))) {
616DataEdit copy{edit};
617copy.variation = DataEdit::ListDirected;
618return EditEorDOutput(copy);
619}
620int expo{converted.decimalExponent};
621// The decimal precision of 16-bit floating-point types is very low,
622// so use a reasonable cap of 6 to allow more values to be emitted
623// with Fw.d editing.
624static constexpr int maxExpo{
625std::max(6, BinaryFloatingPoint::decimalPrecision)};
626if (expo < 0 || expo > maxExpo) {
627DataEdit copy{edit};
628copy.variation = DataEdit::ListDirected;
629copy.modes.scale = 1; // 1P
630return EditEorDOutput(copy);
631} else {
632return EditFOutput(edit);
633}
634}
635
636// 13.7.2.3.6 in F'2023
637// The specification for hexadecimal output, unfortunately for implementors,
638// leaves as "implementation dependent" the choice of how to emit values
639// with multiple hexadecimal output possibilities that are numerically
640// equivalent. The one working implementation of EX output that I can find
641// apparently chooses to frame the nybbles from most to least significant,
642// rather than trying to minimize the magnitude of the binary exponent.
643// E.g., 2. is edited into 0X8.0P-2 rather than 0X2.0P0. This implementation
644// follows that precedent so as to avoid a gratuitous incompatibility.
645template <int KIND>
646RT_API_ATTRS auto RealOutputEditing<KIND>::ConvertToHexadecimal(
647int significantDigits, enum decimal::FortranRounding rounding,
648int flags) -> ConvertToHexadecimalResult {
649if (x_.IsNaN() || x_.IsInfinite()) {
650auto converted{ConvertToDecimal(significantDigits, rounding, flags)};
651return {converted.str, static_cast<int>(converted.length), 0};
652}
653x_.RoundToBits(4 * significantDigits, rounding);
654if (x_.IsInfinite()) { // rounded away to +/-Inf
655auto converted{ConvertToDecimal(significantDigits, rounding, flags)};
656return {converted.str, static_cast<int>(converted.length), 0};
657}
658int len{0};
659if (x_.IsNegative()) {
660buffer_[len++] = '-';
661} else if (flags & decimal::AlwaysSign) {
662buffer_[len++] = '+';
663}
664auto fraction{x_.Fraction()};
665if (fraction == 0) {
666buffer_[len++] = '0';
667return {buffer_, len, 0};
668} else {
669// Ensure that the MSB is set.
670int expo{x_.UnbiasedExponent() - 3};
671while (!(fraction >> (x_.binaryPrecision - 1))) {
672fraction <<= 1;
673--expo;
674}
675// This is initially the right shift count needed to bring the
676// most-significant hexadecimal digit's bits into the LSBs.
677// x_.binaryPrecision is constant, so / can be used for readability.
678int shift{x_.binaryPrecision - 4};
679typename BinaryFloatingPoint::RawType one{1};
680auto remaining{(one << x_.binaryPrecision) - one};
681for (int digits{0}; digits < significantDigits; ++digits) {
682if ((flags & decimal::Minimize) && !(fraction & remaining)) {
683break;
684}
685int hexDigit{0};
686if (shift >= 0) {
687hexDigit = int(fraction >> shift) & 0xf;
688} else if (shift >= -3) {
689hexDigit = int(fraction << -shift) & 0xf;
690}
691if (hexDigit >= 10) {
692buffer_[len++] = 'A' + hexDigit - 10;
693} else {
694buffer_[len++] = '0' + hexDigit;
695}
696shift -= 4;
697remaining >>= 4;
698}
699return {buffer_, len, expo};
700}
701}
702
703template <int KIND>
704RT_API_ATTRS bool RealOutputEditing<KIND>::EditEXOutput(const DataEdit &edit) {
705addSpaceBeforeCharacter(io_);
706int editDigits{edit.digits.value_or(0)}; // 'd' field
707int significantDigits{editDigits + 1};
708int flags{0};
709if (edit.modes.editingFlags & signPlus) {
710flags |= decimal::AlwaysSign;
711}
712int editWidth{edit.width.value_or(0)}; // 'w' field
713if ((editWidth == 0 && !edit.digits) || editDigits == 0) {
714// EX0 or EXw.0
715flags |= decimal::Minimize;
716static constexpr int maxSigHexDigits{
717(common::PrecisionOfRealKind(16) + 3) / 4};
718significantDigits = maxSigHexDigits;
719}
720auto converted{
721ConvertToHexadecimal(significantDigits, edit.modes.round, flags)};
722if (IsInfOrNaN(converted.str, converted.length)) {
723return editWidth > 0 && converted.length > editWidth
724? EmitRepeated(io_, '*', editWidth)
725: (editWidth <= converted.length ||
726EmitRepeated(io_, ' ', editWidth - converted.length)) &&
727EmitAscii(io_, converted.str, converted.length);
728}
729int signLength{converted.length > 0 &&
730(converted.str[0] == '-' || converted.str[0] == '+')
731? 1
732: 0};
733int convertedDigits{converted.length - signLength};
734int expoLength{0};
735const char *exponent{FormatExponent(converted.exponent, edit, expoLength)};
736int trailingZeroes{flags & decimal::Minimize
737? 0
738: std::max(0, significantDigits - convertedDigits)};
739int totalLength{converted.length + trailingZeroes + expoLength + 3 /*0X.*/};
740int width{editWidth > 0 ? editWidth : totalLength};
741return totalLength > width || !exponent
742? EmitRepeated(io_, '*', width)
743: EmitRepeated(io_, ' ', width - totalLength) &&
744EmitAscii(io_, converted.str, signLength) &&
745EmitAscii(io_, "0X", 2) &&
746EmitAscii(io_, converted.str + signLength, 1) &&
747EmitAscii(
748io_, edit.modes.editingFlags & decimalComma ? "," : ".", 1) &&
749EmitAscii(io_, converted.str + signLength + 1,
750converted.length - (signLength + 1)) &&
751EmitRepeated(io_, '0', trailingZeroes) &&
752EmitAscii(io_, exponent, expoLength);
753}
754
755template <int KIND>
756RT_API_ATTRS bool RealOutputEditing<KIND>::Edit(const DataEdit &edit) {
757const DataEdit *editPtr{&edit};
758DataEdit newEdit;
759if (editPtr->descriptor == 'G') {
760// Avoid recursive call as in Edit(EditForGOutput(edit)).
761newEdit = EditForGOutput(*editPtr);
762editPtr = &newEdit;
763RUNTIME_CHECK(io_.GetIoErrorHandler(), editPtr->descriptor != 'G');
764}
765switch (editPtr->descriptor) {
766case 'D':
767return EditEorDOutput(*editPtr);
768case 'E':
769if (editPtr->variation == 'X') {
770return EditEXOutput(*editPtr);
771} else {
772return EditEorDOutput(*editPtr);
773}
774case 'F':
775return EditFOutput(*editPtr);
776case 'B':
777return EditBOZOutput<1>(io_, *editPtr,
778reinterpret_cast<const unsigned char *>(&x_),
779common::BitsForBinaryPrecision(common::PrecisionOfRealKind(KIND)) >> 3);
780case 'O':
781return EditBOZOutput<3>(io_, *editPtr,
782reinterpret_cast<const unsigned char *>(&x_),
783common::BitsForBinaryPrecision(common::PrecisionOfRealKind(KIND)) >> 3);
784case 'Z':
785return EditBOZOutput<4>(io_, *editPtr,
786reinterpret_cast<const unsigned char *>(&x_),
787common::BitsForBinaryPrecision(common::PrecisionOfRealKind(KIND)) >> 3);
788case 'L':
789return EditLogicalOutput(
790io_, *editPtr, *reinterpret_cast<const char *>(&x_));
791case 'A': // legacy extension
792return EditCharacterOutput(
793io_, *editPtr, reinterpret_cast<char *>(&x_), sizeof x_);
794default:
795if (editPtr->IsListDirected()) {
796return EditListDirectedOutput(*editPtr);
797}
798io_.GetIoErrorHandler().SignalError(IostatErrorInFormat,
799"Data edit descriptor '%c' may not be used with a REAL data item",
800editPtr->descriptor);
801return false;
802}
803return false;
804}
805
806RT_API_ATTRS bool ListDirectedLogicalOutput(IoStatementState &io,
807ListDirectedStatementState<Direction::Output> &list, bool truth) {
808return list.EmitLeadingSpaceOrAdvance(io) &&
809EmitAscii(io, truth ? "T" : "F", 1);
810}
811
812RT_API_ATTRS bool EditLogicalOutput(
813IoStatementState &io, const DataEdit &edit, bool truth) {
814switch (edit.descriptor) {
815case 'L':
816case 'G':
817return EmitRepeated(io, ' ', std::max(0, edit.width.value_or(1) - 1)) &&
818EmitAscii(io, truth ? "T" : "F", 1);
819case 'B':
820return EditBOZOutput<1>(io, edit,
821reinterpret_cast<const unsigned char *>(&truth), sizeof truth);
822case 'O':
823return EditBOZOutput<3>(io, edit,
824reinterpret_cast<const unsigned char *>(&truth), sizeof truth);
825case 'Z':
826return EditBOZOutput<4>(io, edit,
827reinterpret_cast<const unsigned char *>(&truth), sizeof truth);
828case 'A': { // legacy extension
829int truthBits{truth};
830int len{sizeof truthBits};
831int width{edit.width.value_or(len)};
832return EmitRepeated(io, ' ', std::max(0, width - len)) &&
833EmitEncoded(
834io, reinterpret_cast<char *>(&truthBits), std::min(width, len));
835}
836default:
837io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
838"Data edit descriptor '%c' may not be used with a LOGICAL data item",
839edit.descriptor);
840return false;
841}
842}
843
844template <typename CHAR>
845RT_API_ATTRS bool ListDirectedCharacterOutput(IoStatementState &io,
846ListDirectedStatementState<Direction::Output> &list, const CHAR *x,
847std::size_t length) {
848bool ok{true};
849MutableModes &modes{io.mutableModes()};
850ConnectionState &connection{io.GetConnectionState()};
851if (modes.delim) {
852ok = ok && list.EmitLeadingSpaceOrAdvance(io);
853// Value is delimited with ' or " marks, and interior
854// instances of that character are doubled.
855auto EmitOne{[&](CHAR ch) {
856if (connection.NeedAdvance(1)) {
857ok = ok && io.AdvanceRecord();
858}
859ok = ok && EmitEncoded(io, &ch, 1);
860}};
861EmitOne(modes.delim);
862for (std::size_t j{0}; j < length; ++j) {
863// Doubled delimiters must be put on the same record
864// in order to be acceptable as list-directed or NAMELIST
865// input; however, this requirement is not always possible
866// when the records have a fixed length, as is the case with
867// internal output. The standard is silent on what should
868// happen, and no two extant Fortran implementations do
869// the same thing when tested with this case.
870// This runtime splits the doubled delimiters across
871// two records for lack of a better alternative.
872if (x[j] == static_cast<CHAR>(modes.delim)) {
873EmitOne(x[j]);
874}
875EmitOne(x[j]);
876}
877EmitOne(modes.delim);
878} else {
879// Undelimited list-directed output
880ok = ok && list.EmitLeadingSpaceOrAdvance(io, length > 0 ? 1 : 0, true);
881std::size_t put{0};
882std::size_t oneAtATime{
883connection.useUTF8<CHAR>() || connection.internalIoCharKind > 1
884? 1
885: length};
886while (ok && put < length) {
887if (std::size_t chunk{std::min<std::size_t>(
888std::min<std::size_t>(length - put, oneAtATime),
889connection.RemainingSpaceInRecord())}) {
890ok = EmitEncoded(io, x + put, chunk);
891put += chunk;
892} else {
893ok = io.AdvanceRecord() && EmitAscii(io, " ", 1);
894}
895}
896list.set_lastWasUndelimitedCharacter(true);
897}
898return ok;
899}
900
901template <typename CHAR>
902RT_API_ATTRS bool EditCharacterOutput(IoStatementState &io,
903const DataEdit &edit, const CHAR *x, std::size_t length) {
904int len{static_cast<int>(length)};
905int width{edit.width.value_or(len)};
906switch (edit.descriptor) {
907case 'A':
908break;
909case 'G':
910if (width == 0) {
911width = len;
912}
913break;
914case 'B':
915return EditBOZOutput<1>(io, edit,
916reinterpret_cast<const unsigned char *>(x), sizeof(CHAR) * length);
917case 'O':
918return EditBOZOutput<3>(io, edit,
919reinterpret_cast<const unsigned char *>(x), sizeof(CHAR) * length);
920case 'Z':
921return EditBOZOutput<4>(io, edit,
922reinterpret_cast<const unsigned char *>(x), sizeof(CHAR) * length);
923case 'L':
924return EditLogicalOutput(io, edit, *reinterpret_cast<const char *>(x));
925default:
926io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
927"Data edit descriptor '%c' may not be used with a CHARACTER data item",
928edit.descriptor);
929return false;
930}
931return EmitRepeated(io, ' ', std::max(0, width - len)) &&
932EmitEncoded(io, x, std::min(width, len));
933}
934
935template RT_API_ATTRS bool EditIntegerOutput<1>(
936IoStatementState &, const DataEdit &, std::int8_t);
937template RT_API_ATTRS bool EditIntegerOutput<2>(
938IoStatementState &, const DataEdit &, std::int16_t);
939template RT_API_ATTRS bool EditIntegerOutput<4>(
940IoStatementState &, const DataEdit &, std::int32_t);
941template RT_API_ATTRS bool EditIntegerOutput<8>(
942IoStatementState &, const DataEdit &, std::int64_t);
943template RT_API_ATTRS bool EditIntegerOutput<16>(
944IoStatementState &, const DataEdit &, common::int128_t);
945
946template class RealOutputEditing<2>;
947template class RealOutputEditing<3>;
948template class RealOutputEditing<4>;
949template class RealOutputEditing<8>;
950template class RealOutputEditing<10>;
951// TODO: double/double
952template class RealOutputEditing<16>;
953
954template RT_API_ATTRS bool ListDirectedCharacterOutput(IoStatementState &,
955ListDirectedStatementState<Direction::Output> &, const char *,
956std::size_t chars);
957template RT_API_ATTRS bool ListDirectedCharacterOutput(IoStatementState &,
958ListDirectedStatementState<Direction::Output> &, const char16_t *,
959std::size_t chars);
960template RT_API_ATTRS bool ListDirectedCharacterOutput(IoStatementState &,
961ListDirectedStatementState<Direction::Output> &, const char32_t *,
962std::size_t chars);
963
964template RT_API_ATTRS bool EditCharacterOutput(
965IoStatementState &, const DataEdit &, const char *, std::size_t chars);
966template RT_API_ATTRS bool EditCharacterOutput(
967IoStatementState &, const DataEdit &, const char16_t *, std::size_t chars);
968template RT_API_ATTRS bool EditCharacterOutput(
969IoStatementState &, const DataEdit &, const char32_t *, std::size_t chars);
970
971RT_OFFLOAD_API_GROUP_END
972} // namespace Fortran::runtime::io
973