xref: /llvm-project/flang/runtime/edit-input.cpp (revision b83242e20e099c9cc4ba90a63abda8ba6e2f32d5)
1 //===-- runtime/edit-input.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-input.h"
10 #include "namelist.h"
11 #include "flang/Common/real.h"
12 #include "flang/Common/uint128.h"
13 #include <algorithm>
14 
15 namespace Fortran::runtime::io {
16 
17 static bool EditBOZInput(IoStatementState &io, const DataEdit &edit, void *n,
18     int base, int totalBitSize) {
19   std::optional<int> remaining;
20   std::optional<char32_t> next{io.PrepareInput(edit, remaining)};
21   common::UnsignedInt128 value{0};
22   for (; next; next = io.NextInField(remaining)) {
23     char32_t ch{*next};
24     if (ch == ' ' || ch == '\t') {
25       continue;
26     }
27     int digit{0};
28     if (ch >= '0' && ch <= '1') {
29       digit = ch - '0';
30     } else if (base >= 8 && ch >= '2' && ch <= '7') {
31       digit = ch - '0';
32     } else if (base >= 10 && ch >= '8' && ch <= '9') {
33       digit = ch - '0';
34     } else if (base == 16 && ch >= 'A' && ch <= 'Z') {
35       digit = ch + 10 - 'A';
36     } else if (base == 16 && ch >= 'a' && ch <= 'z') {
37       digit = ch + 10 - 'a';
38     } else {
39       io.GetIoErrorHandler().SignalError(
40           "Bad character '%lc' in B/O/Z input field", ch);
41       return false;
42     }
43     value *= base;
44     value += digit;
45   }
46   // TODO: check for overflow
47   std::memcpy(n, &value, totalBitSize >> 3);
48   return true;
49 }
50 
51 // Prepares input from a field, and consumes the sign, if any.
52 // Returns true if there's a '-' sign.
53 static bool ScanNumericPrefix(IoStatementState &io, const DataEdit &edit,
54     std::optional<char32_t> &next, std::optional<int> &remaining) {
55   next = io.PrepareInput(edit, remaining);
56   bool negative{false};
57   if (next) {
58     negative = *next == '-';
59     if (negative || *next == '+') {
60       io.GotChar();
61       io.SkipSpaces(remaining);
62       next = io.NextInField(remaining);
63     }
64   }
65   return negative;
66 }
67 
68 bool EditIntegerInput(
69     IoStatementState &io, const DataEdit &edit, void *n, int kind) {
70   RUNTIME_CHECK(io.GetIoErrorHandler(), kind >= 1 && !(kind & (kind - 1)));
71   switch (edit.descriptor) {
72   case DataEdit::ListDirected:
73     if (IsNamelistName(io)) {
74       return false;
75     }
76     break;
77   case 'G':
78   case 'I':
79     break;
80   case 'B':
81     return EditBOZInput(io, edit, n, 2, kind << 3);
82   case 'O':
83     return EditBOZInput(io, edit, n, 8, kind << 3);
84   case 'Z':
85     return EditBOZInput(io, edit, n, 16, kind << 3);
86   case 'A': // legacy extension
87     return EditDefaultCharacterInput(
88         io, edit, reinterpret_cast<char *>(n), kind);
89   default:
90     io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
91         "Data edit descriptor '%c' may not be used with an INTEGER data item",
92         edit.descriptor);
93     return false;
94   }
95   std::optional<int> remaining;
96   std::optional<char32_t> next;
97   bool negate{ScanNumericPrefix(io, edit, next, remaining)};
98   common::UnsignedInt128 value;
99   for (; next; next = io.NextInField(remaining)) {
100     char32_t ch{*next};
101     if (ch == ' ' || ch == '\t') {
102       if (edit.modes.editingFlags & blankZero) {
103         ch = '0'; // BZ mode - treat blank as if it were zero
104       } else {
105         continue;
106       }
107     }
108     int digit{0};
109     if (ch >= '0' && ch <= '9') {
110       digit = ch - '0';
111     } else {
112       io.GetIoErrorHandler().SignalError(
113           "Bad character '%lc' in INTEGER input field", ch);
114       return false;
115     }
116     value *= 10;
117     value += digit;
118   }
119   if (negate) {
120     value = -value;
121   }
122   std::memcpy(n, &value, kind);
123   return true;
124 }
125 
126 // Parses a REAL input number from the input source as a normalized
127 // fraction into a supplied buffer -- there's an optional '-', a
128 // decimal point, and at least one digit.  The adjusted exponent value
129 // is returned in a reference argument.  The returned value is the number
130 // of characters that (should) have been written to the buffer -- this can
131 // be larger than the buffer size and can indicate overflow.  Replaces
132 // blanks with zeroes if appropriate.
133 static int ScanRealInput(char *buffer, int bufferSize, IoStatementState &io,
134     const DataEdit &edit, int &exponent) {
135   std::optional<int> remaining;
136   std::optional<char32_t> next;
137   int got{0};
138   std::optional<int> decimalPoint;
139   auto Put{[&](char ch) -> void {
140     if (got < bufferSize) {
141       buffer[got] = ch;
142     }
143     ++got;
144   }};
145   if (ScanNumericPrefix(io, edit, next, remaining)) {
146     Put('-');
147   }
148   if (next.value_or(' ') == ' ') { // empty/blank field means zero
149     remaining.reset();
150     Put('0');
151     return got;
152   }
153   char32_t decimal = edit.modes.editingFlags & decimalComma ? ',' : '.';
154   char32_t first{*next >= 'a' && *next <= 'z' ? *next + 'A' - 'a' : *next};
155   if (first == 'N' || first == 'I') {
156     // NaN or infinity - convert to upper case
157     // Subtle: a blank field of digits could be followed by 'E' or 'D',
158     for (; next &&
159          ((*next >= 'a' && *next <= 'z') || (*next >= 'A' && *next <= 'Z'));
160          next = io.NextInField(remaining)) {
161       if (*next >= 'a' && *next <= 'z') {
162         Put(*next - 'a' + 'A');
163       } else {
164         Put(*next);
165       }
166     }
167     if (next && *next == '(') { // NaN(...)
168       while (next && *next != ')') {
169         next = io.NextInField(remaining);
170       }
171     }
172     exponent = 0;
173   } else if (first == decimal || (first >= '0' && first <= '9') ||
174       first == 'E' || first == 'D' || first == 'Q') {
175     Put('.'); // input field is normalized to a fraction
176     auto start{got};
177     bool bzMode{(edit.modes.editingFlags & blankZero) != 0};
178     for (; next; next = io.NextInField(remaining)) {
179       char32_t ch{*next};
180       if (ch == ' ' || ch == '\t') {
181         if (bzMode) {
182           ch = '0'; // BZ mode - treat blank as if it were zero
183         } else {
184           continue;
185         }
186       }
187       if (ch == '0' && got == start && !decimalPoint) {
188         // omit leading zeroes before the decimal
189       } else if (ch >= '0' && ch <= '9') {
190         Put(ch);
191       } else if (ch == decimal && !decimalPoint) {
192         // the decimal point is *not* copied to the buffer
193         decimalPoint = got - start; // # of digits before the decimal point
194       } else {
195         break;
196       }
197     }
198     if (got == start) {
199       Put('0'); // emit at least one digit
200     }
201     if (next &&
202         (*next == 'e' || *next == 'E' || *next == 'd' || *next == 'D' ||
203             *next == 'q' || *next == 'Q')) {
204       // Optional exponent letter.  Blanks are allowed between the
205       // optional exponent letter and the exponent value.
206       io.SkipSpaces(remaining);
207       next = io.NextInField(remaining);
208     }
209     // The default exponent is -kP, but the scale factor doesn't affect
210     // an explicit exponent.
211     exponent = -edit.modes.scale;
212     if (next &&
213         (*next == '-' || *next == '+' || (*next >= '0' && *next <= '9') ||
214             (bzMode && (*next == ' ' || *next == '\t')))) {
215       bool negExpo{*next == '-'};
216       if (negExpo || *next == '+') {
217         next = io.NextInField(remaining);
218       }
219       for (exponent = 0; next; next = io.NextInField(remaining)) {
220         if (*next >= '0' && *next <= '9') {
221           exponent = 10 * exponent + *next - '0';
222         } else if (bzMode && (*next == ' ' || *next == '\t')) {
223           exponent = 10 * exponent;
224         } else {
225           break;
226         }
227       }
228       if (negExpo) {
229         exponent = -exponent;
230       }
231     }
232     if (decimalPoint) {
233       exponent += *decimalPoint;
234     } else {
235       // When no decimal point (or comma) appears in the value, the 'd'
236       // part of the edit descriptor must be interpreted as the number of
237       // digits in the value to be interpreted as being to the *right* of
238       // the assumed decimal point (13.7.2.3.2)
239       exponent += got - start - edit.digits.value_or(0);
240     }
241   } else {
242     // TODO: hex FP input
243     exponent = 0;
244     return 0;
245   }
246   // Consume the trailing ')' of a list-directed or NAMELIST complex
247   // input value.
248   if (edit.descriptor == DataEdit::ListDirectedImaginaryPart) {
249     if (next && (*next == ' ' || *next == '\t')) {
250       next = io.NextInField(remaining);
251     }
252     if (!next) { // NextInField fails on separators like ')'
253       next = io.GetCurrentChar();
254       if (next && *next == ')') {
255         io.HandleRelativePosition(1);
256       }
257     }
258   } else if (remaining) {
259     while (next && (*next == ' ' || *next == '\t')) {
260       next = io.NextInField(remaining);
261     }
262     if (next) {
263       return 0; // error: unused nonblank character in fixed-width field
264     }
265   }
266   return got;
267 }
268 
269 template <int KIND>
270 bool EditCommonRealInput(IoStatementState &io, const DataEdit &edit, void *n) {
271   constexpr int binaryPrecision{common::PrecisionOfRealKind(KIND)};
272   static constexpr int maxDigits{
273       common::MaxDecimalConversionDigits(binaryPrecision)};
274   static constexpr int bufferSize{maxDigits + 18};
275   char buffer[bufferSize];
276   int exponent{0};
277   int got{ScanRealInput(buffer, maxDigits + 2, io, edit, exponent)};
278   if (got >= maxDigits + 2) {
279     io.GetIoErrorHandler().Crash("EditCommonRealInput: buffer was too small");
280     return false;
281   }
282   if (got == 0) {
283     io.GetIoErrorHandler().SignalError("Bad REAL input value");
284     return false;
285   }
286   bool hadExtra{got > maxDigits};
287   if (exponent != 0) {
288     got += std::snprintf(&buffer[got], bufferSize - got, "e%d", exponent);
289   }
290   buffer[got] = '\0';
291   const char *p{buffer};
292   decimal::ConversionToBinaryResult<binaryPrecision> converted{
293       decimal::ConvertToBinary<binaryPrecision>(p, edit.modes.round)};
294   if (hadExtra) {
295     converted.flags = static_cast<enum decimal::ConversionResultFlags>(
296         converted.flags | decimal::Inexact);
297   }
298   // TODO: raise converted.flags as exceptions?
299   *reinterpret_cast<decimal::BinaryFloatingPointNumber<binaryPrecision> *>(n) =
300       converted.binary;
301   return true;
302 }
303 
304 template <int KIND>
305 bool EditRealInput(IoStatementState &io, const DataEdit &edit, void *n) {
306   constexpr int binaryPrecision{common::PrecisionOfRealKind(KIND)};
307   switch (edit.descriptor) {
308   case DataEdit::ListDirected:
309     if (IsNamelistName(io)) {
310       return false;
311     }
312     return EditCommonRealInput<KIND>(io, edit, n);
313   case DataEdit::ListDirectedRealPart:
314   case DataEdit::ListDirectedImaginaryPart:
315   case 'F':
316   case 'E': // incl. EN, ES, & EX
317   case 'D':
318   case 'G':
319     return EditCommonRealInput<KIND>(io, edit, n);
320   case 'B':
321     return EditBOZInput(
322         io, edit, n, 2, common::BitsForBinaryPrecision(binaryPrecision));
323   case 'O':
324     return EditBOZInput(
325         io, edit, n, 8, common::BitsForBinaryPrecision(binaryPrecision));
326   case 'Z':
327     return EditBOZInput(
328         io, edit, n, 16, common::BitsForBinaryPrecision(binaryPrecision));
329   case 'A': // legacy extension
330     return EditDefaultCharacterInput(
331         io, edit, reinterpret_cast<char *>(n), KIND);
332   default:
333     io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
334         "Data edit descriptor '%c' may not be used for REAL input",
335         edit.descriptor);
336     return false;
337   }
338 }
339 
340 // 13.7.3 in Fortran 2018
341 bool EditLogicalInput(IoStatementState &io, const DataEdit &edit, bool &x) {
342   switch (edit.descriptor) {
343   case DataEdit::ListDirected:
344     if (IsNamelistName(io)) {
345       return false;
346     }
347     break;
348   case 'L':
349   case 'G':
350     break;
351   default:
352     io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
353         "Data edit descriptor '%c' may not be used for LOGICAL input",
354         edit.descriptor);
355     return false;
356   }
357   std::optional<int> remaining;
358   std::optional<char32_t> next{io.PrepareInput(edit, remaining)};
359   if (next && *next == '.') { // skip optional period
360     next = io.NextInField(remaining);
361   }
362   if (!next) {
363     io.GetIoErrorHandler().SignalError("Empty LOGICAL input field");
364     return false;
365   }
366   switch (*next) {
367   case 'T':
368   case 't':
369     x = true;
370     break;
371   case 'F':
372   case 'f':
373     x = false;
374     break;
375   default:
376     io.GetIoErrorHandler().SignalError(
377         "Bad character '%lc' in LOGICAL input field", *next);
378     return false;
379   }
380   if (remaining) { // ignore the rest of the field
381     io.HandleRelativePosition(*remaining);
382   } else if (edit.descriptor == DataEdit::ListDirected) {
383     while (io.NextInField(remaining)) { // discard rest of field
384     }
385   }
386   return true;
387 }
388 
389 // See 13.10.3.1 paragraphs 7-9 in Fortran 2018
390 static bool EditDelimitedCharacterInput(
391     IoStatementState &io, char *x, std::size_t length, char32_t delimiter) {
392   bool result{true};
393   while (true) {
394     auto ch{io.GetCurrentChar()};
395     if (!ch) {
396       if (io.AdvanceRecord()) {
397         continue;
398       } else {
399         result = false; // EOF in character value
400         break;
401       }
402     }
403     io.HandleRelativePosition(1);
404     if (*ch == delimiter) {
405       auto next{io.GetCurrentChar()};
406       if (next && *next == delimiter) {
407         // Repeated delimiter: use as character value
408         io.HandleRelativePosition(1);
409       } else {
410         break; // closing delimiter
411       }
412     }
413     if (length > 0) {
414       *x++ = *ch;
415       --length;
416     }
417   }
418   std::fill_n(x, length, ' ');
419   return result;
420 }
421 
422 static bool EditListDirectedDefaultCharacterInput(
423     IoStatementState &io, char *x, std::size_t length) {
424   auto ch{io.GetCurrentChar()};
425   if (ch && (*ch == '\'' || *ch == '"')) {
426     io.HandleRelativePosition(1);
427     return EditDelimitedCharacterInput(io, x, length, *ch);
428   }
429   if (IsNamelistName(io)) {
430     return false;
431   }
432   // Undelimited list-directed character input: stop at a value separator
433   // or the end of the current record.
434   std::optional<int> remaining{length};
435   for (std::optional<char32_t> next{io.NextInField(remaining)}; next;
436        next = io.NextInField(remaining)) {
437     switch (*next) {
438     case ' ':
439     case '\t':
440     case ',':
441     case ';':
442     case '/':
443       remaining = 0; // value separator: stop
444       break;
445     default:
446       *x++ = *next;
447       --length;
448     }
449   }
450   std::fill_n(x, length, ' ');
451   return true;
452 }
453 
454 bool EditDefaultCharacterInput(
455     IoStatementState &io, const DataEdit &edit, char *x, std::size_t length) {
456   switch (edit.descriptor) {
457   case DataEdit::ListDirected:
458     return EditListDirectedDefaultCharacterInput(io, x, length);
459   case 'A':
460   case 'G':
461     break;
462   default:
463     io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
464         "Data edit descriptor '%c' may not be used with a CHARACTER data item",
465         edit.descriptor);
466     return false;
467   }
468   std::optional<int> remaining{length};
469   if (edit.width && *edit.width > 0) {
470     remaining = *edit.width;
471   }
472   // When the field is wider than the variable, we drop the leading
473   // characters.  When the variable is wider than the field, there's
474   // trailing padding.
475   std::int64_t skip{*remaining - static_cast<std::int64_t>(length)};
476   for (std::optional<char32_t> next{io.NextInField(remaining)}; next;
477        next = io.NextInField(remaining)) {
478     if (skip > 0) {
479       --skip;
480       io.GotChar(-1);
481     } else {
482       *x++ = *next;
483       --length;
484     }
485   }
486   std::fill_n(x, length, ' ');
487   return true;
488 }
489 
490 template bool EditRealInput<2>(IoStatementState &, const DataEdit &, void *);
491 template bool EditRealInput<3>(IoStatementState &, const DataEdit &, void *);
492 template bool EditRealInput<4>(IoStatementState &, const DataEdit &, void *);
493 template bool EditRealInput<8>(IoStatementState &, const DataEdit &, void *);
494 template bool EditRealInput<10>(IoStatementState &, const DataEdit &, void *);
495 // TODO: double/double
496 template bool EditRealInput<16>(IoStatementState &, const DataEdit &, void *);
497 } // namespace Fortran::runtime::io
498