1// Locale support -*- C++ -*-
2
3// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4// 2006, 2007, 2008, 2009, 2010
5// Free Software Foundation, Inc.
6//
7// This file is part of the GNU ISO C++ Library.  This library is free
8// software; you can redistribute it and/or modify it under the
9// terms of the GNU General Public License as published by the
10// Free Software Foundation; either version 3, or (at your option)
11// any later version.
12
13// This library is distributed in the hope that it will be useful,
14// but WITHOUT ANY WARRANTY; without even the implied warranty of
15// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16// GNU General Public License for more details.
17
18// Under Section 7 of GPL version 3, you are granted additional
19// permissions described in the GCC Runtime Library Exception, version
20// 3.1, as published by the Free Software Foundation.
21
22// You should have received a copy of the GNU General Public License and
23// a copy of the GCC Runtime Library Exception along with this program;
24// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
25// <http://www.gnu.org/licenses/>.
26
27/** @file locale_classes.h
28 *  This is an internal header file, included by other library headers.
29 *  You should not attempt to use it directly.
30 */
31
32//
33// ISO C++ 14882: 22.1  Locales
34//
35
36#ifndef _LOCALE_CLASSES_H
37#define _LOCALE_CLASSES_H 1
38
39#pragma GCC system_header
40
41#include <bits/localefwd.h>
42#include <string>
43#include <ext/atomicity.h>
44
45_GLIBCXX_BEGIN_NAMESPACE(std)
46
47  // 22.1.1 Class locale
48  /**
49   *  @brief  Container class for localization functionality.
50   *  @ingroup locales
51   *
52   *  The locale class is first a class wrapper for C library locales.  It is
53   *  also an extensible container for user-defined localization.  A locale is
54   *  a collection of facets that implement various localization features such
55   *  as money, time, and number printing.
56   *
57   *  Constructing C++ locales does not change the C library locale.
58   *
59   *  This library supports efficient construction and copying of locales
60   *  through a reference counting implementation of the locale class.
61  */
62  class locale
63  {
64  public:
65    // Types:
66    /// Definition of locale::category.
67    typedef int	category;
68
69    // Forward decls and friends:
70    class facet;
71    class id;
72    class _Impl;
73
74    friend class facet;
75    friend class _Impl;
76
77    template<typename _Facet>
78      friend bool
79      has_facet(const locale&) throw();
80
81    template<typename _Facet>
82      friend const _Facet&
83      use_facet(const locale&);
84
85    template<typename _Cache>
86      friend struct __use_cache;
87
88    //@{
89    /**
90     *  @brief  Category values.
91     *
92     *  The standard category values are none, ctype, numeric, collate, time,
93     *  monetary, and messages.  They form a bitmask that supports union and
94     *  intersection.  The category all is the union of these values.
95     *
96     *  NB: Order must match _S_facet_categories definition in locale.cc
97    */
98    static const category none		= 0;
99    static const category ctype		= 1L << 0;
100    static const category numeric	= 1L << 1;
101    static const category collate	= 1L << 2;
102    static const category time		= 1L << 3;
103    static const category monetary	= 1L << 4;
104    static const category messages	= 1L << 5;
105    static const category all		= (ctype | numeric | collate |
106					   time  | monetary | messages);
107    //@}
108
109    // Construct/copy/destroy:
110
111    /**
112     *  @brief  Default constructor.
113     *
114     *  Constructs a copy of the global locale.  If no locale has been
115     *  explicitly set, this is the C locale.
116    */
117    locale() throw();
118
119    /**
120     *  @brief  Copy constructor.
121     *
122     *  Constructs a copy of @a other.
123     *
124     *  @param  other  The locale to copy.
125    */
126    locale(const locale& __other) throw();
127
128    /**
129     *  @brief  Named locale constructor.
130     *
131     *  Constructs a copy of the named C library locale.
132     *
133     *  @param  s  Name of the locale to construct.
134     *  @throw  std::runtime_error if s is null or an undefined locale.
135    */
136    explicit
137    locale(const char* __s);
138
139    /**
140     *  @brief  Construct locale with facets from another locale.
141     *
142     *  Constructs a copy of the locale @a base.  The facets specified by @a
143     *  cat are replaced with those from the locale named by @a s.  If base is
144     *  named, this locale instance will also be named.
145     *
146     *  @param  base  The locale to copy.
147     *  @param  s  Name of the locale to use facets from.
148     *  @param  cat  Set of categories defining the facets to use from s.
149     *  @throw  std::runtime_error if s is null or an undefined locale.
150    */
151    locale(const locale& __base, const char* __s, category __cat);
152
153    /**
154     *  @brief  Construct locale with facets from another locale.
155     *
156     *  Constructs a copy of the locale @a base.  The facets specified by @a
157     *  cat are replaced with those from the locale @a add.  If @a base and @a
158     *  add are named, this locale instance will also be named.
159     *
160     *  @param  base  The locale to copy.
161     *  @param  add  The locale to use facets from.
162     *  @param  cat  Set of categories defining the facets to use from add.
163    */
164    locale(const locale& __base, const locale& __add, category __cat);
165
166    /**
167     *  @brief  Construct locale with another facet.
168     *
169     *  Constructs a copy of the locale @a other.  The facet @f is added to
170     *  @other, replacing an existing facet of type Facet if there is one.  If
171     *  @f is null, this locale is a copy of @a other.
172     *
173     *  @param  other  The locale to copy.
174     *  @param  f  The facet to add in.
175    */
176    template<typename _Facet>
177      locale(const locale& __other, _Facet* __f);
178
179    /// Locale destructor.
180    ~locale() throw();
181
182    /**
183     *  @brief  Assignment operator.
184     *
185     *  Set this locale to be a copy of @a other.
186     *
187     *  @param  other  The locale to copy.
188     *  @return  A reference to this locale.
189    */
190    const locale&
191    operator=(const locale& __other) throw();
192
193    /**
194     *  @brief  Construct locale with another facet.
195     *
196     *  Constructs and returns a new copy of this locale.  Adds or replaces an
197     *  existing facet of type Facet from the locale @a other into the new
198     *  locale.
199     *
200     *  @param  Facet  The facet type to copy from other
201     *  @param  other  The locale to copy from.
202     *  @return  Newly constructed locale.
203     *  @throw  std::runtime_error if other has no facet of type Facet.
204    */
205    template<typename _Facet>
206      locale
207      combine(const locale& __other) const;
208
209    // Locale operations:
210    /**
211     *  @brief  Return locale name.
212     *  @return  Locale name or "*" if unnamed.
213    */
214    string
215    name() const;
216
217    /**
218     *  @brief  Locale equality.
219     *
220     *  @param  other  The locale to compare against.
221     *  @return  True if other and this refer to the same locale instance, are
222     *		 copies, or have the same name.  False otherwise.
223    */
224    bool
225    operator==(const locale& __other) const throw();
226
227    /**
228     *  @brief  Locale inequality.
229     *
230     *  @param  other  The locale to compare against.
231     *  @return  ! (*this == other)
232    */
233    bool
234    operator!=(const locale& __other) const throw()
235    { return !(this->operator==(__other)); }
236
237    /**
238     *  @brief  Compare two strings according to collate.
239     *
240     *  Template operator to compare two strings using the compare function of
241     *  the collate facet in this locale.  One use is to provide the locale to
242     *  the sort function.  For example, a vector v of strings could be sorted
243     *  according to locale loc by doing:
244     *  @code
245     *  std::sort(v.begin(), v.end(), loc);
246     *  @endcode
247     *
248     *  @param  s1  First string to compare.
249     *  @param  s2  Second string to compare.
250     *  @return  True if collate<Char> facet compares s1 < s2, else false.
251    */
252    template<typename _Char, typename _Traits, typename _Alloc>
253      bool
254      operator()(const basic_string<_Char, _Traits, _Alloc>& __s1,
255		 const basic_string<_Char, _Traits, _Alloc>& __s2) const;
256
257    // Global locale objects:
258    /**
259     *  @brief  Set global locale
260     *
261     *  This function sets the global locale to the argument and returns a
262     *  copy of the previous global locale.  If the argument has a name, it
263     *  will also call std::setlocale(LC_ALL, loc.name()).
264     *
265     *  @param  locale  The new locale to make global.
266     *  @return  Copy of the old global locale.
267    */
268    static locale
269    global(const locale&);
270
271    /**
272     *  @brief  Return reference to the C locale.
273    */
274    static const locale&
275    classic();
276
277  private:
278    // The (shared) implementation
279    _Impl*		_M_impl;
280
281    // The "C" reference locale
282    static _Impl*       _S_classic;
283
284    // Current global locale
285    static _Impl*	_S_global;
286
287    // Names of underlying locale categories.
288    // NB: locale::global() has to know how to modify all the
289    // underlying categories, not just the ones required by the C++
290    // standard.
291    static const char* const* const _S_categories;
292
293    // Number of standard categories. For C++, these categories are
294    // collate, ctype, monetary, numeric, time, and messages. These
295    // directly correspond to ISO C99 macros LC_COLLATE, LC_CTYPE,
296    // LC_MONETARY, LC_NUMERIC, and LC_TIME. In addition, POSIX (IEEE
297    // 1003.1-2001) specifies LC_MESSAGES.
298    // In addition to the standard categories, the underlying
299    // operating system is allowed to define extra LC_*
300    // macros. For GNU systems, the following are also valid:
301    // LC_PAPER, LC_NAME, LC_ADDRESS, LC_TELEPHONE, LC_MEASUREMENT,
302    // and LC_IDENTIFICATION.
303    enum { _S_categories_size = 6 + _GLIBCXX_NUM_CATEGORIES };
304
305#ifdef __GTHREADS
306    static __gthread_once_t _S_once;
307#endif
308
309    explicit
310    locale(_Impl*) throw();
311
312    static void
313    _S_initialize();
314
315    static void
316    _S_initialize_once() throw();
317
318    static category
319    _S_normalize_category(category);
320
321    void
322    _M_coalesce(const locale& __base, const locale& __add, category __cat);
323  };
324
325
326  // 22.1.1.1.2  Class locale::facet
327  /**
328   *  @brief  Localization functionality base class.
329   *  @ingroup locales
330   *
331   *  The facet class is the base class for a localization feature, such as
332   *  money, time, and number printing.  It provides common support for facets
333   *  and reference management.
334   *
335   *  Facets may not be copied or assigned.
336  */
337  class locale::facet
338  {
339  private:
340    friend class locale;
341    friend class locale::_Impl;
342
343    mutable _Atomic_word		_M_refcount;
344
345    // Contains data from the underlying "C" library for the classic locale.
346    static __c_locale                   _S_c_locale;
347
348    // String literal for the name of the classic locale.
349    static const char			_S_c_name[2];
350
351#ifdef __GTHREADS
352    static __gthread_once_t		_S_once;
353#endif
354
355    static void
356    _S_initialize_once();
357
358  protected:
359    /**
360     *  @brief  Facet constructor.
361     *
362     *  This is the constructor provided by the standard.  If refs is 0, the
363     *  facet is destroyed when the last referencing locale is destroyed.
364     *  Otherwise the facet will never be destroyed.
365     *
366     *  @param refs  The initial value for reference count.
367    */
368    explicit
369    facet(size_t __refs = 0) throw() : _M_refcount(__refs ? 1 : 0)
370    { }
371
372    /// Facet destructor.
373    virtual
374    ~facet();
375
376    static void
377    _S_create_c_locale(__c_locale& __cloc, const char* __s,
378		       __c_locale __old = 0);
379
380    static __c_locale
381    _S_clone_c_locale(__c_locale& __cloc) throw();
382
383    static void
384    _S_destroy_c_locale(__c_locale& __cloc);
385
386    static __c_locale
387    _S_lc_ctype_c_locale(__c_locale __cloc, const char* __s);
388
389    // Returns data from the underlying "C" library data for the
390    // classic locale.
391    static __c_locale
392    _S_get_c_locale();
393
394    _GLIBCXX_CONST static const char*
395    _S_get_c_name() throw();
396
397  private:
398    void
399    _M_add_reference() const throw()
400    { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); }
401
402    void
403    _M_remove_reference() const throw()
404    {
405      if (__gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1) == 1)
406	{
407	  __try
408	    { delete this; }
409	  __catch(...)
410	    { }
411	}
412    }
413
414    facet(const facet&);  // Not defined.
415
416    facet&
417    operator=(const facet&);  // Not defined.
418  };
419
420
421  // 22.1.1.1.3 Class locale::id
422  /**
423   *  @brief  Facet ID class.
424   *  @ingroup locales
425   *
426   *  The ID class provides facets with an index used to identify them.
427   *  Every facet class must define a public static member locale::id, or be
428   *  derived from a facet that provides this member, otherwise the facet
429   *  cannot be used in a locale.  The locale::id ensures that each class
430   *  type gets a unique identifier.
431  */
432  class locale::id
433  {
434  private:
435    friend class locale;
436    friend class locale::_Impl;
437
438    template<typename _Facet>
439      friend const _Facet&
440      use_facet(const locale&);
441
442    template<typename _Facet>
443      friend bool
444      has_facet(const locale&) throw();
445
446    // NB: There is no accessor for _M_index because it may be used
447    // before the constructor is run; the effect of calling a member
448    // function (even an inline) would be undefined.
449    mutable size_t		_M_index;
450
451    // Last id number assigned.
452    static _Atomic_word		_S_refcount;
453
454    void
455    operator=(const id&);  // Not defined.
456
457    id(const id&);  // Not defined.
458
459  public:
460    // NB: This class is always a static data member, and thus can be
461    // counted on to be zero-initialized.
462    /// Constructor.
463    id() { }
464
465    size_t
466    _M_id() const throw();
467  };
468
469
470  // Implementation object for locale.
471  class locale::_Impl
472  {
473  public:
474    // Friends.
475    friend class locale;
476    friend class locale::facet;
477
478    template<typename _Facet>
479      friend bool
480      has_facet(const locale&) throw();
481
482    template<typename _Facet>
483      friend const _Facet&
484      use_facet(const locale&);
485
486    template<typename _Cache>
487      friend struct __use_cache;
488
489  private:
490    // Data Members.
491    _Atomic_word			_M_refcount;
492    const facet**			_M_facets;
493    size_t				_M_facets_size;
494    const facet**			_M_caches;
495    char**				_M_names;
496    static const locale::id* const	_S_id_ctype[];
497    static const locale::id* const	_S_id_numeric[];
498    static const locale::id* const	_S_id_collate[];
499    static const locale::id* const	_S_id_time[];
500    static const locale::id* const	_S_id_monetary[];
501    static const locale::id* const	_S_id_messages[];
502    static const locale::id* const* const _S_facet_categories[];
503
504    void
505    _M_add_reference() throw()
506    { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); }
507
508    void
509    _M_remove_reference() throw()
510    {
511      if (__gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1) == 1)
512	{
513	  __try
514	    { delete this; }
515	  __catch(...)
516	    { }
517	}
518    }
519
520    _Impl(const _Impl&, size_t);
521    _Impl(const char*, size_t);
522    _Impl(size_t) throw();
523
524   ~_Impl() throw();
525
526    _Impl(const _Impl&);  // Not defined.
527
528    void
529    operator=(const _Impl&);  // Not defined.
530
531    bool
532    _M_check_same_name()
533    {
534      bool __ret = true;
535      if (_M_names[1])
536	// We must actually compare all the _M_names: can be all equal!
537	for (size_t __i = 0; __ret && __i < _S_categories_size - 1; ++__i)
538	  __ret = __builtin_strcmp(_M_names[__i], _M_names[__i + 1]) == 0;
539      return __ret;
540    }
541
542    void
543    _M_replace_categories(const _Impl*, category);
544
545    void
546    _M_replace_category(const _Impl*, const locale::id* const*);
547
548    void
549    _M_replace_facet(const _Impl*, const locale::id*);
550
551    void
552    _M_install_facet(const locale::id*, const facet*);
553
554    template<typename _Facet>
555      void
556      _M_init_facet(_Facet* __facet)
557      { _M_install_facet(&_Facet::id, __facet); }
558
559    void
560    _M_install_cache(const facet*, size_t);
561  };
562
563
564  /**
565   *  @brief  Test for the presence of a facet.
566   *
567   *  has_facet tests the locale argument for the presence of the facet type
568   *  provided as the template parameter.  Facets derived from the facet
569   *  parameter will also return true.
570   *
571   *  @param  Facet  The facet type to test the presence of.
572   *  @param  locale  The locale to test.
573   *  @return  true if locale contains a facet of type Facet, else false.
574  */
575  template<typename _Facet>
576    bool
577    has_facet(const locale& __loc) throw();
578
579  /**
580   *  @brief  Return a facet.
581   *
582   *  use_facet looks for and returns a reference to a facet of type Facet
583   *  where Facet is the template parameter.  If has_facet(locale) is true,
584   *  there is a suitable facet to return.  It throws std::bad_cast if the
585   *  locale doesn't contain a facet of type Facet.
586   *
587   *  @param  Facet  The facet type to access.
588   *  @param  locale  The locale to use.
589   *  @return  Reference to facet of type Facet.
590   *  @throw  std::bad_cast if locale doesn't contain a facet of type Facet.
591  */
592  template<typename _Facet>
593    const _Facet&
594    use_facet(const locale& __loc);
595
596
597  /**
598   *  @brief  Facet for localized string comparison.
599   *
600   *  This facet encapsulates the code to compare strings in a localized
601   *  manner.
602   *
603   *  The collate template uses protected virtual functions to provide
604   *  the actual results.  The public accessors forward the call to
605   *  the virtual functions.  These virtual functions are hooks for
606   *  developers to implement the behavior they require from the
607   *  collate facet.
608  */
609  template<typename _CharT>
610    class collate : public locale::facet
611    {
612    public:
613      // Types:
614      //@{
615      /// Public typedefs
616      typedef _CharT			char_type;
617      typedef basic_string<_CharT>	string_type;
618      //@}
619
620    protected:
621      // Underlying "C" library locale information saved from
622      // initialization, needed by collate_byname as well.
623      __c_locale			_M_c_locale_collate;
624
625    public:
626      /// Numpunct facet id.
627      static locale::id			id;
628
629      /**
630       *  @brief  Constructor performs initialization.
631       *
632       *  This is the constructor provided by the standard.
633       *
634       *  @param refs  Passed to the base facet class.
635      */
636      explicit
637      collate(size_t __refs = 0)
638      : facet(__refs), _M_c_locale_collate(_S_get_c_locale())
639      { }
640
641      /**
642       *  @brief  Internal constructor. Not for general use.
643       *
644       *  This is a constructor for use by the library itself to set up new
645       *  locales.
646       *
647       *  @param cloc  The C locale.
648       *  @param refs  Passed to the base facet class.
649      */
650      explicit
651      collate(__c_locale __cloc, size_t __refs = 0)
652      : facet(__refs), _M_c_locale_collate(_S_clone_c_locale(__cloc))
653      { }
654
655      /**
656       *  @brief  Compare two strings.
657       *
658       *  This function compares two strings and returns the result by calling
659       *  collate::do_compare().
660       *
661       *  @param lo1  Start of string 1.
662       *  @param hi1  End of string 1.
663       *  @param lo2  Start of string 2.
664       *  @param hi2  End of string 2.
665       *  @return  1 if string1 > string2, -1 if string1 < string2, else 0.
666      */
667      int
668      compare(const _CharT* __lo1, const _CharT* __hi1,
669	      const _CharT* __lo2, const _CharT* __hi2) const
670      { return this->do_compare(__lo1, __hi1, __lo2, __hi2); }
671
672      /**
673       *  @brief  Transform string to comparable form.
674       *
675       *  This function is a wrapper for strxfrm functionality.  It takes the
676       *  input string and returns a modified string that can be directly
677       *  compared to other transformed strings.  In the C locale, this
678       *  function just returns a copy of the input string.  In some other
679       *  locales, it may replace two chars with one, change a char for
680       *  another, etc.  It does so by returning collate::do_transform().
681       *
682       *  @param lo  Start of string.
683       *  @param hi  End of string.
684       *  @return  Transformed string_type.
685      */
686      string_type
687      transform(const _CharT* __lo, const _CharT* __hi) const
688      { return this->do_transform(__lo, __hi); }
689
690      /**
691       *  @brief  Return hash of a string.
692       *
693       *  This function computes and returns a hash on the input string.  It
694       *  does so by returning collate::do_hash().
695       *
696       *  @param lo  Start of string.
697       *  @param hi  End of string.
698       *  @return  Hash value.
699      */
700      long
701      hash(const _CharT* __lo, const _CharT* __hi) const
702      { return this->do_hash(__lo, __hi); }
703
704      // Used to abstract out _CharT bits in virtual member functions, below.
705      int
706      _M_compare(const _CharT*, const _CharT*) const throw();
707
708      size_t
709      _M_transform(_CharT*, const _CharT*, size_t) const throw();
710
711  protected:
712      /// Destructor.
713      virtual
714      ~collate()
715      { _S_destroy_c_locale(_M_c_locale_collate); }
716
717      /**
718       *  @brief  Compare two strings.
719       *
720       *  This function is a hook for derived classes to change the value
721       *  returned.  @see compare().
722       *
723       *  @param lo1  Start of string 1.
724       *  @param hi1  End of string 1.
725       *  @param lo2  Start of string 2.
726       *  @param hi2  End of string 2.
727       *  @return  1 if string1 > string2, -1 if string1 < string2, else 0.
728      */
729      virtual int
730      do_compare(const _CharT* __lo1, const _CharT* __hi1,
731		 const _CharT* __lo2, const _CharT* __hi2) const;
732
733      /**
734       *  @brief  Transform string to comparable form.
735       *
736       *  This function is a hook for derived classes to change the value
737       *  returned.
738       *
739       *  @param lo1  Start of string 1.
740       *  @param hi1  End of string 1.
741       *  @param lo2  Start of string 2.
742       *  @param hi2  End of string 2.
743       *  @return  1 if string1 > string2, -1 if string1 < string2, else 0.
744      */
745      virtual string_type
746      do_transform(const _CharT* __lo, const _CharT* __hi) const;
747
748      /**
749       *  @brief  Return hash of a string.
750       *
751       *  This function computes and returns a hash on the input string.  This
752       *  function is a hook for derived classes to change the value returned.
753       *
754       *  @param lo  Start of string.
755       *  @param hi  End of string.
756       *  @return  Hash value.
757      */
758      virtual long
759      do_hash(const _CharT* __lo, const _CharT* __hi) const;
760    };
761
762  template<typename _CharT>
763    locale::id collate<_CharT>::id;
764
765  // Specializations.
766  template<>
767    int
768    collate<char>::_M_compare(const char*, const char*) const throw();
769
770  template<>
771    size_t
772    collate<char>::_M_transform(char*, const char*, size_t) const throw();
773
774#ifdef _GLIBCXX_USE_WCHAR_T
775  template<>
776    int
777    collate<wchar_t>::_M_compare(const wchar_t*, const wchar_t*) const throw();
778
779  template<>
780    size_t
781    collate<wchar_t>::_M_transform(wchar_t*, const wchar_t*, size_t) const throw();
782#endif
783
784  /// class collate_byname [22.2.4.2].
785  template<typename _CharT>
786    class collate_byname : public collate<_CharT>
787    {
788    public:
789      //@{
790      /// Public typedefs
791      typedef _CharT               char_type;
792      typedef basic_string<_CharT> string_type;
793      //@}
794
795      explicit
796      collate_byname(const char* __s, size_t __refs = 0)
797      : collate<_CharT>(__refs)
798      {
799	if (__builtin_strcmp(__s, "C") != 0
800	    && __builtin_strcmp(__s, "POSIX") != 0)
801	  {
802	    this->_S_destroy_c_locale(this->_M_c_locale_collate);
803	    this->_S_create_c_locale(this->_M_c_locale_collate, __s);
804	  }
805      }
806
807    protected:
808      virtual
809      ~collate_byname() { }
810    };
811
812_GLIBCXX_END_NAMESPACE
813
814#ifndef _GLIBCXX_EXPORT_TEMPLATE
815# include <bits/locale_classes.tcc>
816#endif
817
818#endif
819