CodeExpander.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //===- CodeExpander.cpp - Expand variables in a string --------------------===//
  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. /// \file Expand the variables in a string.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeExpander.h"
  13. #include "CodeExpansions.h"
  14. #include "llvm/Support/CommandLine.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include "llvm/TableGen/Error.h"
  17. using namespace llvm;
  18. void CodeExpander::emit(raw_ostream &OS) const {
  19. StringRef Current = Code;
  20. while (!Current.empty()) {
  21. size_t Pos = Current.find_first_of("$\n\\");
  22. if (Pos == StringRef::npos) {
  23. OS << Current;
  24. Current = "";
  25. continue;
  26. }
  27. OS << Current.substr(0, Pos);
  28. Current = Current.substr(Pos);
  29. if (Current.startswith("\n")) {
  30. OS << "\n" << Indent;
  31. Current = Current.drop_front(1);
  32. continue;
  33. }
  34. if (Current.startswith("\\$") || Current.startswith("\\\\")) {
  35. OS << Current[1];
  36. Current = Current.drop_front(2);
  37. continue;
  38. }
  39. if (Current.startswith("\\")) {
  40. Current = Current.drop_front(1);
  41. continue;
  42. }
  43. if (Current.startswith("${")) {
  44. StringRef StartVar = Current;
  45. Current = Current.drop_front(2);
  46. StringRef Var;
  47. std::tie(Var, Current) = Current.split("}");
  48. // Warn if we split because no terminator was found.
  49. StringRef EndVar = StartVar.drop_front(2 /* ${ */ + Var.size());
  50. if (EndVar.empty()) {
  51. PrintWarning(Loc, "Unterminated expansion '${" + Var + "'");
  52. PrintNote("Code: [{" + Code + "}]");
  53. }
  54. auto ValueI = Expansions.find(Var);
  55. if (ValueI == Expansions.end()) {
  56. PrintError(Loc,
  57. "Attempt to expand an undeclared variable '" + Var + "'");
  58. PrintNote("Code: [{" + Code + "}]");
  59. }
  60. if (ShowExpansions)
  61. OS << "/*$" << Var << "{*/";
  62. OS << Expansions.lookup(Var);
  63. if (ShowExpansions)
  64. OS << "/*}*/";
  65. continue;
  66. }
  67. PrintWarning(Loc, "Assuming missing escape character: \\$");
  68. PrintNote("Code: [{" + Code + "}]");
  69. OS << "$";
  70. Current = Current.drop_front(1);
  71. }
  72. }