1 //===-- runtime/format.h ----------------------------------------*- C++ -*-===//
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 // FORMAT string processing
10 
11 #ifndef FORTRAN_RUNTIME_FORMAT_H_
12 #define FORTRAN_RUNTIME_FORMAT_H_
13 
14 #include "environment.h"
15 #include "io-error.h"
16 #include "flang/Common/Fortran.h"
17 #include "flang/Decimal/decimal.h"
18 #include <cinttypes>
19 #include <optional>
20 
21 namespace Fortran::runtime::io {
22 
23 enum EditingFlags {
24   blankZero = 1, // BLANK=ZERO or BZ edit
25   decimalComma = 2, // DECIMAL=COMMA or DC edit
26   signPlus = 4, // SIGN=PLUS or SP edit
27 };
28 
29 struct MutableModes {
30   std::uint8_t editingFlags{0}; // BN, DP, SS
31   enum decimal::FortranRounding round{
32       executionEnvironment
33           .defaultOutputRoundingMode}; // RP/ROUND='PROCESSOR_DEFAULT'
34   bool pad{true}; // PAD= mode on READ
35   char delim{'\0'}; // DELIM=
36   short scale{0}; // kP
37   bool inNamelist{false}; // skip ! comments
38   bool nonAdvancing{false}; // ADVANCE='NO', or $ or \ in FORMAT
39 };
40 
41 // A single edit descriptor extracted from a FORMAT
42 struct DataEdit {
43   char descriptor; // capitalized: one of A, I, B, O, Z, F, E(N/S/X), D, G
44 
45   // Special internal data edit descriptors for list-directed & NAMELIST I/O
46   static constexpr char ListDirected{'g'}; // non-COMPLEX list-directed
47   static constexpr char ListDirectedRealPart{'r'}; // emit "(r," or "(r;"
48   static constexpr char ListDirectedImaginaryPart{'z'}; // emit "z)"
49   static constexpr char ListDirectedNullValue{'n'}; // see 13.10.3.2
IsListDirectedDataEdit50   constexpr bool IsListDirected() const {
51     return descriptor == ListDirected || descriptor == ListDirectedRealPart ||
52         descriptor == ListDirectedImaginaryPart;
53   }
54 
55   static constexpr char DefinedDerivedType{'d'}; // DT user-defined derived type
56 
57   char variation{'\0'}; // N, S, or X for EN, ES, EX
58   std::optional<int> width; // the 'w' field; optional for A
59   std::optional<int> digits; // the 'm' or 'd' field
60   std::optional<int> expoDigits; // 'Ee' field
61   MutableModes modes;
62   int repeat{1};
63 
64   // "iotype" &/or "v_list" values for a DT'iotype'(v_list)
65   // user-defined derived type data edit descriptor
66   static constexpr std::size_t maxIoTypeChars{32};
67   static constexpr std::size_t maxVListEntries{4};
68   std::uint8_t ioTypeChars{0};
69   std::uint8_t vListEntries{0};
70   char ioType[maxIoTypeChars];
71   int vList[maxVListEntries];
72 };
73 
74 // Generates a sequence of DataEdits from a FORMAT statement or
75 // default-CHARACTER string.  Driven by I/O item list processing.
76 // Errors are fatal.  See subclause 13.4 in Fortran 2018 for background.
77 template <typename CONTEXT> class FormatControl {
78 public:
79   using Context = CONTEXT;
80   using CharType = typename Context::CharType;
81 
FormatControl()82   FormatControl() {}
83   FormatControl(const Terminator &, const CharType *format,
84       std::size_t formatLength, int maxHeight = maxMaxHeight);
85 
86   // Determines the max parenthesis nesting level by scanning and validating
87   // the FORMAT string.
88   static int GetMaxParenthesisNesting(
89       IoErrorHandler &, const CharType *format, std::size_t formatLength);
90 
91   // For attempting to allocate in a user-supplied stack area
GetNeededSize(int maxHeight)92   static std::size_t GetNeededSize(int maxHeight) {
93     return sizeof(FormatControl) -
94         sizeof(Iteration) * (maxMaxHeight - maxHeight);
95   }
96 
97   // Extracts the next data edit descriptor, handling control edit descriptors
98   // along the way.  If maxRepeat==0, this is a peek at the next data edit
99   // descriptor.
100   DataEdit GetNextDataEdit(Context &, int maxRepeat = 1);
101 
102   // Emit any remaining character literals after the last data item (on output)
103   // and perform remaining record positioning actions.
104   void Finish(Context &);
105 
106 private:
107   static constexpr std::uint8_t maxMaxHeight{100};
108 
109   struct Iteration {
110     static constexpr int unlimited{-1};
111     int start{0}; // offset in format_ of '(' or a repeated edit descriptor
112     int remaining{0}; // while >0, decrement and iterate
113   };
114 
SkipBlanks()115   void SkipBlanks() {
116     while (offset_ < formatLength_ && format_[offset_] == ' ') {
117       ++offset_;
118     }
119   }
PeekNext()120   CharType PeekNext() {
121     SkipBlanks();
122     return offset_ < formatLength_ ? format_[offset_] : '\0';
123   }
GetNextChar(IoErrorHandler & handler)124   CharType GetNextChar(IoErrorHandler &handler) {
125     SkipBlanks();
126     if (offset_ >= formatLength_) {
127       handler.SignalError(
128           IostatErrorInFormat, "FORMAT missing at least one ')'");
129       return '\n';
130     }
131     return format_[offset_++];
132   }
133   int GetIntField(IoErrorHandler &, CharType firstCh = '\0');
134 
135   // Advances through the FORMAT until the next data edit
136   // descriptor has been found; handles control edit descriptors
137   // along the way.  Returns the repeat count that appeared
138   // before the descriptor (defaulting to 1) and leaves offset_
139   // pointing to the data edit.
140   int CueUpNextDataEdit(Context &, bool stop = false);
141 
Capitalize(CharType ch)142   static constexpr CharType Capitalize(CharType ch) {
143     return ch >= 'a' && ch <= 'z' ? ch + 'A' - 'a' : ch;
144   }
145 
146   // Data members are arranged and typed so as to reduce size.
147   // This structure may be allocated in stack space loaned by the
148   // user program for internal I/O.
149   const std::uint8_t maxHeight_{maxMaxHeight};
150   std::uint8_t height_{0};
151   const CharType *format_{nullptr};
152   int formatLength_{0};
153   int offset_{0}; // next item is at format_[offset_]
154 
155   // must be last, may be incomplete
156   Iteration stack_[maxMaxHeight];
157 };
158 } // namespace Fortran::runtime::io
159 #endif // FORTRAN_RUNTIME_FORMAT_H_
160