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