mirror of
https://github.com/fmtlib/fmt.git
synced 2024-10-06 06:50:00 +00:00
Add support for multiple namespaces
This commit is contained in:
parent
a10e032148
commit
03d14c3beb
104
doc/api.md
104
doc/api.md
@ -1,6 +1,6 @@
|
||||
# API Reference
|
||||
|
||||
The {fmt} library API consists of the following parts:
|
||||
The {fmt} library API consists of the following components:
|
||||
|
||||
- [`fmt/base.h`](#base-api): the base API providing main formatting functions
|
||||
for `char`/UTF-8 with C++20 compile-time checks and minimal dependencies
|
||||
@ -112,32 +112,36 @@ The recommended way of defining a formatter is by reusing an existing
|
||||
one via inheritance or composition. This way you can support standard
|
||||
format specifiers without implementing them yourself. For example:
|
||||
|
||||
// color.h:
|
||||
#include <fmt/base.h>
|
||||
```c++
|
||||
// color.h:
|
||||
#include <fmt/base.h>
|
||||
|
||||
enum class color {red, green, blue};
|
||||
enum class color {red, green, blue};
|
||||
|
||||
template <> struct fmt::formatter<color>: formatter<string_view> {
|
||||
// parse is inherited from formatter<string_view>.
|
||||
template <> struct fmt::formatter<color>: formatter<string_view> {
|
||||
// parse is inherited from formatter<string_view>.
|
||||
|
||||
auto format(color c, format_context& ctx) const
|
||||
-> format_context::iterator;
|
||||
};
|
||||
auto format(color c, format_context& ctx) const
|
||||
-> format_context::iterator;
|
||||
};
|
||||
```
|
||||
|
||||
// color.cc:
|
||||
#include "color.h"
|
||||
#include <fmt/format.h>
|
||||
```c++
|
||||
// color.cc:
|
||||
#include "color.h"
|
||||
#include <fmt/format.h>
|
||||
|
||||
auto fmt::formatter<color>::format(color c, format_context& ctx) const
|
||||
-> format_context::iterator {
|
||||
string_view name = "unknown";
|
||||
switch (c) {
|
||||
case color::red: name = "red"; break;
|
||||
case color::green: name = "green"; break;
|
||||
case color::blue: name = "blue"; break;
|
||||
}
|
||||
return formatter<string_view>::format(name, ctx);
|
||||
}
|
||||
auto fmt::formatter<color>::format(color c, format_context& ctx) const
|
||||
-> format_context::iterator {
|
||||
string_view name = "unknown";
|
||||
switch (c) {
|
||||
case color::red: name = "red"; break;
|
||||
case color::green: name = "green"; break;
|
||||
case color::blue: name = "blue"; break;
|
||||
}
|
||||
return formatter<string_view>::format(name, ctx);
|
||||
}
|
||||
```
|
||||
|
||||
Note that `formatter<string_view>::format` is defined in `fmt/format.h`
|
||||
so it has to be included in the source file. Since `parse` is inherited
|
||||
@ -213,36 +217,40 @@ formatters.
|
||||
|
||||
You can also write a formatter for a hierarchy of classes:
|
||||
|
||||
// demo.h:
|
||||
#include <type_traits>
|
||||
#include <fmt/core.h>
|
||||
```c++
|
||||
// demo.h:
|
||||
#include <type_traits>
|
||||
#include <fmt/core.h>
|
||||
|
||||
struct A {
|
||||
virtual ~A() {}
|
||||
virtual std::string name() const { return "A"; }
|
||||
};
|
||||
struct A {
|
||||
virtual ~A() {}
|
||||
virtual std::string name() const { return "A"; }
|
||||
};
|
||||
|
||||
struct B : A {
|
||||
virtual std::string name() const { return "B"; }
|
||||
};
|
||||
struct B : A {
|
||||
virtual std::string name() const { return "B"; }
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
|
||||
fmt::formatter<std::string> {
|
||||
auto format(const A& a, format_context& ctx) const {
|
||||
return fmt::formatter<std::string>::format(a.name(), ctx);
|
||||
}
|
||||
};
|
||||
template <typename T>
|
||||
struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
|
||||
fmt::formatter<std::string> {
|
||||
auto format(const A& a, format_context& ctx) const {
|
||||
return fmt::formatter<std::string>::format(a.name(), ctx);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
// demo.cc:
|
||||
#include "demo.h"
|
||||
#include <fmt/format.h>
|
||||
```c++
|
||||
// demo.cc:
|
||||
#include "demo.h"
|
||||
#include <fmt/format.h>
|
||||
|
||||
int main() {
|
||||
B b;
|
||||
A& a = b;
|
||||
fmt::print("{}", a); // prints "B"
|
||||
}
|
||||
int main() {
|
||||
B b;
|
||||
A& a = b;
|
||||
fmt::print("{}", a); // prints "B"
|
||||
}
|
||||
```
|
||||
|
||||
Providing both a `formatter` specialization and a `format_as` overload
|
||||
is disallowed.
|
||||
@ -335,7 +343,7 @@ formatting functions and locale support.
|
||||
|
||||
::: group_digits(T)
|
||||
|
||||
<!-- TODO ::: detail::buffer -->
|
||||
::: detail::buffer
|
||||
|
||||
::: basic_memory_buffer
|
||||
|
||||
|
@ -149,7 +149,6 @@ import std;
|
||||
# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
|
||||
#endif
|
||||
|
||||
// Detect C++20 concepts
|
||||
#ifdef FMT_USE_CONCEPTS
|
||||
// Use the provided definition.
|
||||
#elif defined(__cpp_concepts)
|
||||
@ -834,7 +833,7 @@ class compile_parse_context : public basic_format_parse_context<Char> {
|
||||
};
|
||||
|
||||
/// A contiguous memory buffer with an optional growing ability. It is an
|
||||
// internal class and shouldn't be used directly, only via `memory_buffer`.
|
||||
/// internal class and shouldn't be used directly, only via `memory_buffer`.
|
||||
template <typename T> class buffer {
|
||||
private:
|
||||
T* ptr_;
|
||||
|
@ -3869,21 +3869,19 @@ FMT_API auto vsystem_error(int error_code, string_view format_str,
|
||||
format_args args) -> std::system_error;
|
||||
|
||||
/**
|
||||
\rst
|
||||
Constructs :class:`std::system_error` with a message formatted with
|
||||
``fmt::format(fmt, args...)``.
|
||||
*error_code* is a system error code as given by ``errno``.
|
||||
|
||||
**Example**::
|
||||
|
||||
// This throws std::system_error with the description
|
||||
// cannot open file 'madeup': No such file or directory
|
||||
// or similar (system message may vary).
|
||||
const char* filename = "madeup";
|
||||
std::FILE* file = std::fopen(filename, "r");
|
||||
if (!file)
|
||||
throw fmt::system_error(errno, "cannot open file '{}'", filename);
|
||||
\endrst
|
||||
* Constructs `std::system_error` with a message formatted with
|
||||
* `fmt::format(fmt, args...)`.
|
||||
* *error_code* is a system error code as given by `errno`.
|
||||
*
|
||||
* **Example**::
|
||||
*
|
||||
* // This throws std::system_error with the description
|
||||
* // cannot open file 'madeup': No such file or directory
|
||||
* // or similar (system message may vary).
|
||||
* const char* filename = "madeup";
|
||||
* std::FILE* file = std::fopen(filename, "r");
|
||||
* if (!file)
|
||||
* throw fmt::system_error(errno, "cannot open file '{}'", filename);
|
||||
*/
|
||||
template <typename... T>
|
||||
auto system_error(int error_code, format_string<T...> fmt, T&&... args)
|
||||
|
@ -68,7 +68,7 @@ def get_description(node: et.Element) -> list[et.Element]:
|
||||
return node.findall('briefdescription/para') + \
|
||||
node.findall('detaileddescription/para')
|
||||
|
||||
def clean_type(type: str) -> str:
|
||||
def normalize_type(type: str) -> str:
|
||||
type = type.replace('< ', '<').replace(' >', '>')
|
||||
return type.replace(' &', '&').replace(' *', '*')
|
||||
|
||||
@ -79,7 +79,7 @@ def convert_type(type: et.Element) -> str:
|
||||
if ref.tail:
|
||||
result += ref.tail
|
||||
result += type.tail.strip()
|
||||
return clean_type(result)
|
||||
return normalize_type(result)
|
||||
|
||||
def convert_params(func: et.Element) -> Definition:
|
||||
params = []
|
||||
@ -94,7 +94,7 @@ def convert_return_type(d: Definition, node: et.Element) -> None:
|
||||
if d.type == 'auto' or d.type == 'constexpr auto':
|
||||
parts = node.find('argsstring').text.split(' -> ')
|
||||
if len(parts) > 1:
|
||||
d.trailing_return_type = clean_type(parts[1])
|
||||
d.trailing_return_type = normalize_type(parts[1])
|
||||
|
||||
def render_decl(d: Definition) -> None:
|
||||
text = '<pre><code class="language-cpp">'
|
||||
@ -131,6 +131,7 @@ class CxxHandler(BaseHandler):
|
||||
cmd = ['doxygen', '-']
|
||||
doc_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
||||
include_dir = os.path.join(os.path.dirname(doc_dir), 'include', 'fmt')
|
||||
self._ns2doxyxml = {}
|
||||
self._doxyxml_dir = 'doxyxml'
|
||||
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
|
||||
out, _ = p.communicate(input=r'''
|
||||
@ -173,18 +174,26 @@ class CxxHandler(BaseHandler):
|
||||
if p.returncode != 0:
|
||||
raise CalledProcessError(p.returncode, cmd)
|
||||
|
||||
# Load XML.
|
||||
with open(os.path.join(self._doxyxml_dir, 'namespacefmt.xml')) as f:
|
||||
self._doxyxml = et.parse(f)
|
||||
|
||||
def collect(self, identifier: str, config: Mapping[str, Any]) -> Definition:
|
||||
name = identifier
|
||||
paren = name.find('(')
|
||||
qual_name = 'fmt::' + identifier
|
||||
|
||||
param_str = None
|
||||
paren = qual_name.find('(')
|
||||
if paren > 0:
|
||||
name, param_str = name[:paren], name[paren + 1:-1]
|
||||
|
||||
nodes = self._doxyxml.findall(
|
||||
qual_name, param_str = qual_name[:paren], qual_name[paren + 1:-1]
|
||||
|
||||
colons = qual_name.rfind('::')
|
||||
namespace, name = qual_name[:colons], qual_name[colons + 2:]
|
||||
|
||||
# Load XML.
|
||||
doxyxml = self._ns2doxyxml.get(namespace)
|
||||
if doxyxml is None:
|
||||
path = f'namespace{namespace.replace("::", "_1_1")}.xml'
|
||||
with open(os.path.join(self._doxyxml_dir, path)) as f:
|
||||
doxyxml = et.parse(f)
|
||||
self._ns2doxyxml[namespace] = doxyxml
|
||||
|
||||
nodes = doxyxml.findall(
|
||||
f"compounddef/sectiondef/memberdef/name[.='{name}']/..")
|
||||
candidates = []
|
||||
for node in nodes:
|
||||
@ -206,13 +215,14 @@ class CxxHandler(BaseHandler):
|
||||
return d
|
||||
|
||||
# Process a compound definition such as a struct.
|
||||
cls = self._doxyxml.findall(f"compounddef/innerclass[.='fmt::{name}']")
|
||||
cls = doxyxml.findall(f"compounddef/innerclass[.='{qual_name}']")
|
||||
if not cls:
|
||||
raise Exception(f'Cannot find {identifier}. Candidates: {candidates}')
|
||||
with open(os.path.join(self._doxyxml_dir, cls[0].get('refid') + '.xml')) as f:
|
||||
path = os.path.join(self._doxyxml_dir, cls[0].get('refid') + '.xml')
|
||||
with open(path) as f:
|
||||
xml = et.parse(f)
|
||||
node = xml.find('compounddef')
|
||||
d = Definition(name, node.get('kind'))
|
||||
d = Definition(identifier, node.get('kind'))
|
||||
d.template_params = convert_template_params(node)
|
||||
d.desc = get_description(node)
|
||||
d.members = []
|
||||
|
Loading…
Reference in New Issue
Block a user