1 //===-- Implementation of IncludeFileCommand ------------------------------===// 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 "IncludeFileCommand.h" 10 11 #include "llvm/Support/MemoryBuffer.h" 12 #include "llvm/Support/SourceMgr.h" 13 14 #include <cstdlib> 15 16 namespace llvm_libc { 17 18 const char IncludeFileCommand::Name[] = "include_file"; 19 20 void IncludeFileCommand::run(llvm::raw_ostream &OS, const ArgVector &Args, 21 llvm::StringRef StdHeader, 22 llvm::RecordKeeper &Records, 23 const Command::ErrorReporter &Reporter) const { 24 if (Args.size() != 1) { 25 Reporter.printFatalError( 26 "%%include_file command takes exactly 1 argument."); 27 } 28 29 llvm::StringRef IncludeFile = Args[0]; 30 auto Buffer = llvm::MemoryBuffer::getFileAsStream(IncludeFile); 31 if (!Buffer) 32 Reporter.printFatalError(llvm::StringRef("Unable to open ") + IncludeFile); 33 34 llvm::StringRef Content = Buffer.get()->getBuffer(); 35 36 // If the included file has %%begin() command listed, then we want to write 37 // only the content after the begin command. 38 // TODO: The way the content is split below does not allow space within the 39 // the parentheses and, before and after the command. This probably is too 40 // strict and should be relaxed. 41 auto P = Content.split("\n%%begin()\n"); 42 if (P.second.empty()) { 43 // There was no %%begin in the content. 44 OS << P.first; 45 } else { 46 OS << P.second; 47 } 48 } 49 50 } // namespace llvm_libc 51