1 //===-- lib/Semantics/mod-file.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 "mod-file.h"
10 #include "resolve-names.h"
11 #include "flang/Common/restorer.h"
12 #include "flang/Evaluate/tools.h"
13 #include "flang/Parser/message.h"
14 #include "flang/Parser/parsing.h"
15 #include "flang/Parser/unparse.h"
16 #include "flang/Semantics/scope.h"
17 #include "flang/Semantics/semantics.h"
18 #include "flang/Semantics/symbol.h"
19 #include "flang/Semantics/tools.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <algorithm>
24 #include <fstream>
25 #include <set>
26 #include <string_view>
27 #include <vector>
28 
29 namespace Fortran::semantics {
30 
31 using namespace parser::literals;
32 
33 // The first line of a file that identifies it as a .mod file.
34 // The first three bytes are a Unicode byte order mark that ensures
35 // that the module file is decoded as UTF-8 even if source files
36 // are using another encoding.
37 struct ModHeader {
38   static constexpr const char bom[3 + 1]{"\xef\xbb\xbf"};
39   static constexpr int magicLen{13};
40   static constexpr int sumLen{16};
41   static constexpr const char magic[magicLen + 1]{"!mod$ v1 sum:"};
42   static constexpr char terminator{'\n'};
43   static constexpr int len{magicLen + 1 + sumLen};
44 };
45 
46 static std::optional<SourceName> GetSubmoduleParent(const parser::Program &);
47 static void CollectSymbols(const Scope &, SymbolVector &, SymbolVector &);
48 static void PutPassName(llvm::raw_ostream &, const std::optional<SourceName> &);
49 static void PutInit(llvm::raw_ostream &, const Symbol &, const MaybeExpr &,
50     const parser::Expr *);
51 static void PutInit(llvm::raw_ostream &, const MaybeIntExpr &);
52 static void PutBound(llvm::raw_ostream &, const Bound &);
53 static void PutShapeSpec(llvm::raw_ostream &, const ShapeSpec &);
54 static void PutShape(
55     llvm::raw_ostream &, const ArraySpec &, char open, char close);
56 llvm::raw_ostream &PutAttrs(llvm::raw_ostream &, Attrs,
57     const std::string * = nullptr, std::string before = ","s,
58     std::string after = ""s);
59 
60 static llvm::raw_ostream &PutAttr(llvm::raw_ostream &, Attr);
61 static llvm::raw_ostream &PutType(llvm::raw_ostream &, const DeclTypeSpec &);
62 static llvm::raw_ostream &PutLower(llvm::raw_ostream &, const std::string &);
63 static std::error_code WriteFile(
64     const std::string &, const std::string &, bool = true);
65 static bool FileContentsMatch(
66     const std::string &, const std::string &, const std::string &);
67 static std::string CheckSum(const std::string_view &);
68 
69 // Collect symbols needed for a subprogram interface
70 class SubprogramSymbolCollector {
71 public:
72   SubprogramSymbolCollector(const Symbol &symbol, const Scope &scope)
73       : symbol_{symbol}, scope_{scope} {}
74   const SymbolVector &symbols() const { return need_; }
75   const std::set<SourceName> &imports() const { return imports_; }
76   void Collect();
77 
78 private:
79   const Symbol &symbol_;
80   const Scope &scope_;
81   bool isInterface_{false};
82   SymbolVector need_; // symbols that are needed
83   UnorderedSymbolSet needSet_; // symbols already in need_
84   UnorderedSymbolSet useSet_; // use-associations that might be needed
85   std::set<SourceName> imports_; // imports from host that are needed
86 
87   void DoSymbol(const Symbol &);
88   void DoSymbol(const SourceName &, const Symbol &);
89   void DoType(const DeclTypeSpec *);
90   void DoBound(const Bound &);
91   void DoParamValue(const ParamValue &);
92   bool NeedImport(const SourceName &, const Symbol &);
93 
94   template <typename T> void DoExpr(evaluate::Expr<T> expr) {
95     for (const Symbol &symbol : evaluate::CollectSymbols(expr)) {
96       DoSymbol(symbol);
97     }
98   }
99 };
100 
101 bool ModFileWriter::WriteAll() {
102   // this flag affects character literals: force it to be consistent
103   auto restorer{
104       common::ScopedSet(parser::useHexadecimalEscapeSequences, false)};
105   WriteAll(context_.globalScope());
106   return !context_.AnyFatalError();
107 }
108 
109 void ModFileWriter::WriteAll(const Scope &scope) {
110   for (const auto &child : scope.children()) {
111     WriteOne(child);
112   }
113 }
114 
115 void ModFileWriter::WriteOne(const Scope &scope) {
116   if (scope.kind() == Scope::Kind::Module) {
117     auto *symbol{scope.symbol()};
118     if (!symbol->test(Symbol::Flag::ModFile)) {
119       Write(*symbol);
120     }
121     WriteAll(scope); // write out submodules
122   }
123 }
124 
125 // Construct the name of a module file. Non-empty ancestorName means submodule.
126 static std::string ModFileName(const SourceName &name,
127     const std::string &ancestorName, const std::string &suffix) {
128   std::string result{name.ToString() + suffix};
129   return ancestorName.empty() ? result : ancestorName + '-' + result;
130 }
131 
132 // Write the module file for symbol, which must be a module or submodule.
133 void ModFileWriter::Write(const Symbol &symbol) {
134   auto *ancestor{symbol.get<ModuleDetails>().ancestor()};
135   auto ancestorName{ancestor ? ancestor->GetName().value().ToString() : ""s};
136   auto path{context_.moduleDirectory() + '/' +
137       ModFileName(symbol.name(), ancestorName, context_.moduleFileSuffix())};
138   PutSymbols(DEREF(symbol.scope()));
139   if (std::error_code error{
140           WriteFile(path, GetAsString(symbol), context_.debugModuleWriter())}) {
141     context_.Say(
142         symbol.name(), "Error writing %s: %s"_err_en_US, path, error.message());
143   }
144 }
145 
146 // Return the entire body of the module file
147 // and clear saved uses, decls, and contains.
148 std::string ModFileWriter::GetAsString(const Symbol &symbol) {
149   std::string buf;
150   llvm::raw_string_ostream all{buf};
151   auto &details{symbol.get<ModuleDetails>()};
152   if (!details.isSubmodule()) {
153     all << "module " << symbol.name();
154   } else {
155     auto *parent{details.parent()->symbol()};
156     auto *ancestor{details.ancestor()->symbol()};
157     all << "submodule(" << ancestor->name();
158     if (parent != ancestor) {
159       all << ':' << parent->name();
160     }
161     all << ") " << symbol.name();
162   }
163   all << '\n' << uses_.str();
164   uses_.str().clear();
165   all << useExtraAttrs_.str();
166   useExtraAttrs_.str().clear();
167   all << decls_.str();
168   decls_.str().clear();
169   auto str{contains_.str()};
170   contains_.str().clear();
171   if (!str.empty()) {
172     all << "contains\n" << str;
173   }
174   all << "end\n";
175   return all.str();
176 }
177 
178 // Put out the visible symbols from scope.
179 void ModFileWriter::PutSymbols(const Scope &scope) {
180   SymbolVector sorted;
181   SymbolVector uses;
182   CollectSymbols(scope, sorted, uses);
183   std::string buf; // stuff after CONTAINS in derived type
184   llvm::raw_string_ostream typeBindings{buf};
185   for (const Symbol &symbol : sorted) {
186     if (!symbol.test(Symbol::Flag::CompilerCreated)) {
187       PutSymbol(typeBindings, symbol);
188     }
189   }
190   for (const Symbol &symbol : uses) {
191     PutUse(symbol);
192   }
193   for (const auto &set : scope.equivalenceSets()) {
194     if (!set.empty() &&
195         !set.front().symbol.test(Symbol::Flag::CompilerCreated)) {
196       char punctuation{'('};
197       decls_ << "equivalence";
198       for (const auto &object : set) {
199         decls_ << punctuation << object.AsFortran();
200         punctuation = ',';
201       }
202       decls_ << ")\n";
203     }
204   }
205   CHECK(typeBindings.str().empty());
206 }
207 
208 // Emit components in order
209 bool ModFileWriter::PutComponents(const Symbol &typeSymbol) {
210   const auto &scope{DEREF(typeSymbol.scope())};
211   std::string buf; // stuff after CONTAINS in derived type
212   llvm::raw_string_ostream typeBindings{buf};
213   UnorderedSymbolSet emitted;
214   SymbolVector symbols{scope.GetSymbols()};
215   // Emit type parameters first
216   for (const Symbol &symbol : symbols) {
217     if (symbol.has<TypeParamDetails>()) {
218       PutSymbol(typeBindings, symbol);
219       emitted.emplace(symbol);
220     }
221   }
222   // Emit components in component order.
223   const auto &details{typeSymbol.get<DerivedTypeDetails>()};
224   for (SourceName name : details.componentNames()) {
225     auto iter{scope.find(name)};
226     if (iter != scope.end()) {
227       const Symbol &component{*iter->second};
228       if (!component.test(Symbol::Flag::ParentComp)) {
229         PutSymbol(typeBindings, component);
230       }
231       emitted.emplace(component);
232     }
233   }
234   // Emit remaining symbols from the type's scope
235   for (const Symbol &symbol : symbols) {
236     if (emitted.find(symbol) == emitted.end()) {
237       PutSymbol(typeBindings, symbol);
238     }
239   }
240   if (auto str{typeBindings.str()}; !str.empty()) {
241     CHECK(scope.IsDerivedType());
242     decls_ << "contains\n" << str;
243     return true;
244   } else {
245     return false;
246   }
247 }
248 
249 static llvm::raw_ostream &PutGenericName(
250     llvm::raw_ostream &os, const Symbol &symbol) {
251   if (IsGenericDefinedOp(symbol)) {
252     return os << "operator(" << symbol.name() << ')';
253   } else {
254     return os << symbol.name();
255   }
256 }
257 
258 // Emit a symbol to decls_, except for bindings in a derived type (type-bound
259 // procedures, type-bound generics, final procedures) which go to typeBindings.
260 void ModFileWriter::PutSymbol(
261     llvm::raw_ostream &typeBindings, const Symbol &symbol) {
262   common::visit(
263       common::visitors{
264           [&](const ModuleDetails &) { /* should be current module */ },
265           [&](const DerivedTypeDetails &) { PutDerivedType(symbol); },
266           [&](const SubprogramDetails &) { PutSubprogram(symbol); },
267           [&](const GenericDetails &x) {
268             if (symbol.owner().IsDerivedType()) {
269               // generic binding
270               for (const Symbol &proc : x.specificProcs()) {
271                 PutGenericName(typeBindings << "generic::", symbol)
272                     << "=>" << proc.name() << '\n';
273               }
274             } else {
275               PutGeneric(symbol);
276               if (x.specific()) {
277                 PutSymbol(typeBindings, *x.specific());
278               }
279               if (x.derivedType()) {
280                 PutSymbol(typeBindings, *x.derivedType());
281               }
282             }
283           },
284           [&](const UseDetails &) { PutUse(symbol); },
285           [](const UseErrorDetails &) {},
286           [&](const ProcBindingDetails &x) {
287             bool deferred{symbol.attrs().test(Attr::DEFERRED)};
288             typeBindings << "procedure";
289             if (deferred) {
290               typeBindings << '(' << x.symbol().name() << ')';
291             }
292             PutPassName(typeBindings, x.passName());
293             auto attrs{symbol.attrs()};
294             if (x.passName()) {
295               attrs.reset(Attr::PASS);
296             }
297             PutAttrs(typeBindings, attrs);
298             typeBindings << "::" << symbol.name();
299             if (!deferred && x.symbol().name() != symbol.name()) {
300               typeBindings << "=>" << x.symbol().name();
301             }
302             typeBindings << '\n';
303           },
304           [&](const NamelistDetails &x) {
305             decls_ << "namelist/" << symbol.name();
306             char sep{'/'};
307             for (const Symbol &object : x.objects()) {
308               decls_ << sep << object.name();
309               sep = ',';
310             }
311             decls_ << '\n';
312           },
313           [&](const CommonBlockDetails &x) {
314             decls_ << "common/" << symbol.name();
315             char sep = '/';
316             for (const auto &object : x.objects()) {
317               decls_ << sep << object->name();
318               sep = ',';
319             }
320             decls_ << '\n';
321             if (symbol.attrs().test(Attr::BIND_C)) {
322               PutAttrs(decls_, symbol.attrs(), x.bindName(), ""s);
323               decls_ << "::/" << symbol.name() << "/\n";
324             }
325           },
326           [](const HostAssocDetails &) {},
327           [](const MiscDetails &) {},
328           [&](const auto &) {
329             PutEntity(decls_, symbol);
330             if (symbol.test(Symbol::Flag::OmpThreadprivate)) {
331               decls_ << "!$omp threadprivate(" << symbol.name() << ")\n";
332             }
333           },
334       },
335       symbol.details());
336 }
337 
338 void ModFileWriter::PutDerivedType(
339     const Symbol &typeSymbol, const Scope *scope) {
340   auto &details{typeSymbol.get<DerivedTypeDetails>()};
341   if (details.isDECStructure()) {
342     PutDECStructure(typeSymbol, scope);
343     return;
344   }
345   PutAttrs(decls_ << "type", typeSymbol.attrs());
346   if (const DerivedTypeSpec * extends{typeSymbol.GetParentTypeSpec()}) {
347     decls_ << ",extends(" << extends->name() << ')';
348   }
349   decls_ << "::" << typeSymbol.name();
350   if (!details.paramNames().empty()) {
351     char sep{'('};
352     for (const auto &name : details.paramNames()) {
353       decls_ << sep << name;
354       sep = ',';
355     }
356     decls_ << ')';
357   }
358   decls_ << '\n';
359   if (details.sequence()) {
360     decls_ << "sequence\n";
361   }
362   bool contains{PutComponents(typeSymbol)};
363   if (!details.finals().empty()) {
364     const char *sep{contains ? "final::" : "contains\nfinal::"};
365     for (const auto &pair : details.finals()) {
366       decls_ << sep << pair.second->name();
367       sep = ",";
368     }
369     if (*sep == ',') {
370       decls_ << '\n';
371     }
372   }
373   decls_ << "end type\n";
374 }
375 
376 void ModFileWriter::PutDECStructure(
377     const Symbol &typeSymbol, const Scope *scope) {
378   if (emittedDECStructures_.find(typeSymbol) != emittedDECStructures_.end()) {
379     return;
380   }
381   if (!scope && context_.IsTempName(typeSymbol.name().ToString())) {
382     return; // defer until used
383   }
384   emittedDECStructures_.insert(typeSymbol);
385   decls_ << "structure ";
386   if (!context_.IsTempName(typeSymbol.name().ToString())) {
387     decls_ << typeSymbol.name();
388   }
389   if (scope && scope->kind() == Scope::Kind::DerivedType) {
390     // Nested STRUCTURE: emit entity declarations right now
391     // on the STRUCTURE statement.
392     bool any{false};
393     for (const auto &ref : scope->GetSymbols()) {
394       const auto *object{ref->detailsIf<ObjectEntityDetails>()};
395       if (object && object->type() &&
396           object->type()->category() == DeclTypeSpec::TypeDerived &&
397           &object->type()->derivedTypeSpec().typeSymbol() == &typeSymbol) {
398         if (any) {
399           decls_ << ',';
400         } else {
401           any = true;
402         }
403         decls_ << ref->name();
404         PutShape(decls_, object->shape(), '(', ')');
405         PutInit(decls_, *ref, object->init(), nullptr);
406         emittedDECFields_.insert(*ref);
407       } else if (any) {
408         break; // any later use of this structure will use RECORD/str/
409       }
410     }
411   }
412   decls_ << '\n';
413   PutComponents(typeSymbol);
414   decls_ << "end structure\n";
415 }
416 
417 // Attributes that may be in a subprogram prefix
418 static const Attrs subprogramPrefixAttrs{Attr::ELEMENTAL, Attr::IMPURE,
419     Attr::MODULE, Attr::NON_RECURSIVE, Attr::PURE, Attr::RECURSIVE};
420 
421 void ModFileWriter::PutSubprogram(const Symbol &symbol) {
422   auto attrs{symbol.attrs()};
423   auto &details{symbol.get<SubprogramDetails>()};
424   Attrs bindAttrs{};
425   if (attrs.test(Attr::BIND_C)) {
426     // bind(c) is a suffix, not prefix
427     bindAttrs.set(Attr::BIND_C, true);
428     attrs.set(Attr::BIND_C, false);
429   }
430   bool isAbstract{attrs.test(Attr::ABSTRACT)};
431   if (isAbstract) {
432     attrs.set(Attr::ABSTRACT, false);
433   }
434   Attrs prefixAttrs{subprogramPrefixAttrs & attrs};
435   // emit any non-prefix attributes in an attribute statement
436   attrs &= ~subprogramPrefixAttrs;
437   std::string ssBuf;
438   llvm::raw_string_ostream ss{ssBuf};
439   PutAttrs(ss, attrs);
440   if (!ss.str().empty()) {
441     decls_ << ss.str().substr(1) << "::" << symbol.name() << '\n';
442   }
443   bool isInterface{details.isInterface()};
444   llvm::raw_ostream &os{isInterface ? decls_ : contains_};
445   if (isInterface) {
446     os << (isAbstract ? "abstract " : "") << "interface\n";
447   }
448   PutAttrs(os, prefixAttrs, nullptr, ""s, " "s);
449   os << (details.isFunction() ? "function " : "subroutine ");
450   os << symbol.name() << '(';
451   int n = 0;
452   for (const auto &dummy : details.dummyArgs()) {
453     if (n++ > 0) {
454       os << ',';
455     }
456     if (dummy) {
457       os << dummy->name();
458     } else {
459       os << "*";
460     }
461   }
462   os << ')';
463   PutAttrs(os, bindAttrs, details.bindName(), " "s, ""s);
464   if (details.isFunction()) {
465     const Symbol &result{details.result()};
466     if (result.name() != symbol.name()) {
467       os << " result(" << result.name() << ')';
468     }
469   }
470   os << '\n';
471 
472   // walk symbols, collect ones needed for interface
473   const Scope &scope{
474       details.entryScope() ? *details.entryScope() : DEREF(symbol.scope())};
475   SubprogramSymbolCollector collector{symbol, scope};
476   collector.Collect();
477   std::string typeBindingsBuf;
478   llvm::raw_string_ostream typeBindings{typeBindingsBuf};
479   ModFileWriter writer{context_};
480   for (const Symbol &need : collector.symbols()) {
481     writer.PutSymbol(typeBindings, need);
482   }
483   CHECK(typeBindings.str().empty());
484   os << writer.uses_.str();
485   for (const SourceName &import : collector.imports()) {
486     decls_ << "import::" << import << "\n";
487   }
488   os << writer.decls_.str();
489   os << "end\n";
490   if (isInterface) {
491     os << "end interface\n";
492   }
493 }
494 
495 static bool IsIntrinsicOp(const Symbol &symbol) {
496   if (const auto *details{symbol.GetUltimate().detailsIf<GenericDetails>()}) {
497     return details->kind().IsIntrinsicOperator();
498   } else {
499     return false;
500   }
501 }
502 
503 void ModFileWriter::PutGeneric(const Symbol &symbol) {
504   const auto &genericOwner{symbol.owner()};
505   auto &details{symbol.get<GenericDetails>()};
506   PutGenericName(decls_ << "interface ", symbol) << '\n';
507   for (const Symbol &specific : details.specificProcs()) {
508     if (specific.owner() == genericOwner) {
509       decls_ << "procedure::" << specific.name() << '\n';
510     }
511   }
512   decls_ << "end interface\n";
513   if (symbol.attrs().test(Attr::PRIVATE)) {
514     PutGenericName(decls_ << "private::", symbol) << '\n';
515   }
516 }
517 
518 void ModFileWriter::PutUse(const Symbol &symbol) {
519   auto &details{symbol.get<UseDetails>()};
520   auto &use{details.symbol()};
521   uses_ << "use " << GetUsedModule(details).name();
522   PutGenericName(uses_ << ",only:", symbol);
523   // Can have intrinsic op with different local-name and use-name
524   // (e.g. `operator(<)` and `operator(.lt.)`) but rename is not allowed
525   if (!IsIntrinsicOp(symbol) && use.name() != symbol.name()) {
526     PutGenericName(uses_ << "=>", use);
527   }
528   uses_ << '\n';
529   PutUseExtraAttr(Attr::VOLATILE, symbol, use);
530   PutUseExtraAttr(Attr::ASYNCHRONOUS, symbol, use);
531   if (symbol.attrs().test(Attr::PRIVATE)) {
532     PutGenericName(useExtraAttrs_ << "private::", symbol) << '\n';
533   }
534 }
535 
536 // We have "USE local => use" in this module. If attr was added locally
537 // (i.e. on local but not on use), also write it out in the mod file.
538 void ModFileWriter::PutUseExtraAttr(
539     Attr attr, const Symbol &local, const Symbol &use) {
540   if (local.attrs().test(attr) && !use.attrs().test(attr)) {
541     PutAttr(useExtraAttrs_, attr) << "::";
542     useExtraAttrs_ << local.name() << '\n';
543   }
544 }
545 
546 // When a generic interface has the same name as a derived type
547 // in the same scope, the generic shadows the derived type.
548 // If the derived type were declared first, emit the generic
549 // interface at the position of derived type's declaration.
550 // (ReplaceName() is not used for this purpose because doing so
551 // would confusingly position error messages pertaining to the generic
552 // interface upon the derived type's declaration.)
553 static inline SourceName NameInModuleFile(const Symbol &symbol) {
554   if (const auto *generic{symbol.detailsIf<GenericDetails>()}) {
555     if (const auto *derivedTypeOverload{generic->derivedType()}) {
556       if (derivedTypeOverload->name().begin() < symbol.name().begin()) {
557         return derivedTypeOverload->name();
558       }
559     }
560   } else if (const auto *use{symbol.detailsIf<UseDetails>()}) {
561     if (use->symbol().attrs().test(Attr::PRIVATE)) {
562       // Avoid the use in sorting of names created to access private
563       // specific procedures as a result of generic resolution;
564       // they're not in the cooked source.
565       return use->symbol().name();
566     }
567   }
568   return symbol.name();
569 }
570 
571 // Collect the symbols of this scope sorted by their original order, not name.
572 // Namelists are an exception: they are sorted after other symbols.
573 void CollectSymbols(
574     const Scope &scope, SymbolVector &sorted, SymbolVector &uses) {
575   SymbolVector namelist;
576   std::size_t commonSize{scope.commonBlocks().size()};
577   auto symbols{scope.GetSymbols()};
578   sorted.reserve(symbols.size() + commonSize);
579   for (SymbolRef symbol : symbols) {
580     if (!symbol->test(Symbol::Flag::ParentComp)) {
581       if (symbol->has<NamelistDetails>()) {
582         namelist.push_back(symbol);
583       } else {
584         sorted.push_back(symbol);
585       }
586       if (const auto *details{symbol->detailsIf<GenericDetails>()}) {
587         uses.insert(uses.end(), details->uses().begin(), details->uses().end());
588       }
589     }
590   }
591   // Sort most symbols by name: use of Symbol::ReplaceName ensures the source
592   // location of a symbol's name is the first "real" use.
593   std::sort(sorted.begin(), sorted.end(), [](SymbolRef x, SymbolRef y) {
594     return NameInModuleFile(x).begin() < NameInModuleFile(y).begin();
595   });
596   sorted.insert(sorted.end(), namelist.begin(), namelist.end());
597   for (const auto &pair : scope.commonBlocks()) {
598     sorted.push_back(*pair.second);
599   }
600   std::sort(
601       sorted.end() - commonSize, sorted.end(), SymbolSourcePositionCompare{});
602 }
603 
604 void ModFileWriter::PutEntity(llvm::raw_ostream &os, const Symbol &symbol) {
605   common::visit(
606       common::visitors{
607           [&](const ObjectEntityDetails &) { PutObjectEntity(os, symbol); },
608           [&](const ProcEntityDetails &) { PutProcEntity(os, symbol); },
609           [&](const TypeParamDetails &) { PutTypeParam(os, symbol); },
610           [&](const auto &) {
611             common::die("PutEntity: unexpected details: %s",
612                 DetailsToString(symbol.details()).c_str());
613           },
614       },
615       symbol.details());
616 }
617 
618 void PutShapeSpec(llvm::raw_ostream &os, const ShapeSpec &x) {
619   if (x.lbound().isStar()) {
620     CHECK(x.ubound().isStar());
621     os << ".."; // assumed rank
622   } else {
623     if (!x.lbound().isColon()) {
624       PutBound(os, x.lbound());
625     }
626     os << ':';
627     if (!x.ubound().isColon()) {
628       PutBound(os, x.ubound());
629     }
630   }
631 }
632 void PutShape(
633     llvm::raw_ostream &os, const ArraySpec &shape, char open, char close) {
634   if (!shape.empty()) {
635     os << open;
636     bool first{true};
637     for (const auto &shapeSpec : shape) {
638       if (first) {
639         first = false;
640       } else {
641         os << ',';
642       }
643       PutShapeSpec(os, shapeSpec);
644     }
645     os << close;
646   }
647 }
648 
649 void ModFileWriter::PutObjectEntity(
650     llvm::raw_ostream &os, const Symbol &symbol) {
651   auto &details{symbol.get<ObjectEntityDetails>()};
652   if (details.type() &&
653       details.type()->category() == DeclTypeSpec::TypeDerived) {
654     const Symbol &typeSymbol{details.type()->derivedTypeSpec().typeSymbol()};
655     if (typeSymbol.get<DerivedTypeDetails>().isDECStructure()) {
656       PutDerivedType(typeSymbol, &symbol.owner());
657       if (emittedDECFields_.find(symbol) != emittedDECFields_.end()) {
658         return; // symbol was emitted on STRUCTURE statement
659       }
660     }
661   }
662   PutEntity(
663       os, symbol, [&]() { PutType(os, DEREF(symbol.GetType())); },
664       symbol.attrs());
665   PutShape(os, details.shape(), '(', ')');
666   PutShape(os, details.coshape(), '[', ']');
667   PutInit(os, symbol, details.init(), details.unanalyzedPDTComponentInit());
668   os << '\n';
669 }
670 
671 void ModFileWriter::PutProcEntity(llvm::raw_ostream &os, const Symbol &symbol) {
672   if (symbol.attrs().test(Attr::INTRINSIC)) {
673     os << "intrinsic::" << symbol.name() << '\n';
674     if (symbol.attrs().test(Attr::PRIVATE)) {
675       os << "private::" << symbol.name() << '\n';
676     }
677     return;
678   }
679   const auto &details{symbol.get<ProcEntityDetails>()};
680   const ProcInterface &interface{details.interface()};
681   Attrs attrs{symbol.attrs()};
682   if (details.passName()) {
683     attrs.reset(Attr::PASS);
684   }
685   PutEntity(
686       os, symbol,
687       [&]() {
688         os << "procedure(";
689         if (interface.symbol()) {
690           os << interface.symbol()->name();
691         } else if (interface.type()) {
692           PutType(os, *interface.type());
693         }
694         os << ')';
695         PutPassName(os, details.passName());
696       },
697       attrs);
698   os << '\n';
699 }
700 
701 void PutPassName(
702     llvm::raw_ostream &os, const std::optional<SourceName> &passName) {
703   if (passName) {
704     os << ",pass(" << *passName << ')';
705   }
706 }
707 
708 void ModFileWriter::PutTypeParam(llvm::raw_ostream &os, const Symbol &symbol) {
709   auto &details{symbol.get<TypeParamDetails>()};
710   PutEntity(
711       os, symbol,
712       [&]() {
713         PutType(os, DEREF(symbol.GetType()));
714         PutLower(os << ',', common::EnumToString(details.attr()));
715       },
716       symbol.attrs());
717   PutInit(os, details.init());
718   os << '\n';
719 }
720 
721 void PutInit(llvm::raw_ostream &os, const Symbol &symbol, const MaybeExpr &init,
722     const parser::Expr *unanalyzed) {
723   if (symbol.attrs().test(Attr::PARAMETER) || symbol.owner().IsDerivedType()) {
724     const char *assign{symbol.attrs().test(Attr::POINTER) ? "=>" : "="};
725     if (unanalyzed) {
726       parser::Unparse(os << assign, *unanalyzed);
727     } else if (init) {
728       init->AsFortran(os << assign);
729     }
730   }
731 }
732 
733 void PutInit(llvm::raw_ostream &os, const MaybeIntExpr &init) {
734   if (init) {
735     init->AsFortran(os << '=');
736   }
737 }
738 
739 void PutBound(llvm::raw_ostream &os, const Bound &x) {
740   if (x.isStar()) {
741     os << '*';
742   } else if (x.isColon()) {
743     os << ':';
744   } else {
745     x.GetExplicit()->AsFortran(os);
746   }
747 }
748 
749 // Write an entity (object or procedure) declaration.
750 // writeType is called to write out the type.
751 void ModFileWriter::PutEntity(llvm::raw_ostream &os, const Symbol &symbol,
752     std::function<void()> writeType, Attrs attrs) {
753   writeType();
754   PutAttrs(os, attrs, symbol.GetBindName());
755   if (symbol.owner().kind() == Scope::Kind::DerivedType &&
756       context_.IsTempName(symbol.name().ToString())) {
757     os << "::%FILL";
758   } else {
759     os << "::" << symbol.name();
760   }
761 }
762 
763 // Put out each attribute to os, surrounded by `before` and `after` and
764 // mapped to lower case.
765 llvm::raw_ostream &PutAttrs(llvm::raw_ostream &os, Attrs attrs,
766     const std::string *bindName, std::string before, std::string after) {
767   attrs.set(Attr::PUBLIC, false); // no need to write PUBLIC
768   attrs.set(Attr::EXTERNAL, false); // no need to write EXTERNAL
769   if (bindName) {
770     os << before << "bind(c, name=\"" << *bindName << "\")" << after;
771     attrs.set(Attr::BIND_C, false);
772   }
773   for (std::size_t i{0}; i < Attr_enumSize; ++i) {
774     Attr attr{static_cast<Attr>(i)};
775     if (attrs.test(attr)) {
776       PutAttr(os << before, attr) << after;
777     }
778   }
779   return os;
780 }
781 
782 llvm::raw_ostream &PutAttr(llvm::raw_ostream &os, Attr attr) {
783   return PutLower(os, AttrToString(attr));
784 }
785 
786 llvm::raw_ostream &PutType(llvm::raw_ostream &os, const DeclTypeSpec &type) {
787   return PutLower(os, type.AsFortran());
788 }
789 
790 llvm::raw_ostream &PutLower(llvm::raw_ostream &os, const std::string &str) {
791   for (char c : str) {
792     os << parser::ToLowerCaseLetter(c);
793   }
794   return os;
795 }
796 
797 struct Temp {
798   Temp(int fd, std::string path) : fd{fd}, path{path} {}
799   Temp(Temp &&t) : fd{std::exchange(t.fd, -1)}, path{std::move(t.path)} {}
800   ~Temp() {
801     if (fd >= 0) {
802       llvm::sys::fs::file_t native{llvm::sys::fs::convertFDToNativeFile(fd)};
803       llvm::sys::fs::closeFile(native);
804       llvm::sys::fs::remove(path.c_str());
805     }
806   }
807   int fd;
808   std::string path;
809 };
810 
811 // Create a temp file in the same directory and with the same suffix as path.
812 // Return an open file descriptor and its path.
813 static llvm::ErrorOr<Temp> MkTemp(const std::string &path) {
814   auto length{path.length()};
815   auto dot{path.find_last_of("./")};
816   std::string suffix{
817       dot < length && path[dot] == '.' ? path.substr(dot + 1) : ""};
818   CHECK(length > suffix.length() &&
819       path.substr(length - suffix.length()) == suffix);
820   auto prefix{path.substr(0, length - suffix.length())};
821   int fd;
822   llvm::SmallString<16> tempPath;
823   if (std::error_code err{llvm::sys::fs::createUniqueFile(
824           prefix + "%%%%%%" + suffix, fd, tempPath)}) {
825     return err;
826   }
827   return Temp{fd, tempPath.c_str()};
828 }
829 
830 // Write the module file at path, prepending header. If an error occurs,
831 // return errno, otherwise 0.
832 static std::error_code WriteFile(
833     const std::string &path, const std::string &contents, bool debug) {
834   auto header{std::string{ModHeader::bom} + ModHeader::magic +
835       CheckSum(contents) + ModHeader::terminator};
836   if (debug) {
837     llvm::dbgs() << "Processing module " << path << ": ";
838   }
839   if (FileContentsMatch(path, header, contents)) {
840     if (debug) {
841       llvm::dbgs() << "module unchanged, not writing\n";
842     }
843     return {};
844   }
845   llvm::ErrorOr<Temp> temp{MkTemp(path)};
846   if (!temp) {
847     return temp.getError();
848   }
849   llvm::raw_fd_ostream writer(temp->fd, /*shouldClose=*/false);
850   writer << header;
851   writer << contents;
852   writer.flush();
853   if (writer.has_error()) {
854     return writer.error();
855   }
856   if (debug) {
857     llvm::dbgs() << "module written\n";
858   }
859   return llvm::sys::fs::rename(temp->path, path);
860 }
861 
862 // Return true if the stream matches what we would write for the mod file.
863 static bool FileContentsMatch(const std::string &path,
864     const std::string &header, const std::string &contents) {
865   std::size_t hsize{header.size()};
866   std::size_t csize{contents.size()};
867   auto buf_or{llvm::MemoryBuffer::getFile(path)};
868   if (!buf_or) {
869     return false;
870   }
871   auto buf = std::move(buf_or.get());
872   if (buf->getBufferSize() != hsize + csize) {
873     return false;
874   }
875   if (!std::equal(header.begin(), header.end(), buf->getBufferStart(),
876           buf->getBufferStart() + hsize)) {
877     return false;
878   }
879 
880   return std::equal(contents.begin(), contents.end(),
881       buf->getBufferStart() + hsize, buf->getBufferEnd());
882 }
883 
884 // Compute a simple hash of the contents of a module file and
885 // return it as a string of hex digits.
886 // This uses the Fowler-Noll-Vo hash function.
887 static std::string CheckSum(const std::string_view &contents) {
888   std::uint64_t hash{0xcbf29ce484222325ull};
889   for (char c : contents) {
890     hash ^= c & 0xff;
891     hash *= 0x100000001b3;
892   }
893   static const char *digits = "0123456789abcdef";
894   std::string result(ModHeader::sumLen, '0');
895   for (size_t i{ModHeader::sumLen}; hash != 0; hash >>= 4) {
896     result[--i] = digits[hash & 0xf];
897   }
898   return result;
899 }
900 
901 static bool VerifyHeader(llvm::ArrayRef<char> content) {
902   std::string_view sv{content.data(), content.size()};
903   if (sv.substr(0, ModHeader::magicLen) != ModHeader::magic) {
904     return false;
905   }
906   std::string_view expectSum{sv.substr(ModHeader::magicLen, ModHeader::sumLen)};
907   std::string actualSum{CheckSum(sv.substr(ModHeader::len))};
908   return expectSum == actualSum;
909 }
910 
911 Scope *ModFileReader::Read(const SourceName &name,
912     std::optional<bool> isIntrinsic, Scope *ancestor, bool silent) {
913   std::string ancestorName; // empty for module
914   if (ancestor) {
915     if (auto *scope{ancestor->FindSubmodule(name)}) {
916       return scope;
917     }
918     ancestorName = ancestor->GetName().value().ToString();
919   } else {
920     if (!isIntrinsic.value_or(false)) {
921       auto it{context_.globalScope().find(name)};
922       if (it != context_.globalScope().end()) {
923         return it->second->scope();
924       }
925     }
926     if (isIntrinsic.value_or(true)) {
927       auto it{context_.intrinsicModulesScope().find(name)};
928       if (it != context_.intrinsicModulesScope().end()) {
929         return it->second->scope();
930       }
931     }
932   }
933   parser::Parsing parsing{context_.allCookedSources()};
934   parser::Options options;
935   options.isModuleFile = true;
936   options.features.Enable(common::LanguageFeature::BackslashEscapes);
937   options.features.Enable(common::LanguageFeature::OpenMP);
938   if (!isIntrinsic.value_or(false)) {
939     options.searchDirectories = context_.searchDirectories();
940     // If a directory is in both lists, the intrinsic module directory
941     // takes precedence.
942     for (const auto &dir : context_.intrinsicModuleDirectories()) {
943       std::remove(options.searchDirectories.begin(),
944           options.searchDirectories.end(), dir);
945     }
946   }
947   if (isIntrinsic.value_or(true)) {
948     for (const auto &dir : context_.intrinsicModuleDirectories()) {
949       options.searchDirectories.push_back(dir);
950     }
951   }
952   auto path{ModFileName(name, ancestorName, context_.moduleFileSuffix())};
953   const auto *sourceFile{parsing.Prescan(path, options)};
954   if (parsing.messages().AnyFatalError()) {
955     if (!silent) {
956       for (auto &msg : parsing.messages().messages()) {
957         std::string str{msg.ToString()};
958         Say(name, ancestorName,
959             parser::MessageFixedText{str.c_str(), str.size(), msg.severity()},
960             path);
961       }
962     }
963     return nullptr;
964   }
965   CHECK(sourceFile);
966   if (!VerifyHeader(sourceFile->content())) {
967     Say(name, ancestorName, "File has invalid checksum: %s"_warn_en_US,
968         sourceFile->path());
969     return nullptr;
970   }
971   llvm::raw_null_ostream NullStream;
972   parsing.Parse(NullStream);
973   auto &parseTree{parsing.parseTree()};
974   if (!parsing.messages().empty() || !parsing.consumedWholeFile() ||
975       !parseTree) {
976     Say(name, ancestorName, "Module file is corrupt: %s"_err_en_US,
977         sourceFile->path());
978     return nullptr;
979   }
980   Scope *parentScope; // the scope this module/submodule goes into
981   if (!isIntrinsic.has_value()) {
982     for (const auto &dir : context_.intrinsicModuleDirectories()) {
983       if (sourceFile->path().size() > dir.size() &&
984           sourceFile->path().find(dir) == 0) {
985         isIntrinsic = true;
986         break;
987       }
988     }
989   }
990   Scope &topScope{isIntrinsic.value_or(false) ? context_.intrinsicModulesScope()
991                                               : context_.globalScope()};
992   if (!ancestor) {
993     parentScope = &topScope;
994   } else if (std::optional<SourceName> parent{GetSubmoduleParent(*parseTree)}) {
995     parentScope = Read(*parent, false /*not intrinsic*/, ancestor, silent);
996   } else {
997     parentScope = ancestor;
998   }
999   auto pair{parentScope->try_emplace(name, UnknownDetails{})};
1000   if (!pair.second) {
1001     return nullptr;
1002   }
1003   Symbol &modSymbol{*pair.first->second};
1004   modSymbol.set(Symbol::Flag::ModFile);
1005   ResolveNames(context_, *parseTree, topScope);
1006   CHECK(modSymbol.has<ModuleDetails>());
1007   CHECK(modSymbol.test(Symbol::Flag::ModFile));
1008   if (isIntrinsic.value_or(false)) {
1009     modSymbol.attrs().set(Attr::INTRINSIC);
1010   }
1011   return modSymbol.scope();
1012 }
1013 
1014 parser::Message &ModFileReader::Say(const SourceName &name,
1015     const std::string &ancestor, parser::MessageFixedText &&msg,
1016     const std::string &arg) {
1017   return context_.Say(name, "Cannot read module file for %s: %s"_err_en_US,
1018       parser::MessageFormattedText{ancestor.empty()
1019               ? "module '%s'"_en_US
1020               : "submodule '%s' of module '%s'"_en_US,
1021           name, ancestor}
1022           .MoveString(),
1023       parser::MessageFormattedText{std::move(msg), arg}.MoveString());
1024 }
1025 
1026 // program was read from a .mod file for a submodule; return the name of the
1027 // submodule's parent submodule, nullptr if none.
1028 static std::optional<SourceName> GetSubmoduleParent(
1029     const parser::Program &program) {
1030   CHECK(program.v.size() == 1);
1031   auto &unit{program.v.front()};
1032   auto &submod{std::get<common::Indirection<parser::Submodule>>(unit.u)};
1033   auto &stmt{
1034       std::get<parser::Statement<parser::SubmoduleStmt>>(submod.value().t)};
1035   auto &parentId{std::get<parser::ParentIdentifier>(stmt.statement.t)};
1036   if (auto &parent{std::get<std::optional<parser::Name>>(parentId.t)}) {
1037     return parent->source;
1038   } else {
1039     return std::nullopt;
1040   }
1041 }
1042 
1043 void SubprogramSymbolCollector::Collect() {
1044   const auto &details{symbol_.get<SubprogramDetails>()};
1045   isInterface_ = details.isInterface();
1046   for (const Symbol *dummyArg : details.dummyArgs()) {
1047     if (dummyArg) {
1048       DoSymbol(*dummyArg);
1049     }
1050   }
1051   if (details.isFunction()) {
1052     DoSymbol(details.result());
1053   }
1054   for (const auto &pair : scope_) {
1055     const Symbol &symbol{*pair.second};
1056     if (const auto *useDetails{symbol.detailsIf<UseDetails>()}) {
1057       const Symbol &ultimate{useDetails->symbol().GetUltimate()};
1058       bool needed{useSet_.count(ultimate) > 0};
1059       if (const auto *generic{ultimate.detailsIf<GenericDetails>()}) {
1060         // The generic may not be needed itself, but the specific procedure
1061         // &/or derived type that it shadows may be needed.
1062         const Symbol *spec{generic->specific()};
1063         const Symbol *dt{generic->derivedType()};
1064         needed = needed || (spec && useSet_.count(*spec) > 0) ||
1065             (dt && useSet_.count(*dt) > 0);
1066       }
1067       if (needed) {
1068         need_.push_back(symbol);
1069       }
1070     } else if (symbol.has<SubprogramDetails>()) {
1071       // An internal subprogram is needed if it is used as interface
1072       // for a dummy or return value procedure.
1073       bool needed{false};
1074       const auto hasInterface{[&symbol](const Symbol *s) -> bool {
1075         // Is 's' a procedure with interface 'symbol'?
1076         if (s) {
1077           if (const auto *sDetails{s->detailsIf<ProcEntityDetails>()}) {
1078             const ProcInterface &sInterface{sDetails->interface()};
1079             if (sInterface.symbol() == &symbol) {
1080               return true;
1081             }
1082           }
1083         }
1084         return false;
1085       }};
1086       for (const Symbol *dummyArg : details.dummyArgs()) {
1087         needed = needed || hasInterface(dummyArg);
1088       }
1089       needed =
1090           needed || (details.isFunction() && hasInterface(&details.result()));
1091       if (needed && needSet_.insert(symbol).second) {
1092         need_.push_back(symbol);
1093       }
1094     }
1095   }
1096 }
1097 
1098 void SubprogramSymbolCollector::DoSymbol(const Symbol &symbol) {
1099   DoSymbol(symbol.name(), symbol);
1100 }
1101 
1102 // Do symbols this one depends on; then add to need_
1103 void SubprogramSymbolCollector::DoSymbol(
1104     const SourceName &name, const Symbol &symbol) {
1105   const auto &scope{symbol.owner()};
1106   if (scope != scope_ && !scope.IsDerivedType()) {
1107     if (scope != scope_.parent()) {
1108       useSet_.insert(symbol);
1109     }
1110     if (NeedImport(name, symbol)) {
1111       imports_.insert(name);
1112     }
1113     return;
1114   }
1115   if (!needSet_.insert(symbol).second) {
1116     return; // already done
1117   }
1118   common::visit(common::visitors{
1119                     [this](const ObjectEntityDetails &details) {
1120                       for (const ShapeSpec &spec : details.shape()) {
1121                         DoBound(spec.lbound());
1122                         DoBound(spec.ubound());
1123                       }
1124                       for (const ShapeSpec &spec : details.coshape()) {
1125                         DoBound(spec.lbound());
1126                         DoBound(spec.ubound());
1127                       }
1128                       if (const Symbol * commonBlock{details.commonBlock()}) {
1129                         DoSymbol(*commonBlock);
1130                       }
1131                     },
1132                     [this](const CommonBlockDetails &details) {
1133                       for (const auto &object : details.objects()) {
1134                         DoSymbol(*object);
1135                       }
1136                     },
1137                     [](const auto &) {},
1138                 },
1139       symbol.details());
1140   if (!symbol.has<UseDetails>()) {
1141     DoType(symbol.GetType());
1142   }
1143   if (!scope.IsDerivedType()) {
1144     need_.push_back(symbol);
1145   }
1146 }
1147 
1148 void SubprogramSymbolCollector::DoType(const DeclTypeSpec *type) {
1149   if (!type) {
1150     return;
1151   }
1152   switch (type->category()) {
1153   case DeclTypeSpec::Numeric:
1154   case DeclTypeSpec::Logical:
1155     break; // nothing to do
1156   case DeclTypeSpec::Character:
1157     DoParamValue(type->characterTypeSpec().length());
1158     break;
1159   default:
1160     if (const DerivedTypeSpec * derived{type->AsDerived()}) {
1161       const auto &typeSymbol{derived->typeSymbol()};
1162       if (const DerivedTypeSpec * extends{typeSymbol.GetParentTypeSpec()}) {
1163         DoSymbol(extends->name(), extends->typeSymbol());
1164       }
1165       for (const auto &pair : derived->parameters()) {
1166         DoParamValue(pair.second);
1167       }
1168       for (const auto &pair : *typeSymbol.scope()) {
1169         const Symbol &comp{*pair.second};
1170         DoSymbol(comp);
1171       }
1172       DoSymbol(derived->name(), derived->typeSymbol());
1173     }
1174   }
1175 }
1176 
1177 void SubprogramSymbolCollector::DoBound(const Bound &bound) {
1178   if (const MaybeSubscriptIntExpr & expr{bound.GetExplicit()}) {
1179     DoExpr(*expr);
1180   }
1181 }
1182 void SubprogramSymbolCollector::DoParamValue(const ParamValue &paramValue) {
1183   if (const auto &expr{paramValue.GetExplicit()}) {
1184     DoExpr(*expr);
1185   }
1186 }
1187 
1188 // Do we need a IMPORT of this symbol into an interface block?
1189 bool SubprogramSymbolCollector::NeedImport(
1190     const SourceName &name, const Symbol &symbol) {
1191   if (!isInterface_) {
1192     return false;
1193   } else if (symbol.owner().Contains(scope_)) {
1194     return true;
1195   } else if (const Symbol * found{scope_.FindSymbol(name)}) {
1196     // detect import from ancestor of use-associated symbol
1197     return found->has<UseDetails>() && found->owner() != scope_;
1198   } else {
1199     // "found" can be null in the case of a use-associated derived type's parent
1200     // type
1201     CHECK(symbol.has<DerivedTypeDetails>());
1202     return false;
1203   }
1204 }
1205 
1206 } // namespace Fortran::semantics
1207