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