LCOV - code coverage report
Current view: top level - include/llvm/Support - FormatVariadic.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 436 500 87.2 %
Date: 2018-10-14 09:39:32 Functions: 240 600 40.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- FormatVariadic.h - Efficient type-safe string formatting --*- C++-*-===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the formatv() function which can be used with other LLVM
      11             : // subsystems to provide printf-like formatting, but with improved safety and
      12             : // flexibility.  The result of `formatv` is an object which can be streamed to
      13             : // a raw_ostream or converted to a std::string or llvm::SmallString.
      14             : //
      15             : //   // Convert to std::string.
      16             : //   std::string S = formatv("{0} {1}", 1234.412, "test").str();
      17             : //
      18             : //   // Convert to llvm::SmallString
      19             : //   SmallString<8> S = formatv("{0} {1}", 1234.412, "test").sstr<8>();
      20             : //
      21             : //   // Stream to an existing raw_ostream.
      22             : //   OS << formatv("{0} {1}", 1234.412, "test");
      23             : //
      24             : //===----------------------------------------------------------------------===//
      25             : 
      26             : #ifndef LLVM_SUPPORT_FORMATVARIADIC_H
      27             : #define LLVM_SUPPORT_FORMATVARIADIC_H
      28             : 
      29             : #include "llvm/ADT/Optional.h"
      30             : #include "llvm/ADT/STLExtras.h"
      31             : #include "llvm/ADT/SmallString.h"
      32             : #include "llvm/ADT/StringRef.h"
      33             : #include "llvm/Support/FormatCommon.h"
      34             : #include "llvm/Support/FormatProviders.h"
      35             : #include "llvm/Support/FormatVariadicDetails.h"
      36             : #include "llvm/Support/raw_ostream.h"
      37             : #include <cstddef>
      38             : #include <string>
      39             : #include <tuple>
      40             : #include <utility>
      41             : #include <vector>
      42             : 
      43             : namespace llvm {
      44             : 
      45             : enum class ReplacementType { Empty, Format, Literal };
      46             : 
      47             : struct ReplacementItem {
      48      175274 :   ReplacementItem() = default;
      49             :   explicit ReplacementItem(StringRef Literal)
      50             :       : Type(ReplacementType::Literal), Spec(Literal) {}
      51             :   ReplacementItem(StringRef Spec, size_t Index, size_t Align, AlignStyle Where,
      52             :                   char Pad, StringRef Options)
      53             :       : Type(ReplacementType::Format), Spec(Spec), Index(Index), Align(Align),
      54             :         Where(Where), Pad(Pad), Options(Options) {}
      55             : 
      56             :   ReplacementType Type = ReplacementType::Empty;
      57             :   StringRef Spec;
      58             :   size_t Index = 0;
      59             :   size_t Align = 0;
      60             :   AlignStyle Where = AlignStyle::Right;
      61             :   char Pad;
      62             :   StringRef Options;
      63             : };
      64             : 
      65             : class formatv_object_base {
      66             : protected:
      67             :   // The parameters are stored in a std::tuple, which does not provide runtime
      68             :   // indexing capabilities.  In order to enable runtime indexing, we use this
      69             :   // structure to put the parameters into a std::vector.  Since the parameters
      70             :   // are not all the same type, we use some type-erasure by wrapping the
      71             :   // parameters in a template class that derives from a non-template superclass.
      72             :   // Essentially, we are converting a std::tuple<Derived<Ts...>> to a
      73             :   // std::vector<Base*>.
      74             :   struct create_adapters {
      75             :     template <typename... Ts>
      76           0 :     std::vector<detail::format_adapter *> operator()(Ts &... Items) {
      77       87176 :       return std::vector<detail::format_adapter *>{&Items...};
      78             :     }
      79           0 :   };
      80           0 : 
      81             :   StringRef Fmt;
      82           0 :   std::vector<detail::format_adapter *> Adapters;
      83           0 :   std::vector<ReplacementItem> Replacements;
      84             : 
      85           0 :   static bool consumeFieldLayout(StringRef &Spec, AlignStyle &Where,
      86           0 :                                  size_t &Align, char &Pad);
      87             : 
      88           0 :   static std::pair<ReplacementItem, StringRef>
      89           0 :   splitLiteralAndReplacement(StringRef Fmt);
      90             : 
      91           0 : public:
      92        5647 :   formatv_object_base(StringRef Fmt, std::size_t ParamCount)
      93       11294 :       : Fmt(Fmt), Replacements(parseFormatString(Fmt)) {
      94        5647 :     Adapters.reserve(ParamCount);
      95        5647 :   }
      96             : 
      97           0 :   formatv_object_base(formatv_object_base const &rhs) = delete;
      98        8523 : 
      99       17046 :   formatv_object_base(formatv_object_base &&rhs)
     100        8523 :       : Fmt(std::move(rhs.Fmt)),
     101       61557 :         Adapters(), // Adapters are initialized by formatv_object
     102      106068 :         Replacements(std::move(rhs.Replacements)) {
     103       53034 :     Adapters.reserve(rhs.Adapters.size());
     104       54855 :   };
     105        3642 : 
     106       88730 :   void format(raw_ostream &S) const {
     107      297972 :     for (auto &R : Replacements) {
     108      209846 :       if (R.Type == ReplacementType::Empty)
     109       94332 :         continue;
     110      209611 :       if (R.Type == ReplacementType::Literal) {
     111       94461 :         S << R.Spec;
     112       94092 :         continue;
     113         682 :       }
     114      230456 :       if (R.Index >= Adapters.size()) {
     115         318 :         S << R.Spec;
     116         318 :         continue;
     117             :       }
     118           0 : 
     119      114936 :       auto W = Adapters[R.Index];
     120          52 : 
     121      114936 :       FmtAlign Align(*W, R.Where, R.Align, R.Pad);
     122      114936 :       Align.format(S, R.Options);
     123           0 :     }
     124       86909 :   }
     125        5318 :   static std::vector<ReplacementItem> parseFormatString(StringRef Fmt);
     126       10636 : 
     127        5318 :   static Optional<ReplacementItem> parseReplacementItem(StringRef Spec);
     128        5318 : 
     129        5357 :   std::string str() const {
     130           0 :     std::string Result;
     131        5357 :     raw_string_ostream Stream(Result);
     132        5357 :     Stream << *this;
     133           0 :     Stream.flush();
     134        5737 :     return Result;
     135         829 :   }
     136         380 : 
     137         540 :   template <unsigned N> SmallString<N> sstr() const {
     138          76 :     SmallString<N> Result;
     139          91 :     raw_svector_ostream Stream(Result);
     140        1385 :     Stream << *this;
     141        2545 :     return Result;
     142        1218 :   }
     143        1236 : 
     144          15 :   template <unsigned N> operator SmallString<N>() const { return sstr<N>(); }
     145           0 : 
     146        4300 :   operator std::string() const { return str(); }
     147         119 : };
     148         715 : 
     149        6481 : template <typename Tuple> class formatv_object : public formatv_object_base {
     150        1103 :   // Storage for the parameter adapters.  Since the base class erases the type
     151           0 :   // of the parameters, we have to own the storage for the parameters here, and
     152         430 :   // have the base class store type-erased pointers into this tuple.
     153         288 :   Tuple Parameters;
     154          42 : 
     155        8838 : public:
     156        5860 :   formatv_object(StringRef Fmt, Tuple &&Params)
     157           0 :       : formatv_object_base(Fmt, std::tuple_size<Tuple>::value),
     158       58777 :         Parameters(std::move(Params)) {
     159        5818 :     Adapters = apply_tuple(create_adapters(), Parameters);
     160        5654 :   }
     161        1859 : 
     162        8537 :   formatv_object(formatv_object const &rhs) = delete;
     163           0 : 
     164        9263 :   formatv_object(formatv_object &&rhs)
     165       61619 :       : formatv_object_base(std::move(rhs)),
     166        8572 :         Parameters(std::move(rhs.Parameters)) {
     167       60633 :     Adapters = apply_tuple(create_adapters(), Parameters);
     168       54806 :   }
     169       60023 : };
     170       15348 : 
     171        9463 : // Format text given a format string and replacement parameters.
     172        9466 : //
     173        7466 : // ===General Description===
     174        8618 : //
     175       21493 : // Formats textual output.  `Fmt` is a string consisting of one or more
     176        2738 : // replacement sequences with the following grammar:
     177       20135 : //
     178       19375 : // rep_field ::= "{" [index] ["," layout] [":" format] "}"
     179       19344 : // index     ::= <non-negative integer>
     180       28789 : // layout    ::= [[[char]loc]width]
     181         759 : // format    ::= <any string not containing "{" or "}">
     182       33755 : // char      ::= <any character except "{" or "}">
     183       28923 : // loc       ::= "-" | "=" | "+"
     184       28309 : // width     ::= <positive integer>
     185         718 : //
     186         929 : // index   - A non-negative integer specifying the index of the item in the
     187         604 : //           parameter pack to print.  Any other value is invalid.
     188         784 : // layout  - A string controlling how the field is laid out within the available
     189        5758 : //           space.
     190         799 : // format  - A type-dependent string used to provide additional options to
     191        5909 : //           the formatting operation.  Refer to the documentation of the
     192        6038 : //           various individual format providers for per-type options.
     193        5416 : // char    - The padding character.  Defaults to ' ' (space).  Only valid if
     194         446 : //           `loc` is also specified.
     195         192 : // loc     - Where to print the formatted text within the field.  Only valid if
     196         443 : //           `width` is also specified.
     197        1811 : //           '-' : The field is left aligned within the available space.
     198         303 : //           '=' : The field is centered within the available space.
     199          74 : //           '+' : The field is right aligned within the available space (this
     200          53 : //                 is the default).
     201         120 : // width   - The width of the field within which to print the formatted text.
     202         209 : //           If this is less than the required length then the `char` and `loc`
     203          70 : //           fields are ignored, and the field is printed with no leading or
     204        1698 : //           trailing padding.  If this is greater than the required length,
     205          99 : //           then the text is output according to the value of `loc`, and padded
     206        1860 : //           as appropriate on the left and/or right by `char`.
     207        1923 : //
     208        1779 : // ===Special Characters===
     209         351 : //
     210          18 : // The characters '{' and '}' are reserved and cannot appear anywhere within a
     211         210 : // replacement sequence.  Outside of a replacement sequence, in order to print
     212        1808 : // a literal '{' or '}' it must be doubled -- "{{" to print a literal '{' and
     213        3416 : // "}}" to print a literal '}'.
     214        1605 : //
     215        3111 : // ===Parameter Indexing===
     216        3012 : // `index` specifies the index of the parameter in the parameter pack to format
     217        1527 : // into the output.  Note that it is possible to refer to the same parameter
     218        1500 : // index multiple times in a given format string.  This makes it possible to
     219          32 : // output the same value multiple times without passing it multiple times to the
     220           1 : // function. For example:
     221          80 : //
     222          33 : //   formatv("{0} {1} {0}", "a", "bb")
     223          33 : //
     224          33 : // would yield the string "abba".  This can be convenient when it is expensive
     225           1 : // to compute the value of the parameter, and you would otherwise have had to
     226          34 : // save it to a temporary.
     227          34 : //
     228         100 : // ===Formatter Search===
     229           0 : //
     230          67 : // For a given parameter of type T, the following steps are executed in order
     231          67 : // until a match is found:
     232          67 : //
     233           1 : //   1. If the parameter is of class type, and inherits from format_adapter,
     234           4 : //      Then format() is invoked on it to produce the formatted output.  The
     235           1 : //      implementation should write the formatted text into `Stream`.
     236           5 : //   2. If there is a suitable template specialization of format_provider<>
     237           5 : //      for type T containing a method whose signature is:
     238           7 : //      void format(const T &Obj, raw_ostream &Stream, StringRef Options)
     239         136 : //      Then this method is invoked as described in Step 1.
     240           3 : //   3. If an appropriate operator<< for raw_ostream exists, it will be used.
     241         139 : //      For this to work, (raw_ostream& << const T&) must return raw_ostream&.
     242         139 : //
     243         154 : // If a match cannot be found through either of the above methods, a compiler
     244        5015 : // error is generated.
     245          18 : //
     246        5033 : // ===Invalid Format String Handling===
     247        5026 : //
     248        5023 : // In the case of a format string which does not match the grammar described
     249           9 : // above, the output is undefined.  With asserts enabled, LLVM will trigger an
     250           1 : // assertion.  Otherwise, it will try to do something reasonable, but in general
     251          11 : // the details of what that is are undefined.
     252         390 : //
     253          12 : template <typename... Ts>
     254        2425 : inline auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object<decltype(
     255         383 :     std::make_tuple(detail::build_format_adapter(std::forward<Ts>(Vals))...))> {
     256          11 :   using ParamTuple = decltype(
     257        7455 :       std::make_tuple(detail::build_format_adapter(std::forward<Ts>(Vals))...));
     258       14139 :   return formatv_object<ParamTuple>(
     259        7064 :       Fmt,
     260       12706 :       std::make_tuple(detail::build_format_adapter(std::forward<Ts>(Vals))...));
     261           1 : }
     262           1 : 
     263         159 : } // end namespace llvm
     264         159 : 
     265           1 : #endif // LLVM_SUPPORT_FORMATVARIADIC_H

Generated by: LCOV version 1.13