1 //===-- runtime/io-stmt.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 "io-stmt.h"
10 #include "connection.h"
11 #include "format.h"
12 #include "tools.h"
13 #include "unit.h"
14 #include "flang/Runtime/memory.h"
15 #include <algorithm>
16 #include <cstdio>
17 #include <cstring>
18 #include <limits>
19 
20 namespace Fortran::runtime::io {
21 
22 int IoStatementBase::EndIoStatement() { return GetIoStat(); }
23 
24 bool IoStatementBase::Emit(const char *, std::size_t, std::size_t) {
25   return false;
26 }
27 
28 bool IoStatementBase::Emit(const char *, std::size_t) { return false; }
29 
30 bool IoStatementBase::Emit(const char16_t *, std::size_t) { return false; }
31 
32 bool IoStatementBase::Emit(const char32_t *, std::size_t) { return false; }
33 
34 std::size_t IoStatementBase::GetNextInputBytes(const char *&p) {
35   p = nullptr;
36   return 0;
37 }
38 
39 bool IoStatementBase::AdvanceRecord(int) { return false; }
40 
41 void IoStatementBase::BackspaceRecord() {}
42 
43 bool IoStatementBase::Receive(char *, std::size_t, std::size_t) {
44   return false;
45 }
46 
47 std::optional<DataEdit> IoStatementBase::GetNextDataEdit(
48     IoStatementState &, int) {
49   return std::nullopt;
50 }
51 
52 ExternalFileUnit *IoStatementBase::GetExternalFileUnit() const {
53   return nullptr;
54 }
55 
56 bool IoStatementBase::BeginReadingRecord() { return true; }
57 
58 void IoStatementBase::FinishReadingRecord() {}
59 
60 void IoStatementBase::HandleAbsolutePosition(std::int64_t) {}
61 
62 void IoStatementBase::HandleRelativePosition(std::int64_t) {}
63 
64 bool IoStatementBase::Inquire(InquiryKeywordHash, char *, std::size_t) {
65   return false;
66 }
67 
68 bool IoStatementBase::Inquire(InquiryKeywordHash, bool &) { return false; }
69 
70 bool IoStatementBase::Inquire(InquiryKeywordHash, std::int64_t, bool &) {
71   return false;
72 }
73 
74 bool IoStatementBase::Inquire(InquiryKeywordHash, std::int64_t &) {
75   return false;
76 }
77 
78 void IoStatementBase::BadInquiryKeywordHashCrash(InquiryKeywordHash inquiry) {
79   char buffer[16];
80   const char *decode{InquiryKeywordHashDecode(buffer, sizeof buffer, inquiry)};
81   Crash("bad InquiryKeywordHash 0x%x (%s)", inquiry,
82       decode ? decode : "(cannot decode)");
83 }
84 
85 template <Direction DIR, typename CHAR>
86 InternalIoStatementState<DIR, CHAR>::InternalIoStatementState(
87     Buffer scalar, std::size_t length, const char *sourceFile, int sourceLine)
88     : IoStatementBase{sourceFile, sourceLine}, unit_{scalar, length} {}
89 
90 template <Direction DIR, typename CHAR>
91 InternalIoStatementState<DIR, CHAR>::InternalIoStatementState(
92     const Descriptor &d, const char *sourceFile, int sourceLine)
93     : IoStatementBase{sourceFile, sourceLine}, unit_{d, *this} {}
94 
95 template <Direction DIR, typename CHAR>
96 bool InternalIoStatementState<DIR, CHAR>::Emit(
97     const CharType *data, std::size_t chars) {
98   if constexpr (DIR == Direction::Input) {
99     Crash("InternalIoStatementState<Direction::Input>::Emit() called");
100     return false;
101   }
102   return unit_.Emit(data, chars * sizeof(CharType), *this);
103 }
104 
105 template <Direction DIR, typename CHAR>
106 std::size_t InternalIoStatementState<DIR, CHAR>::GetNextInputBytes(
107     const char *&p) {
108   return unit_.GetNextInputBytes(p, *this);
109 }
110 
111 template <Direction DIR, typename CHAR>
112 bool InternalIoStatementState<DIR, CHAR>::AdvanceRecord(int n) {
113   while (n-- > 0) {
114     if (!unit_.AdvanceRecord(*this)) {
115       return false;
116     }
117   }
118   return true;
119 }
120 
121 template <Direction DIR, typename CHAR>
122 void InternalIoStatementState<DIR, CHAR>::BackspaceRecord() {
123   unit_.BackspaceRecord(*this);
124 }
125 
126 template <Direction DIR, typename CHAR>
127 int InternalIoStatementState<DIR, CHAR>::EndIoStatement() {
128   if constexpr (DIR == Direction::Output) {
129     unit_.EndIoStatement(); // fill
130   }
131   auto result{IoStatementBase::EndIoStatement()};
132   if (free_) {
133     FreeMemory(this);
134   }
135   return result;
136 }
137 
138 template <Direction DIR, typename CHAR>
139 void InternalIoStatementState<DIR, CHAR>::HandleAbsolutePosition(
140     std::int64_t n) {
141   return unit_.HandleAbsolutePosition(n);
142 }
143 
144 template <Direction DIR, typename CHAR>
145 void InternalIoStatementState<DIR, CHAR>::HandleRelativePosition(
146     std::int64_t n) {
147   return unit_.HandleRelativePosition(n);
148 }
149 
150 template <Direction DIR, typename CHAR>
151 InternalFormattedIoStatementState<DIR, CHAR>::InternalFormattedIoStatementState(
152     Buffer buffer, std::size_t length, const CHAR *format,
153     std::size_t formatLength, const char *sourceFile, int sourceLine)
154     : InternalIoStatementState<DIR, CHAR>{buffer, length, sourceFile,
155           sourceLine},
156       ioStatementState_{*this}, format_{*this, format, formatLength} {}
157 
158 template <Direction DIR, typename CHAR>
159 InternalFormattedIoStatementState<DIR, CHAR>::InternalFormattedIoStatementState(
160     const Descriptor &d, const CHAR *format, std::size_t formatLength,
161     const char *sourceFile, int sourceLine)
162     : InternalIoStatementState<DIR, CHAR>{d, sourceFile, sourceLine},
163       ioStatementState_{*this}, format_{*this, format, formatLength} {}
164 
165 template <Direction DIR, typename CHAR>
166 int InternalFormattedIoStatementState<DIR, CHAR>::EndIoStatement() {
167   if constexpr (DIR == Direction::Output) {
168     format_.Finish(*this); // ignore any remaining input positioning actions
169   }
170   return InternalIoStatementState<DIR, CHAR>::EndIoStatement();
171 }
172 
173 template <Direction DIR, typename CHAR>
174 InternalListIoStatementState<DIR, CHAR>::InternalListIoStatementState(
175     Buffer buffer, std::size_t length, const char *sourceFile, int sourceLine)
176     : InternalIoStatementState<DIR, CharType>{buffer, length, sourceFile,
177           sourceLine},
178       ioStatementState_{*this} {}
179 
180 template <Direction DIR, typename CHAR>
181 InternalListIoStatementState<DIR, CHAR>::InternalListIoStatementState(
182     const Descriptor &d, const char *sourceFile, int sourceLine)
183     : InternalIoStatementState<DIR, CharType>{d, sourceFile, sourceLine},
184       ioStatementState_{*this} {}
185 
186 ExternalIoStatementBase::ExternalIoStatementBase(
187     ExternalFileUnit &unit, const char *sourceFile, int sourceLine)
188     : IoStatementBase{sourceFile, sourceLine}, unit_{unit} {}
189 
190 MutableModes &ExternalIoStatementBase::mutableModes() { return unit_.modes; }
191 
192 ConnectionState &ExternalIoStatementBase::GetConnectionState() { return unit_; }
193 
194 int ExternalIoStatementBase::EndIoStatement() {
195   if (mutableModes().nonAdvancing) {
196     unit_.leftTabLimit = unit_.furthestPositionInRecord;
197   } else {
198     unit_.leftTabLimit.reset();
199   }
200   auto result{IoStatementBase::EndIoStatement()};
201   unit_.EndIoStatement(); // annihilates *this in unit_.u_
202   return result;
203 }
204 
205 void OpenStatementState::set_path(const char *path, std::size_t length) {
206   pathLength_ = TrimTrailingSpaces(path, length);
207   path_ = SaveDefaultCharacter(path, pathLength_, *this);
208 }
209 
210 int OpenStatementState::EndIoStatement() {
211   if (path_.get() || wasExtant_ ||
212       (status_ && *status_ == OpenStatus::Scratch)) {
213     unit().OpenUnit(status_, action_, position_, std::move(path_), pathLength_,
214         convert_, *this);
215   } else {
216     unit().OpenAnonymousUnit(status_, action_, position_, convert_, *this);
217   }
218   if (access_) {
219     if (*access_ != unit().access) {
220       if (wasExtant_) {
221         SignalError("ACCESS= may not be changed on an open unit");
222       }
223     }
224     unit().access = *access_;
225   }
226   if (!unit().isUnformatted) {
227     unit().isUnformatted = isUnformatted_;
228   }
229   if (isUnformatted_ && *isUnformatted_ != *unit().isUnformatted) {
230     if (wasExtant_) {
231       SignalError("FORM= may not be changed on an open unit");
232     }
233     unit().isUnformatted = *isUnformatted_;
234   }
235   if (!unit().isUnformatted) {
236     // Set default format (C.7.4 point 2).
237     unit().isUnformatted = unit().access != Access::Sequential;
238   }
239   return ExternalIoStatementBase::EndIoStatement();
240 }
241 
242 int CloseStatementState::EndIoStatement() {
243   int result{ExternalIoStatementBase::EndIoStatement()};
244   unit().CloseUnit(status_, *this);
245   unit().DestroyClosed();
246   return result;
247 }
248 
249 int NoUnitIoStatementState::EndIoStatement() {
250   auto result{IoStatementBase::EndIoStatement()};
251   FreeMemory(this);
252   return result;
253 }
254 
255 template <Direction DIR>
256 ExternalIoStatementState<DIR>::ExternalIoStatementState(
257     ExternalFileUnit &unit, const char *sourceFile, int sourceLine)
258     : ExternalIoStatementBase{unit, sourceFile, sourceLine}, mutableModes_{
259                                                                  unit.modes} {
260   if constexpr (DIR == Direction::Output) {
261     // If the last statement was a non advancing IO input statement, the unit
262     // furthestPositionInRecord was not advanced, but the positionInRecord may
263     // have been advanced. Advance furthestPositionInRecord here to avoid
264     // overwriting the part of the record that has been read with blanks.
265     unit.furthestPositionInRecord =
266         std::max(unit.furthestPositionInRecord, unit.positionInRecord);
267   }
268 }
269 
270 template <Direction DIR> int ExternalIoStatementState<DIR>::EndIoStatement() {
271   if constexpr (DIR == Direction::Input) {
272     BeginReadingRecord(); // in case there were no I/O items
273     if (!mutableModes().nonAdvancing || GetIoStat() == IostatEor) {
274       FinishReadingRecord();
275     }
276   } else {
277     if (!mutableModes().nonAdvancing) {
278       unit().AdvanceRecord(*this);
279     }
280     unit().FlushIfTerminal(*this);
281   }
282   return ExternalIoStatementBase::EndIoStatement();
283 }
284 
285 template <Direction DIR>
286 bool ExternalIoStatementState<DIR>::Emit(
287     const char *data, std::size_t bytes, std::size_t elementBytes) {
288   if constexpr (DIR == Direction::Input) {
289     Crash("ExternalIoStatementState::Emit(char) called for input statement");
290   }
291   return unit().Emit(data, bytes, elementBytes, *this);
292 }
293 
294 template <Direction DIR>
295 bool ExternalIoStatementState<DIR>::Emit(const char *data, std::size_t bytes) {
296   if constexpr (DIR == Direction::Input) {
297     Crash("ExternalIoStatementState::Emit(char) called for input statement");
298   }
299   return unit().Emit(data, bytes, 0, *this);
300 }
301 
302 template <Direction DIR>
303 bool ExternalIoStatementState<DIR>::Emit(
304     const char16_t *data, std::size_t chars) {
305   if constexpr (DIR == Direction::Input) {
306     Crash(
307         "ExternalIoStatementState::Emit(char16_t) called for input statement");
308   }
309   // TODO: UTF-8 encoding
310   return unit().Emit(reinterpret_cast<const char *>(data), chars * sizeof *data,
311       sizeof *data, *this);
312 }
313 
314 template <Direction DIR>
315 bool ExternalIoStatementState<DIR>::Emit(
316     const char32_t *data, std::size_t chars) {
317   if constexpr (DIR == Direction::Input) {
318     Crash(
319         "ExternalIoStatementState::Emit(char32_t) called for input statement");
320   }
321   // TODO: UTF-8 encoding
322   return unit().Emit(reinterpret_cast<const char *>(data), chars * sizeof *data,
323       sizeof *data, *this);
324 }
325 
326 template <Direction DIR>
327 std::size_t ExternalIoStatementState<DIR>::GetNextInputBytes(const char *&p) {
328   return unit().GetNextInputBytes(p, *this);
329 }
330 
331 template <Direction DIR>
332 bool ExternalIoStatementState<DIR>::AdvanceRecord(int n) {
333   while (n-- > 0) {
334     if (!unit().AdvanceRecord(*this)) {
335       return false;
336     }
337   }
338   return true;
339 }
340 
341 template <Direction DIR> void ExternalIoStatementState<DIR>::BackspaceRecord() {
342   unit().BackspaceRecord(*this);
343 }
344 
345 template <Direction DIR>
346 void ExternalIoStatementState<DIR>::HandleAbsolutePosition(std::int64_t n) {
347   return unit().HandleAbsolutePosition(n);
348 }
349 
350 template <Direction DIR>
351 void ExternalIoStatementState<DIR>::HandleRelativePosition(std::int64_t n) {
352   return unit().HandleRelativePosition(n);
353 }
354 
355 template <Direction DIR>
356 bool ExternalIoStatementState<DIR>::BeginReadingRecord() {
357   if constexpr (DIR == Direction::Input) {
358     return unit().BeginReadingRecord(*this);
359   } else {
360     Crash("ExternalIoStatementState<Direction::Output>::BeginReadingRecord() "
361           "called");
362     return false;
363   }
364 }
365 
366 template <Direction DIR>
367 void ExternalIoStatementState<DIR>::FinishReadingRecord() {
368   if constexpr (DIR == Direction::Input) {
369     unit().FinishReadingRecord(*this);
370   } else {
371     Crash("ExternalIoStatementState<Direction::Output>::FinishReadingRecord() "
372           "called");
373   }
374 }
375 
376 template <Direction DIR, typename CHAR>
377 ExternalFormattedIoStatementState<DIR, CHAR>::ExternalFormattedIoStatementState(
378     ExternalFileUnit &unit, const CHAR *format, std::size_t formatLength,
379     const char *sourceFile, int sourceLine)
380     : ExternalIoStatementState<DIR>{unit, sourceFile, sourceLine},
381       format_{*this, format, formatLength} {}
382 
383 template <Direction DIR, typename CHAR>
384 int ExternalFormattedIoStatementState<DIR, CHAR>::EndIoStatement() {
385   if constexpr (DIR == Direction::Input) {
386     this->BeginReadingRecord(); // in case there were no I/O items
387   }
388   format_.Finish(*this);
389   return ExternalIoStatementState<DIR>::EndIoStatement();
390 }
391 
392 std::optional<DataEdit> IoStatementState::GetNextDataEdit(int n) {
393   return std::visit(
394       [&](auto &x) { return x.get().GetNextDataEdit(*this, n); }, u_);
395 }
396 
397 bool IoStatementState::Emit(
398     const char *data, std::size_t n, std::size_t elementBytes) {
399   return std::visit(
400       [=](auto &x) { return x.get().Emit(data, n, elementBytes); }, u_);
401 }
402 
403 bool IoStatementState::Emit(const char *data, std::size_t n) {
404   return std::visit([=](auto &x) { return x.get().Emit(data, n); }, u_);
405 }
406 
407 bool IoStatementState::Emit(const char16_t *data, std::size_t chars) {
408   return std::visit([=](auto &x) { return x.get().Emit(data, chars); }, u_);
409 }
410 
411 bool IoStatementState::Emit(const char32_t *data, std::size_t chars) {
412   return std::visit([=](auto &x) { return x.get().Emit(data, chars); }, u_);
413 }
414 
415 bool IoStatementState::Receive(
416     char *data, std::size_t n, std::size_t elementBytes) {
417   return std::visit(
418       [=](auto &x) { return x.get().Receive(data, n, elementBytes); }, u_);
419 }
420 
421 std::size_t IoStatementState::GetNextInputBytes(const char *&p) {
422   return std::visit([&](auto &x) { return x.get().GetNextInputBytes(p); }, u_);
423 }
424 
425 bool IoStatementState::AdvanceRecord(int n) {
426   return std::visit([=](auto &x) { return x.get().AdvanceRecord(n); }, u_);
427 }
428 
429 void IoStatementState::BackspaceRecord() {
430   std::visit([](auto &x) { x.get().BackspaceRecord(); }, u_);
431 }
432 
433 void IoStatementState::HandleRelativePosition(std::int64_t n) {
434   std::visit([=](auto &x) { x.get().HandleRelativePosition(n); }, u_);
435 }
436 
437 void IoStatementState::HandleAbsolutePosition(std::int64_t n) {
438   std::visit([=](auto &x) { x.get().HandleAbsolutePosition(n); }, u_);
439 }
440 
441 int IoStatementState::EndIoStatement() {
442   return std::visit([](auto &x) { return x.get().EndIoStatement(); }, u_);
443 }
444 
445 ConnectionState &IoStatementState::GetConnectionState() {
446   return std::visit(
447       [](auto &x) -> ConnectionState & { return x.get().GetConnectionState(); },
448       u_);
449 }
450 
451 MutableModes &IoStatementState::mutableModes() {
452   return std::visit(
453       [](auto &x) -> MutableModes & { return x.get().mutableModes(); }, u_);
454 }
455 
456 bool IoStatementState::BeginReadingRecord() {
457   return std::visit([](auto &x) { return x.get().BeginReadingRecord(); }, u_);
458 }
459 
460 IoErrorHandler &IoStatementState::GetIoErrorHandler() const {
461   return std::visit(
462       [](auto &x) -> IoErrorHandler & {
463         return static_cast<IoErrorHandler &>(x.get());
464       },
465       u_);
466 }
467 
468 ExternalFileUnit *IoStatementState::GetExternalFileUnit() const {
469   return std::visit([](auto &x) { return x.get().GetExternalFileUnit(); }, u_);
470 }
471 
472 bool IoStatementState::EmitRepeated(char ch, std::size_t n) {
473   return std::visit(
474       [=](auto &x) {
475         for (std::size_t j{0}; j < n; ++j) {
476           if (!x.get().Emit(&ch, 1)) {
477             return false;
478           }
479         }
480         return true;
481       },
482       u_);
483 }
484 
485 bool IoStatementState::EmitField(
486     const char *p, std::size_t length, std::size_t width) {
487   if (width <= 0) {
488     width = static_cast<int>(length);
489   }
490   if (length > static_cast<std::size_t>(width)) {
491     return EmitRepeated('*', width);
492   } else {
493     return EmitRepeated(' ', static_cast<int>(width - length)) &&
494         Emit(p, length);
495   }
496 }
497 
498 bool IoStatementState::Inquire(
499     InquiryKeywordHash inquiry, char *out, std::size_t chars) {
500   return std::visit(
501       [&](auto &x) { return x.get().Inquire(inquiry, out, chars); }, u_);
502 }
503 
504 bool IoStatementState::Inquire(InquiryKeywordHash inquiry, bool &out) {
505   return std::visit([&](auto &x) { return x.get().Inquire(inquiry, out); }, u_);
506 }
507 
508 bool IoStatementState::Inquire(
509     InquiryKeywordHash inquiry, std::int64_t id, bool &out) {
510   return std::visit(
511       [&](auto &x) { return x.get().Inquire(inquiry, id, out); }, u_);
512 }
513 
514 bool IoStatementState::Inquire(InquiryKeywordHash inquiry, std::int64_t &n) {
515   return std::visit([&](auto &x) { return x.get().Inquire(inquiry, n); }, u_);
516 }
517 
518 void IoStatementState::GotChar(int n) {
519   if (auto *formattedIn{
520           get_if<FormattedIoStatementState<Direction::Input>>()}) {
521     formattedIn->GotChar(n);
522   } else {
523     GetIoErrorHandler().Crash("IoStatementState::GotChar() called for "
524                               "statement that is not formatted input");
525   }
526 }
527 
528 std::size_t
529 FormattedIoStatementState<Direction::Input>::GetEditDescriptorChars() const {
530   return chars_;
531 }
532 
533 void FormattedIoStatementState<Direction::Input>::GotChar(int n) {
534   chars_ += n;
535 }
536 
537 bool ListDirectedStatementState<Direction::Output>::EmitLeadingSpaceOrAdvance(
538     IoStatementState &io, std::size_t length, bool isCharacter) {
539   if (length == 0) {
540     return true;
541   }
542   const ConnectionState &connection{io.GetConnectionState()};
543   int space{connection.positionInRecord == 0 ||
544       !(isCharacter && lastWasUndelimitedCharacter())};
545   set_lastWasUndelimitedCharacter(false);
546   if (connection.NeedAdvance(space + length)) {
547     return io.AdvanceRecord();
548   }
549   if (space) {
550     return io.Emit(" ", 1);
551   }
552   return true;
553 }
554 
555 std::optional<DataEdit>
556 ListDirectedStatementState<Direction::Output>::GetNextDataEdit(
557     IoStatementState &io, int maxRepeat) {
558   DataEdit edit;
559   edit.descriptor = DataEdit::ListDirected;
560   edit.repeat = maxRepeat;
561   edit.modes = io.mutableModes();
562   return edit;
563 }
564 
565 std::optional<DataEdit>
566 ListDirectedStatementState<Direction::Input>::GetNextDataEdit(
567     IoStatementState &io, int maxRepeat) {
568   // N.B. list-directed transfers cannot be nonadvancing (C1221)
569   ConnectionState &connection{io.GetConnectionState()};
570   DataEdit edit;
571   edit.descriptor = DataEdit::ListDirected;
572   edit.repeat = 1; // may be overridden below
573   edit.modes = connection.modes;
574   if (hitSlash_) { // everything after '/' is nullified
575     edit.descriptor = DataEdit::ListDirectedNullValue;
576     return edit;
577   }
578   char32_t comma{','};
579   if (io.mutableModes().editingFlags & decimalComma) {
580     comma = ';';
581   }
582   if (remaining_ > 0 && !realPart_) { // "r*c" repetition in progress
583     RUNTIME_CHECK(io.GetIoErrorHandler(), repeatPosition_.has_value());
584     repeatPosition_.reset(); // restores the saved position
585     if (!imaginaryPart_) {
586       edit.repeat = std::min<int>(remaining_, maxRepeat);
587       auto ch{io.GetCurrentChar()};
588       if (!ch || *ch == ' ' || *ch == '\t' || *ch == comma) {
589         // "r*" repeated null
590         edit.descriptor = DataEdit::ListDirectedNullValue;
591       }
592     }
593     remaining_ -= edit.repeat;
594     if (remaining_ > 0) {
595       repeatPosition_.emplace(io);
596     }
597     return edit;
598   }
599   // Skip separators, handle a "r*c" repeat count; see 13.10.2 in Fortran 2018
600   if (imaginaryPart_) {
601     imaginaryPart_ = false;
602   } else if (realPart_) {
603     realPart_ = false;
604     imaginaryPart_ = true;
605     edit.descriptor = DataEdit::ListDirectedImaginaryPart;
606   }
607   auto ch{io.GetNextNonBlank()};
608   if (ch && *ch == comma && eatComma_) {
609     // Consume comma & whitespace after previous item.
610     // This includes the comma between real and imaginary components
611     // in list-directed/NAMELIST complex input.
612     io.HandleRelativePosition(1);
613     ch = io.GetNextNonBlank();
614   }
615   eatComma_ = true;
616   if (!ch) {
617     return std::nullopt;
618   }
619   if (*ch == '/') {
620     hitSlash_ = true;
621     edit.descriptor = DataEdit::ListDirectedNullValue;
622     return edit;
623   }
624   if (*ch == comma) { // separator: null value
625     edit.descriptor = DataEdit::ListDirectedNullValue;
626     return edit;
627   }
628   if (imaginaryPart_) { // can't repeat components
629     return edit;
630   }
631   if (*ch >= '0' && *ch <= '9') { // look for "r*" repetition count
632     auto start{connection.positionInRecord};
633     int r{0};
634     do {
635       static auto constexpr clamp{(std::numeric_limits<int>::max() - '9') / 10};
636       if (r >= clamp) {
637         r = 0;
638         break;
639       }
640       r = 10 * r + (*ch - '0');
641       io.HandleRelativePosition(1);
642       ch = io.GetCurrentChar();
643     } while (ch && *ch >= '0' && *ch <= '9');
644     if (r > 0 && ch && *ch == '*') { // subtle: r must be nonzero
645       io.HandleRelativePosition(1);
646       ch = io.GetCurrentChar();
647       if (ch && *ch == '/') { // r*/
648         hitSlash_ = true;
649         edit.descriptor = DataEdit::ListDirectedNullValue;
650         return edit;
651       }
652       if (!ch || *ch == ' ' || *ch == '\t' || *ch == comma) { // "r*" null
653         edit.descriptor = DataEdit::ListDirectedNullValue;
654       }
655       edit.repeat = std::min<int>(r, maxRepeat);
656       remaining_ = r - edit.repeat;
657       if (remaining_ > 0) {
658         repeatPosition_.emplace(io);
659       }
660     } else { // not a repetition count, just an integer value; rewind
661       connection.positionInRecord = start;
662     }
663   }
664   if (!imaginaryPart_ && ch && *ch == '(') {
665     realPart_ = true;
666     io.HandleRelativePosition(1);
667     edit.descriptor = DataEdit::ListDirectedRealPart;
668   }
669   return edit;
670 }
671 
672 template <Direction DIR>
673 bool ExternalUnformattedIoStatementState<DIR>::Receive(
674     char *data, std::size_t bytes, std::size_t elementBytes) {
675   if constexpr (DIR == Direction::Output) {
676     this->Crash("ExternalUnformattedIoStatementState::Receive() called for "
677                 "output statement");
678   }
679   return this->unit().Receive(data, bytes, elementBytes, *this);
680 }
681 
682 template <Direction DIR>
683 ChildIoStatementState<DIR>::ChildIoStatementState(
684     ChildIo &child, const char *sourceFile, int sourceLine)
685     : IoStatementBase{sourceFile, sourceLine}, child_{child} {}
686 
687 template <Direction DIR>
688 MutableModes &ChildIoStatementState<DIR>::mutableModes() {
689   return child_.parent().mutableModes();
690 }
691 
692 template <Direction DIR>
693 ConnectionState &ChildIoStatementState<DIR>::GetConnectionState() {
694   return child_.parent().GetConnectionState();
695 }
696 
697 template <Direction DIR>
698 ExternalFileUnit *ChildIoStatementState<DIR>::GetExternalFileUnit() const {
699   return child_.parent().GetExternalFileUnit();
700 }
701 
702 template <Direction DIR> int ChildIoStatementState<DIR>::EndIoStatement() {
703   auto result{IoStatementBase::EndIoStatement()};
704   child_.EndIoStatement(); // annihilates *this in child_.u_
705   return result;
706 }
707 
708 template <Direction DIR>
709 bool ChildIoStatementState<DIR>::Emit(
710     const char *data, std::size_t bytes, std::size_t elementBytes) {
711   return child_.parent().Emit(data, bytes, elementBytes);
712 }
713 
714 template <Direction DIR>
715 bool ChildIoStatementState<DIR>::Emit(const char *data, std::size_t bytes) {
716   return child_.parent().Emit(data, bytes);
717 }
718 
719 template <Direction DIR>
720 bool ChildIoStatementState<DIR>::Emit(const char16_t *data, std::size_t chars) {
721   return child_.parent().Emit(data, chars);
722 }
723 
724 template <Direction DIR>
725 bool ChildIoStatementState<DIR>::Emit(const char32_t *data, std::size_t chars) {
726   return child_.parent().Emit(data, chars);
727 }
728 
729 template <Direction DIR>
730 std::size_t ChildIoStatementState<DIR>::GetNextInputBytes(const char *&p) {
731   return child_.parent().GetNextInputBytes(p);
732 }
733 
734 template <Direction DIR>
735 void ChildIoStatementState<DIR>::HandleAbsolutePosition(std::int64_t n) {
736   return child_.parent().HandleAbsolutePosition(n);
737 }
738 
739 template <Direction DIR>
740 void ChildIoStatementState<DIR>::HandleRelativePosition(std::int64_t n) {
741   return child_.parent().HandleRelativePosition(n);
742 }
743 
744 template <Direction DIR, typename CHAR>
745 ChildFormattedIoStatementState<DIR, CHAR>::ChildFormattedIoStatementState(
746     ChildIo &child, const CHAR *format, std::size_t formatLength,
747     const char *sourceFile, int sourceLine)
748     : ChildIoStatementState<DIR>{child, sourceFile, sourceLine},
749       mutableModes_{child.parent().mutableModes()}, format_{*this, format,
750                                                         formatLength} {}
751 
752 template <Direction DIR, typename CHAR>
753 int ChildFormattedIoStatementState<DIR, CHAR>::EndIoStatement() {
754   format_.Finish(*this);
755   return ChildIoStatementState<DIR>::EndIoStatement();
756 }
757 
758 template <Direction DIR, typename CHAR>
759 bool ChildFormattedIoStatementState<DIR, CHAR>::AdvanceRecord(int) {
760   return false; // no can do in a child I/O
761 }
762 
763 template <Direction DIR>
764 bool ChildUnformattedIoStatementState<DIR>::Receive(
765     char *data, std::size_t bytes, std::size_t elementBytes) {
766   return this->child().parent().Receive(data, bytes, elementBytes);
767 }
768 
769 template class InternalIoStatementState<Direction::Output>;
770 template class InternalIoStatementState<Direction::Input>;
771 template class InternalFormattedIoStatementState<Direction::Output>;
772 template class InternalFormattedIoStatementState<Direction::Input>;
773 template class InternalListIoStatementState<Direction::Output>;
774 template class InternalListIoStatementState<Direction::Input>;
775 template class ExternalIoStatementState<Direction::Output>;
776 template class ExternalIoStatementState<Direction::Input>;
777 template class ExternalFormattedIoStatementState<Direction::Output>;
778 template class ExternalFormattedIoStatementState<Direction::Input>;
779 template class ExternalListIoStatementState<Direction::Output>;
780 template class ExternalListIoStatementState<Direction::Input>;
781 template class ExternalUnformattedIoStatementState<Direction::Output>;
782 template class ExternalUnformattedIoStatementState<Direction::Input>;
783 template class ChildIoStatementState<Direction::Output>;
784 template class ChildIoStatementState<Direction::Input>;
785 template class ChildFormattedIoStatementState<Direction::Output>;
786 template class ChildFormattedIoStatementState<Direction::Input>;
787 template class ChildListIoStatementState<Direction::Output>;
788 template class ChildListIoStatementState<Direction::Input>;
789 template class ChildUnformattedIoStatementState<Direction::Output>;
790 template class ChildUnformattedIoStatementState<Direction::Input>;
791 
792 int ExternalMiscIoStatementState::EndIoStatement() {
793   ExternalFileUnit &ext{unit()};
794   switch (which_) {
795   case Flush:
796     ext.FlushOutput(*this);
797     std::fflush(nullptr); // flushes C stdio output streams (12.9(2))
798     break;
799   case Backspace:
800     ext.BackspaceRecord(*this);
801     break;
802   case Endfile:
803     ext.Endfile(*this);
804     break;
805   case Rewind:
806     ext.Rewind(*this);
807     break;
808   }
809   return ExternalIoStatementBase::EndIoStatement();
810 }
811 
812 InquireUnitState::InquireUnitState(
813     ExternalFileUnit &unit, const char *sourceFile, int sourceLine)
814     : ExternalIoStatementBase{unit, sourceFile, sourceLine} {}
815 
816 bool InquireUnitState::Inquire(
817     InquiryKeywordHash inquiry, char *result, std::size_t length) {
818   if (unit().createdForInternalChildIo()) {
819     SignalError(IostatInquireInternalUnit,
820         "INQUIRE of unit created for defined derived type I/O of an internal "
821         "unit");
822     return false;
823   }
824   const char *str{nullptr};
825   switch (inquiry) {
826   case HashInquiryKeyword("ACCESS"):
827     switch (unit().access) {
828     case Access::Sequential:
829       str = "SEQUENTIAL";
830       break;
831     case Access::Direct:
832       str = "DIRECT";
833       break;
834     case Access::Stream:
835       str = "STREAM";
836       break;
837     }
838     break;
839   case HashInquiryKeyword("ACTION"):
840     str = unit().mayWrite() ? unit().mayRead() ? "READWRITE" : "WRITE" : "READ";
841     break;
842   case HashInquiryKeyword("ASYNCHRONOUS"):
843     str = unit().mayAsynchronous() ? "YES" : "NO";
844     break;
845   case HashInquiryKeyword("BLANK"):
846     str = unit().isUnformatted.value_or(true)   ? "UNDEFINED"
847         : unit().modes.editingFlags & blankZero ? "ZERO"
848                                                 : "NULL";
849     break;
850   case HashInquiryKeyword("CARRIAGECONTROL"):
851     str = "LIST";
852     break;
853   case HashInquiryKeyword("CONVERT"):
854     str = unit().swapEndianness() ? "SWAP" : "NATIVE";
855     break;
856   case HashInquiryKeyword("DECIMAL"):
857     str = unit().isUnformatted.value_or(true)      ? "UNDEFINED"
858         : unit().modes.editingFlags & decimalComma ? "COMMA"
859                                                    : "POINT";
860     break;
861   case HashInquiryKeyword("DELIM"):
862     if (unit().isUnformatted.value_or(true)) {
863       str = "UNDEFINED";
864     } else {
865       switch (unit().modes.delim) {
866       case '\'':
867         str = "APOSTROPHE";
868         break;
869       case '"':
870         str = "QUOTE";
871         break;
872       default:
873         str = "NONE";
874         break;
875       }
876     }
877     break;
878   case HashInquiryKeyword("DIRECT"):
879     str = unit().access == Access::Direct ||
880             (unit().mayPosition() && unit().isFixedRecordLength)
881         ? "YES"
882         : "NO";
883     break;
884   case HashInquiryKeyword("ENCODING"):
885     str = unit().isUnformatted.value_or(true) ? "UNDEFINED"
886         : unit().isUTF8                       ? "UTF-8"
887                                               : "ASCII";
888     break;
889   case HashInquiryKeyword("FORM"):
890     str = !unit().isUnformatted ? "UNDEFINED"
891         : *unit().isUnformatted ? "UNFORMATTED"
892                                 : "FORMATTED";
893     break;
894   case HashInquiryKeyword("FORMATTED"):
895     str = !unit().isUnformatted ? "UNKNOWN"
896         : *unit().isUnformatted ? "NO"
897                                 : "YES";
898     break;
899   case HashInquiryKeyword("NAME"):
900     str = unit().path();
901     if (!str) {
902       return true; // result is undefined
903     }
904     break;
905   case HashInquiryKeyword("PAD"):
906     str = unit().isUnformatted.value_or(true) ? "UNDEFINED"
907         : unit().modes.pad                    ? "YES"
908                                               : "NO";
909     break;
910   case HashInquiryKeyword("POSITION"):
911     if (unit().access == Access::Direct) {
912       str = "UNDEFINED";
913     } else {
914       auto size{unit().knownSize()};
915       auto pos{unit().position()};
916       if (pos == size.value_or(pos + 1)) {
917         str = "APPEND";
918       } else if (pos == 0 && unit().mayPosition()) {
919         str = "REWIND";
920       } else {
921         str = "ASIS"; // processor-dependent & no common behavior
922       }
923     }
924     break;
925   case HashInquiryKeyword("READ"):
926     str = unit().mayRead() ? "YES" : "NO";
927     break;
928   case HashInquiryKeyword("READWRITE"):
929     str = unit().mayRead() && unit().mayWrite() ? "YES" : "NO";
930     break;
931   case HashInquiryKeyword("ROUND"):
932     if (unit().isUnformatted.value_or(true)) {
933       str = "UNDEFINED";
934     } else {
935       switch (unit().modes.round) {
936       case decimal::FortranRounding::RoundNearest:
937         str = "NEAREST";
938         break;
939       case decimal::FortranRounding::RoundUp:
940         str = "UP";
941         break;
942       case decimal::FortranRounding::RoundDown:
943         str = "DOWN";
944         break;
945       case decimal::FortranRounding::RoundToZero:
946         str = "ZERO";
947         break;
948       case decimal::FortranRounding::RoundCompatible:
949         str = "COMPATIBLE";
950         break;
951       }
952     }
953     break;
954   case HashInquiryKeyword("SEQUENTIAL"):
955     // "NO" for Direct, since Sequential would not work if
956     // the unit were reopened without RECL=.
957     str = unit().access == Access::Sequential ? "YES" : "NO";
958     break;
959   case HashInquiryKeyword("SIGN"):
960     str = unit().isUnformatted.value_or(true)  ? "UNDEFINED"
961         : unit().modes.editingFlags & signPlus ? "PLUS"
962                                                : "SUPPRESS";
963     break;
964   case HashInquiryKeyword("STREAM"):
965     str = unit().access == Access::Stream ? "YES" : "NO";
966     break;
967   case HashInquiryKeyword("WRITE"):
968     str = unit().mayWrite() ? "YES" : "NO";
969     break;
970   case HashInquiryKeyword("UNFORMATTED"):
971     str = !unit().isUnformatted ? "UNKNOWN"
972         : *unit().isUnformatted ? "YES"
973                                 : "NO";
974     break;
975   }
976   if (str) {
977     ToFortranDefaultCharacter(result, length, str);
978     return true;
979   } else {
980     BadInquiryKeywordHashCrash(inquiry);
981     return false;
982   }
983 }
984 
985 bool InquireUnitState::Inquire(InquiryKeywordHash inquiry, bool &result) {
986   switch (inquiry) {
987   case HashInquiryKeyword("EXIST"):
988     result = true;
989     return true;
990   case HashInquiryKeyword("NAMED"):
991     result = unit().path() != nullptr;
992     return true;
993   case HashInquiryKeyword("OPENED"):
994     result = true;
995     return true;
996   case HashInquiryKeyword("PENDING"):
997     result = false; // asynchronous I/O is not implemented
998     return true;
999   default:
1000     BadInquiryKeywordHashCrash(inquiry);
1001     return false;
1002   }
1003 }
1004 
1005 bool InquireUnitState::Inquire(
1006     InquiryKeywordHash inquiry, std::int64_t, bool &result) {
1007   switch (inquiry) {
1008   case HashInquiryKeyword("PENDING"):
1009     result = false; // asynchronous I/O is not implemented
1010     return true;
1011   default:
1012     BadInquiryKeywordHashCrash(inquiry);
1013     return false;
1014   }
1015 }
1016 
1017 bool InquireUnitState::Inquire(
1018     InquiryKeywordHash inquiry, std::int64_t &result) {
1019   switch (inquiry) {
1020   case HashInquiryKeyword("NEXTREC"):
1021     if (unit().access == Access::Direct) {
1022       result = unit().currentRecordNumber;
1023     }
1024     return true;
1025   case HashInquiryKeyword("NUMBER"):
1026     result = unit().unitNumber();
1027     return true;
1028   case HashInquiryKeyword("POS"):
1029     result = unit().position();
1030     return true;
1031   case HashInquiryKeyword("RECL"):
1032     if (unit().access == Access::Stream) {
1033       result = -2;
1034     } else if (unit().isFixedRecordLength && unit().recordLength) {
1035       result = *unit().recordLength;
1036     } else {
1037       result = std::numeric_limits<std::uint32_t>::max();
1038     }
1039     return true;
1040   case HashInquiryKeyword("SIZE"):
1041     if (auto size{unit().knownSize()}) {
1042       result = *size;
1043     } else {
1044       result = -1;
1045     }
1046     return true;
1047   default:
1048     BadInquiryKeywordHashCrash(inquiry);
1049     return false;
1050   }
1051 }
1052 
1053 InquireNoUnitState::InquireNoUnitState(const char *sourceFile, int sourceLine)
1054     : NoUnitIoStatementState{sourceFile, sourceLine, *this} {}
1055 
1056 bool InquireNoUnitState::Inquire(
1057     InquiryKeywordHash inquiry, char *result, std::size_t length) {
1058   switch (inquiry) {
1059   case HashInquiryKeyword("ACCESS"):
1060   case HashInquiryKeyword("ACTION"):
1061   case HashInquiryKeyword("ASYNCHRONOUS"):
1062   case HashInquiryKeyword("BLANK"):
1063   case HashInquiryKeyword("CARRIAGECONTROL"):
1064   case HashInquiryKeyword("CONVERT"):
1065   case HashInquiryKeyword("DECIMAL"):
1066   case HashInquiryKeyword("DELIM"):
1067   case HashInquiryKeyword("FORM"):
1068   case HashInquiryKeyword("NAME"):
1069   case HashInquiryKeyword("PAD"):
1070   case HashInquiryKeyword("POSITION"):
1071   case HashInquiryKeyword("ROUND"):
1072   case HashInquiryKeyword("SIGN"):
1073     ToFortranDefaultCharacter(result, length, "UNDEFINED");
1074     return true;
1075   case HashInquiryKeyword("DIRECT"):
1076   case HashInquiryKeyword("ENCODING"):
1077   case HashInquiryKeyword("FORMATTED"):
1078   case HashInquiryKeyword("READ"):
1079   case HashInquiryKeyword("READWRITE"):
1080   case HashInquiryKeyword("SEQUENTIAL"):
1081   case HashInquiryKeyword("STREAM"):
1082   case HashInquiryKeyword("WRITE"):
1083   case HashInquiryKeyword("UNFORMATTED"):
1084     ToFortranDefaultCharacter(result, length, "UNKNONN");
1085     return true;
1086   default:
1087     BadInquiryKeywordHashCrash(inquiry);
1088     return false;
1089   }
1090 }
1091 
1092 bool InquireNoUnitState::Inquire(InquiryKeywordHash inquiry, bool &result) {
1093   switch (inquiry) {
1094   case HashInquiryKeyword("EXIST"):
1095     result = true;
1096     return true;
1097   case HashInquiryKeyword("NAMED"):
1098   case HashInquiryKeyword("OPENED"):
1099   case HashInquiryKeyword("PENDING"):
1100     result = false;
1101     return true;
1102   default:
1103     BadInquiryKeywordHashCrash(inquiry);
1104     return false;
1105   }
1106 }
1107 
1108 bool InquireNoUnitState::Inquire(
1109     InquiryKeywordHash inquiry, std::int64_t, bool &result) {
1110   switch (inquiry) {
1111   case HashInquiryKeyword("PENDING"):
1112     result = false;
1113     return true;
1114   default:
1115     BadInquiryKeywordHashCrash(inquiry);
1116     return false;
1117   }
1118 }
1119 
1120 bool InquireNoUnitState::Inquire(
1121     InquiryKeywordHash inquiry, std::int64_t &result) {
1122   switch (inquiry) {
1123   case HashInquiryKeyword("NEXTREC"):
1124   case HashInquiryKeyword("NUMBER"):
1125   case HashInquiryKeyword("POS"):
1126   case HashInquiryKeyword("RECL"):
1127   case HashInquiryKeyword("SIZE"):
1128     result = -1;
1129     return true;
1130   default:
1131     BadInquiryKeywordHashCrash(inquiry);
1132     return false;
1133   }
1134 }
1135 
1136 InquireUnconnectedFileState::InquireUnconnectedFileState(
1137     OwningPtr<char> &&path, const char *sourceFile, int sourceLine)
1138     : NoUnitIoStatementState{sourceFile, sourceLine, *this}, path_{std::move(
1139                                                                  path)} {}
1140 
1141 bool InquireUnconnectedFileState::Inquire(
1142     InquiryKeywordHash inquiry, char *result, std::size_t length) {
1143   const char *str{nullptr};
1144   switch (inquiry) {
1145   case HashInquiryKeyword("ACCESS"):
1146   case HashInquiryKeyword("ACTION"):
1147   case HashInquiryKeyword("ASYNCHRONOUS"):
1148   case HashInquiryKeyword("BLANK"):
1149   case HashInquiryKeyword("CARRIAGECONTROL"):
1150   case HashInquiryKeyword("CONVERT"):
1151   case HashInquiryKeyword("DECIMAL"):
1152   case HashInquiryKeyword("DELIM"):
1153   case HashInquiryKeyword("FORM"):
1154   case HashInquiryKeyword("PAD"):
1155   case HashInquiryKeyword("POSITION"):
1156   case HashInquiryKeyword("ROUND"):
1157   case HashInquiryKeyword("SIGN"):
1158     str = "UNDEFINED";
1159     break;
1160   case HashInquiryKeyword("DIRECT"):
1161   case HashInquiryKeyword("ENCODING"):
1162   case HashInquiryKeyword("FORMATTED"):
1163   case HashInquiryKeyword("SEQUENTIAL"):
1164   case HashInquiryKeyword("STREAM"):
1165   case HashInquiryKeyword("UNFORMATTED"):
1166     str = "UNKNONN";
1167     break;
1168   case HashInquiryKeyword("READ"):
1169     str = MayRead(path_.get()) ? "YES" : "NO";
1170     break;
1171   case HashInquiryKeyword("READWRITE"):
1172     str = MayReadAndWrite(path_.get()) ? "YES" : "NO";
1173     break;
1174   case HashInquiryKeyword("WRITE"):
1175     str = MayWrite(path_.get()) ? "YES" : "NO";
1176     break;
1177   case HashInquiryKeyword("NAME"):
1178     str = path_.get();
1179     return true;
1180   }
1181   if (str) {
1182     ToFortranDefaultCharacter(result, length, str);
1183     return true;
1184   } else {
1185     BadInquiryKeywordHashCrash(inquiry);
1186     return false;
1187   }
1188 }
1189 
1190 bool InquireUnconnectedFileState::Inquire(
1191     InquiryKeywordHash inquiry, bool &result) {
1192   switch (inquiry) {
1193   case HashInquiryKeyword("EXIST"):
1194     result = IsExtant(path_.get());
1195     return true;
1196   case HashInquiryKeyword("NAMED"):
1197     result = true;
1198     return true;
1199   case HashInquiryKeyword("OPENED"):
1200     result = false;
1201     return true;
1202   case HashInquiryKeyword("PENDING"):
1203     result = false;
1204     return true;
1205   default:
1206     BadInquiryKeywordHashCrash(inquiry);
1207     return false;
1208   }
1209 }
1210 
1211 bool InquireUnconnectedFileState::Inquire(
1212     InquiryKeywordHash inquiry, std::int64_t, bool &result) {
1213   switch (inquiry) {
1214   case HashInquiryKeyword("PENDING"):
1215     result = false;
1216     return true;
1217   default:
1218     BadInquiryKeywordHashCrash(inquiry);
1219     return false;
1220   }
1221 }
1222 
1223 bool InquireUnconnectedFileState::Inquire(
1224     InquiryKeywordHash inquiry, std::int64_t &result) {
1225   switch (inquiry) {
1226   case HashInquiryKeyword("NEXTREC"):
1227   case HashInquiryKeyword("NUMBER"):
1228   case HashInquiryKeyword("POS"):
1229   case HashInquiryKeyword("RECL"):
1230   case HashInquiryKeyword("SIZE"):
1231     result = -1;
1232     return true;
1233   default:
1234     BadInquiryKeywordHashCrash(inquiry);
1235     return false;
1236   }
1237 }
1238 
1239 InquireIOLengthState::InquireIOLengthState(
1240     const char *sourceFile, int sourceLine)
1241     : NoUnitIoStatementState{sourceFile, sourceLine, *this} {}
1242 
1243 bool InquireIOLengthState::Emit(const char *, std::size_t n, std::size_t) {
1244   bytes_ += n;
1245   return true;
1246 }
1247 
1248 bool InquireIOLengthState::Emit(const char *p, std::size_t n) {
1249   bytes_ += sizeof *p * n;
1250   return true;
1251 }
1252 
1253 bool InquireIOLengthState::Emit(const char16_t *p, std::size_t n) {
1254   bytes_ += sizeof *p * n;
1255   return true;
1256 }
1257 
1258 bool InquireIOLengthState::Emit(const char32_t *p, std::size_t n) {
1259   bytes_ += sizeof *p * n;
1260   return true;
1261 }
1262 
1263 } // namespace Fortran::runtime::io
1264