1 //===--- FrontendActions.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 "flang/Frontend/FrontendActions.h" 10 #include "flang/Frontend/CompilerInstance.h" 11 #include "flang/Parser/parsing.h" 12 #include "flang/Parser/provenance.h" 13 #include "flang/Parser/source.h" 14 15 using namespace Fortran::frontend; 16 17 void InputOutputTestAction::ExecuteAction() { 18 19 // Get the name of the file from FrontendInputFile current. 20 std::string path{GetCurrentFileOrBufferName()}; 21 std::string buf; 22 llvm::raw_string_ostream error_stream{buf}; 23 bool binaryMode = true; 24 25 // Set/store input file info into CompilerInstance. 26 CompilerInstance &ci = instance(); 27 Fortran::parser::AllSources &allSources{ci.allSources()}; 28 const Fortran::parser::SourceFile *sf; 29 sf = allSources.Open(path, error_stream); 30 llvm::ArrayRef<char> fileContent = sf->content(); 31 32 // Output file descriptor to receive the content of input file. 33 std::unique_ptr<llvm::raw_ostream> os; 34 35 // Do not write on the output file if using outputStream_. 36 if (ci.IsOutputStreamNull()) { 37 os = ci.CreateDefaultOutputFile( 38 binaryMode, GetCurrentFileOrBufferName(), "txt"); 39 if (!os) 40 return; 41 (*os) << fileContent.data(); 42 } else { 43 ci.WriteOutputStream(fileContent.data()); 44 } 45 } 46 47 void PrintPreprocessedAction::ExecuteAction() { 48 std::string buf; 49 llvm::raw_string_ostream outForPP{buf}; 50 51 // Run the preprocessor 52 CompilerInstance &ci = this->instance(); 53 ci.parsing().DumpCookedChars(outForPP); 54 55 // If a pre-defined output stream exists, dump the preprocessed content there 56 if (!ci.IsOutputStreamNull()) { 57 // Send the output to the pre-defined output buffer. 58 ci.WriteOutputStream(outForPP.str()); 59 return; 60 } 61 62 // Create a file and save the preprocessed output there 63 if (auto os{ci.CreateDefaultOutputFile( 64 /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName())}) { 65 (*os) << outForPP.str(); 66 } else { 67 llvm::errs() << "Unable to create the output file\n"; 68 return; 69 } 70 } 71