xref: /llvm-project/llvm/lib/Support/FormatVariadic.cpp (revision 7275de7fb2f087871611d037d1b529b226dd0521)
1 //===- FormatVariadic.cpp - Format string parsing and analysis ----*-C++-*-===//
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 #include "llvm/Support/FormatVariadic.h"
9 #include <cassert>
10 
11 using namespace llvm;
12 
13 static Optional<AlignStyle> translateLocChar(char C) {
14   switch (C) {
15   case '-':
16     return AlignStyle::Left;
17   case '=':
18     return AlignStyle::Center;
19   case '+':
20     return AlignStyle::Right;
21   }
22   return None;
23 }
24 
25 bool formatv_object_base::consumeFieldLayout(StringRef &Spec, AlignStyle &Where,
26                                              size_t &Align, char &Pad) {
27   Where = AlignStyle::Right;
28   Align = 0;
29   Pad = ' ';
30   if (Spec.empty())
31     return true;
32 
33   if (Spec.size() > 1) {
34     // A maximum of 2 characters at the beginning can be used for something
35     // other
36     // than the width.
37     // If Spec[1] is a loc char, then Spec[0] is a pad char and Spec[2:...]
38     // contains the width.
39     // Otherwise, if Spec[0] is a loc char, then Spec[1:...] contains the width.
40     // Otherwise, Spec[0:...] contains the width.
41     if (auto Loc = translateLocChar(Spec[1])) {
42       Pad = Spec[0];
43       Where = *Loc;
44       Spec = Spec.drop_front(2);
45     } else if (auto Loc = translateLocChar(Spec[0])) {
46       Where = *Loc;
47       Spec = Spec.drop_front(1);
48     }
49   }
50 
51   bool Failed = Spec.consumeInteger(0, Align);
52   return !Failed;
53 }
54 
55 Optional<ReplacementItem>
56 formatv_object_base::parseReplacementItem(StringRef Spec) {
57   StringRef RepString = Spec.trim("{}");
58 
59   // If the replacement sequence does not start with a non-negative integer,
60   // this is an error.
61   char Pad = ' ';
62   std::size_t Align = 0;
63   AlignStyle Where = AlignStyle::Right;
64   StringRef Options;
65   size_t Index = 0;
66   RepString = RepString.trim();
67   if (RepString.consumeInteger(0, Index)) {
68     assert(false && "Invalid replacement sequence index!");
69     return ReplacementItem{};
70   }
71   RepString = RepString.trim();
72   if (!RepString.empty() && RepString.front() == ',') {
73     RepString = RepString.drop_front();
74     if (!consumeFieldLayout(RepString, Where, Align, Pad))
75       assert(false && "Invalid replacement field layout specification!");
76   }
77   RepString = RepString.trim();
78   if (!RepString.empty() && RepString.front() == ':') {
79     Options = RepString.drop_front().trim();
80     RepString = StringRef();
81   }
82   RepString = RepString.trim();
83   if (!RepString.empty()) {
84     assert(false && "Unexpected characters found in replacement string!");
85   }
86 
87   return ReplacementItem{Spec, Index, Align, Where, Pad, Options};
88 }
89 
90 std::pair<ReplacementItem, StringRef>
91 formatv_object_base::splitLiteralAndReplacement(StringRef Fmt) {
92   while (!Fmt.empty()) {
93     // Everything up until the first brace is a literal.
94     if (Fmt.front() != '{') {
95       std::size_t BO = Fmt.find_first_of('{');
96       return std::make_pair(ReplacementItem{Fmt.substr(0, BO)}, Fmt.substr(BO));
97     }
98 
99     StringRef Braces = Fmt.take_while([](char C) { return C == '{'; });
100     // If there is more than one brace, then some of them are escaped.  Treat
101     // these as replacements.
102     if (Braces.size() > 1) {
103       size_t NumEscapedBraces = Braces.size() / 2;
104       StringRef Middle = Fmt.take_front(NumEscapedBraces);
105       StringRef Right = Fmt.drop_front(NumEscapedBraces * 2);
106       return std::make_pair(ReplacementItem{Middle}, Right);
107     }
108     // An unterminated open brace is undefined.  We treat the rest of the string
109     // as a literal replacement, but we assert to indicate that this is
110     // undefined and that we consider it an error.
111     std::size_t BC = Fmt.find_first_of('}');
112     if (BC == StringRef::npos) {
113       assert(
114           false &&
115           "Unterminated brace sequence.  Escape with {{ for a literal brace.");
116       return std::make_pair(ReplacementItem{Fmt}, StringRef());
117     }
118 
119     // Even if there is a closing brace, if there is another open brace before
120     // this closing brace, treat this portion as literal, and try again with the
121     // next one.
122     std::size_t BO2 = Fmt.find_first_of('{', 1);
123     if (BO2 < BC)
124       return std::make_pair(ReplacementItem{Fmt.substr(0, BO2)},
125                             Fmt.substr(BO2));
126 
127     StringRef Spec = Fmt.slice(1, BC);
128     StringRef Right = Fmt.substr(BC + 1);
129 
130     auto RI = parseReplacementItem(Spec);
131     if (RI.hasValue())
132       return std::make_pair(*RI, Right);
133 
134     // If there was an error parsing the replacement item, treat it as an
135     // invalid replacement spec, and just continue.
136     Fmt = Fmt.drop_front(BC + 1);
137   }
138   return std::make_pair(ReplacementItem{Fmt}, StringRef());
139 }
140 
141 SmallVector<ReplacementItem, 2>
142 formatv_object_base::parseFormatString(StringRef Fmt) {
143   SmallVector<ReplacementItem, 2> Replacements;
144   ReplacementItem I;
145   while (!Fmt.empty()) {
146     std::tie(I, Fmt) = splitLiteralAndReplacement(Fmt);
147     if (I.Type != ReplacementType::Empty)
148       Replacements.push_back(I);
149   }
150   return Replacements;
151 }
152 
153 void detail::format_adapter::anchor() { }
154