1 /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 * Use of this file is governed by the BSD 3-clause license that
3 * can be found in the LICENSE.txt file in the project root.
8 #include "antlr4-common.h"
10 #ifdef USE_UTF8_INSTEAD_OF_CODECVT
16 // For all conversions utf8 <-> utf32.
17 // I wouldn't prefer wstring_convert because: according to
18 // https://en.cppreference.com/w/cpp/locale/wstring_convert,
19 // wstring_convert is deprecated in C++17.
20 // utfcpp (https://github.com/nemtrif/utfcpp) is a substitution.
21 #ifndef USE_UTF8_INSTEAD_OF_CODECVT
22 // VS 2015 and VS 2017 have different bugs in std::codecvt_utf8<char32_t> (VS 2013 works fine).
23 #if defined(_MSC_VER) && _MSC_VER >= 1900 && _MSC_VER < 2000
24 typedef std::wstring_convert<std::codecvt_utf8<__int32>, __int32> UTF32Converter;
26 typedef std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> UTF32Converter;
30 // The conversion functions fails in VS2017, so we explicitly use a workaround.
32 inline std::string utf32_to_utf8(T const& data)
34 #ifndef USE_UTF8_INSTEAD_OF_CODECVT
35 // Don't make the converter static or we have to serialize access to it.
36 thread_local UTF32Converter converter;
38 #if defined(_MSC_VER) && _MSC_VER >= 1900 && _MSC_VER < 2000
39 const auto p = reinterpret_cast<const int32_t *>(data.data());
40 return converter.to_bytes(p, p + data.size());
42 return converter.to_bytes(data);
46 utf8::utf32to8(data.begin(), data.end(), std::back_inserter(narrow));
51 inline UTF32String utf8_to_utf32(const char* first, const char* last)
53 #ifndef USE_UTF8_INSTEAD_OF_CODECVT
54 thread_local UTF32Converter converter;
56 #if defined(_MSC_VER) && _MSC_VER >= 1900 && _MSC_VER < 2000
57 auto r = converter.from_bytes(first, last);
58 i32string s = reinterpret_cast<const int32_t *>(r.data());
61 std::u32string s = converter.from_bytes(first, last);
66 utf8::utf8to32(first, last, std::back_inserter(wide));
71 void replaceAll(std::string &str, std::string const& from, std::string const& to);
73 // string <-> wstring conversion (UTF-16), e.g. for use with Window's wide APIs.
74 ANTLR4CPP_PUBLIC std::string ws2s(std::wstring const& wstr);
75 ANTLR4CPP_PUBLIC std::wstring s2ws(std::string const& str);