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