1 //===- CodeExpander.cpp - Expand variables in a string --------------------===//
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
7 //===----------------------------------------------------------------------===//
9 /// \file Expand the variables in a string.
11 //===----------------------------------------------------------------------===//
13 #include "CodeExpander.h"
14 #include "CodeExpansions.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include "llvm/TableGen/Error.h"
20 void CodeExpander::emit(raw_ostream
&OS
) const {
21 StringRef Current
= Code
;
23 while (!Current
.empty()) {
24 size_t Pos
= Current
.find_first_of("$\n\\");
25 if (Pos
== StringRef::npos
) {
31 OS
<< Current
.substr(0, Pos
);
32 Current
= Current
.substr(Pos
);
34 if (Current
.startswith("\n")) {
36 Current
= Current
.drop_front(1);
40 if (Current
.startswith("\\$") || Current
.startswith("\\\\")) {
42 Current
= Current
.drop_front(2);
46 if (Current
.startswith("\\")) {
47 Current
= Current
.drop_front(1);
51 if (Current
.startswith("${")) {
52 StringRef StartVar
= Current
;
53 Current
= Current
.drop_front(2);
55 std::tie(Var
, Current
) = Current
.split("}");
57 // Warn if we split because no terminator was found.
58 StringRef EndVar
= StartVar
.drop_front(2 /* ${ */ + Var
.size());
60 PrintWarning(Loc
, "Unterminated expansion '${" + Var
+ "'");
61 PrintNote("Code: [{" + Code
+ "}]");
64 auto ValueI
= Expansions
.find(Var
);
65 if (ValueI
== Expansions
.end()) {
67 "Attempt to expand an undeclared variable '" + Var
+ "'");
68 PrintNote("Code: [{" + Code
+ "}]");
71 OS
<< "/*$" << Var
<< "{*/";
72 OS
<< Expansions
.lookup(Var
);
78 PrintWarning(Loc
, "Assuming missing escape character: \\$");
79 PrintNote("Code: [{" + Code
+ "}]");
81 Current
= Current
.drop_front(1);