Changes in / [4e08a54:da87eaf]


Ignore:
Files:
3 deleted
53 edited

Legend:

Unmodified
Added
Removed
  • libcfa/src/collections/string.cfa

    r4e08a54 rda87eaf  
    1010// Created On       : Fri Sep 03 11:00:00 2021
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Apr 15 21:56:28 2024
    13 // Update Count     : 260
     12// Last Modified On : Wed Feb  7 21:17:06 2024
     13// Update Count     : 259
    1414//
    1515
     
    198198        cstr[len] = '\0';                                                                       // terminate
    199199        _Ostream_Manip(const char *) cf @= { cstr, f.wd, f.pc, f.base, {f.all} };
    200         return os | cf | nonl;
     200        os | cf | nonl;
     201        return os;
    201202} // ?|?
    202203
  • libcfa/src/collections/string_res.cfa

    r4e08a54 rda87eaf  
    1010// Created On       : Fri Sep 03 11:00:00 2021
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Apr 15 21:56:27 2024
    13 // Update Count     : 85
     12// Last Modified On : Sat Feb 10 17:47:22 2024
     13// Update Count     : 83
    1414//
    1515
     
    200200ofstream & ?|?(ofstream & out, const string_res & s) {
    201201        // CFA string is NOT null terminated, so print exactly lnth characters in a minimum width of 0.
    202         return out | wd( 0, s.Handle.lnth, s.Handle.s ) | nonl;
     202        out | wd( 0, s.Handle.lnth, s.Handle.s ) | nonl;
     203        return out;
    203204}
    204205
  • libcfa/src/stdlib.hfa

    r4e08a54 rda87eaf  
    1010// Created On       : Thu Jan 28 17:12:35 2016
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Fri Apr 19 09:47:55 2024
    13 // Update Count     : 826
     12// Last Modified On : Fri Apr 12 07:39:15 2024
     13// Update Count     : 812
    1414//
    1515
     
    4747
    4848static inline forall( T & | sized(T) ) {
    49         // CFA safe equivalents, i.e., implicit size specification, eliminate return-type cast
     49        // CFA safe equivalents, i.e., implicit size specification
    5050
    5151        T * malloc( void ) {
     
    6464        } // calloc
    6565
    66         T * resize( T * ptr, size_t size ) {
    67                 if ( _Alignof(T) <= libAlign() ) return (T *)resize( (void *)ptr, size ); // C resize
     66        T * resize( T * ptr, size_t size ) {                            // CFA resize, eliminate return-type cast
     67                if ( _Alignof(T) <= libAlign() ) return (T *)resize( (void *)ptr, size ); // CFA resize
    6868                else return (T *)resize( (void *)ptr, _Alignof(T), size ); // CFA resize
    6969        } // resize
    7070
    71         T * resize( T * ptr, size_t alignment, size_t size ) {
    72                 return (T *)resize( (void *)ptr, alignment, size ); // CFA resize
    73         } // resize
    74 
    75         T * realloc( T * ptr, size_t size ) {                           // CFA realloc
     71        T * realloc( T * ptr, size_t size ) {                           // CFA realloc, eliminate return-type cast
    7672                if ( _Alignof(T) <= libAlign() ) return (T *)realloc( (void *)ptr, size ); // C realloc
    7773                else return (T *)realloc( (void *)ptr, _Alignof(T), size ); // CFA realloc
    7874        } // realloc
    7975
    80         T * realloc( T * ptr, size_t alignment, size_t size ) {
    81                 return (T *)realloc( (void *)ptr, alignment, size ); // CFA realloc
    82         } // realloc
    83 
    84         T * reallocarray( T * ptr, size_t dim ) {                       // CFA reallocarray
    85                 if ( _Alignof(T) <= libAlign() ) return (T *)reallocarray( (void *)ptr, dim, sizeof(T) ); // C reallocarray
    86                 else return (T *)reallocarray( (void *)ptr, _Alignof(T), dim ); // CFA reallocarray
    87         } // realloc
    88 
    89         T * reallocarray( T * ptr, size_t alignment, size_t dim ) {
    90                 return (T *)reallocarray( (void *)ptr, alignment, dim ); // CFA reallocarray
    91         } // realloc
    92 
    9376        T * memalign( size_t align ) {
    9477                return (T *)memalign( align, sizeof(T) );               // C memalign
     
    9982        } // amemalign
    10083
    101         T * cmemalign( size_t align, size_t dim ) {
     84        T * cmemalign( size_t align, size_t dim  ) {
    10285                return (T *)cmemalign( align, dim, sizeof(T) ); // CFA cmemalign
    10386        } // cmemalign
     
    176159static inline T_resize ?`resize( void * a )     { return (T_resize){a}; }
    177160
     161extern "C" ssize_t write(int fd, const void *buf, size_t count);
    178162static inline forall( T & | sized(T) ) {
    179         S_fill(T) ?`fill( T t ) {
     163        S_fill(T) ?`fill ( T t ) {
    180164                S_fill(T) ret = { 't' };
    181165                size_t size = sizeof(T);
     
    186170                return ret;
    187171        }
    188         S_fill(T) ?`fill( zero_t ) = void; // FIX ME: remove this once ticket 214 is resolved
    189         S_fill(T) ?`fill( T * a ) { return (S_fill(T)){ 'T', '0', 0, a }; } // FIX ME: remove this once ticket 214 is resolved
    190         S_fill(T) ?`fill( char c ) { return (S_fill(T)){ 'c', c };      }
    191         S_fill(T) ?`fill( T a[], size_t nmemb ) { return (S_fill(T)){ 'a', '0', nmemb * sizeof(T), a }; }
     172        S_fill(T) ?`fill ( zero_t ) = void; // FIX ME: remove this once ticket 214 is resolved
     173        S_fill(T) ?`fill ( T * a ) { return (S_fill(T)){ 'T', '0', 0, a }; } // FIX ME: remove this once ticket 214 is resolved
     174        S_fill(T) ?`fill ( char c ) { return (S_fill(T)){ 'c', c };     }
     175        S_fill(T) ?`fill ( T a[], size_t nmemb ) { return (S_fill(T)){ 'a', '0', nmemb * sizeof(T), a }; }
    192176
    193177        S_realloc(T) ?`realloc ( T * a ) { return (S_realloc(T)){a}; }
     
    226210        } // alloc_internal$
    227211
    228         forall( List ... | { T * alloc_internal$( void *, T *, size_t, size_t, S_fill(T), List ); } ) {
    229                 T * alloc_internal$( void *, T *, size_t Align, size_t Dim, S_fill(T) Fill, T_resize Resize, List rest ) {
     212        forall( TT... | { T * alloc_internal$( void *, T *, size_t, size_t, S_fill(T), TT ); } ) {
     213                T * alloc_internal$( void *, T *, size_t Align, size_t Dim, S_fill(T) Fill, T_resize Resize, TT rest ) {
    230214                return alloc_internal$( Resize, (T*)0p, Align, Dim, Fill, rest);
    231215                }
    232216
    233                 T * alloc_internal$( void *, T *, size_t Align, size_t Dim, S_fill(T) Fill, S_realloc(T) Realloc, List rest ) {
     217                T * alloc_internal$( void *, T *, size_t Align, size_t Dim, S_fill(T) Fill, S_realloc(T) Realloc, TT rest ) {
    234218                return alloc_internal$( (void*)0p, Realloc, Align, Dim, Fill, rest);
    235219                }
    236220
    237                 T * alloc_internal$( void * Resize, T * Realloc, size_t, size_t Dim, S_fill(T) Fill, T_align Align, List rest ) {
     221                T * alloc_internal$( void * Resize, T * Realloc, size_t, size_t Dim, S_fill(T) Fill, T_align Align, TT rest ) {
    238222                return alloc_internal$( Resize, Realloc, Align, Dim, Fill, rest);
    239223                }
    240224
    241                 T * alloc_internal$( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T), S_fill(T) Fill, List rest ) {
     225                T * alloc_internal$( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T), S_fill(T) Fill, TT rest ) {
    242226                return alloc_internal$( Resize, Realloc, Align, Dim, Fill, rest );
    243227                }
    244228
    245             T * alloc( List all ) {
     229            T * alloc( TT all ) {
    246230                return alloc_internal$( (void*)0p, (T*)0p, (_Alignof(T) > libAlign() ? _Alignof(T) : libAlign()), (size_t)1, (S_fill(T)){'0'}, all );
    247231            }
    248232
    249             T * alloc( size_t dim, List all ) {
     233            T * alloc( size_t dim, TT all ) {
    250234                return alloc_internal$( (void*)0p, (T*)0p, (_Alignof(T) > libAlign() ? _Alignof(T) : libAlign()), dim, (S_fill(T)){'0'}, all );
    251235            }
    252         } // distribution List
     236        } // distribution TT
    253237} // distribution T
    254238
     
    274258
    275259// CFA deallocation for multiple objects
    276 static inline forall( T & )
     260static inline forall( T & )                                                     // FIX ME, problems with 0p in list
    277261void free( T * ptr ) {
    278262        free( (void *)ptr );                                                            // C free
    279263} // free
    280 static inline forall( T &, List ... | { void free( List ); } )
    281 void free( T * ptr, List rest ) {
     264static inline forall( T &, TT... | { void free( TT ); } )
     265void free( T * ptr, TT rest ) {
    282266        free( ptr );
    283267        free( rest );
     
    285269
    286270// CFA allocation/deallocation and constructor/destructor, non-array types
    287 static inline forall( T & | sized(T), Parms ... | { void ?{}( T &, Parms ); } )
    288 T * new( Parms p ) {
     271static inline forall( T & | sized(T), TT... | { void ?{}( T &, TT ); } )
     272T * new( TT p ) {
    289273        return &(*(T *)malloc()){ p };                                          // run constructor
    290274} // new
     
    298282        free( ptr );                                                                            // always call free
    299283} // delete
    300 static inline forall( T &, List ... | { void ^?{}( T & ); void delete( List ); } )
    301 void delete( T * ptr, List rest ) {
     284static inline forall( T &, TT... | { void ^?{}( T & ); void delete( TT ); } )
     285void delete( T * ptr, TT rest ) {
    302286        delete( ptr );
    303287        delete( rest );
     
    305289
    306290// CFA allocation/deallocation and constructor/destructor, array types
    307 forall( T & | sized(T), Parms ... | { void ?{}( T &, Parms ); } ) T * anew( size_t dim, Parms p );
     291forall( T & | sized(T), TT... | { void ?{}( T &, TT ); } ) T * anew( size_t dim, TT p );
    308292forall( T & | sized(T) | { void ^?{}( T & ); } ) void adelete( T arr[] );
    309 forall( T & | sized(T) | { void ^?{}( T & ); }, List ... | { void adelete( List ); } ) void adelete( T arr[], List rest );
    310 
     293forall( T & | sized(T) | { void ^?{}( T & ); }, TT... | { void adelete( TT ); } ) void adelete( T arr[], TT rest );
    311294//---------------------------------------
    312295
  • libcfa/src/time.hfa

    r4e08a54 rda87eaf  
    1010// Created On       : Wed Mar 14 23:18:57 2018
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Apr 18 12:07:21 2024
    13 // Update Count     : 670
     12// Last Modified On : Sat Oct  8 09:07:48 2022
     13// Update Count     : 668
    1414//
    1515
     
    8484        Duration ?`m( int64_t min ) { return (Duration)@{ min * (60LL * TIMEGRAN) }; }
    8585        Duration ?`m( double min ) { return (Duration)@{ min * (60LL * TIMEGRAN) }; }
    86         Duration ?`h( int64_t hour ) { return (Duration)@{ hour * (60LL * 60LL * TIMEGRAN) }; }
    87         Duration ?`h( double hour ) { return (Duration)@{ hour * (60LL * 60LL * TIMEGRAN) }; }
    88         Duration ?`d( int64_t day ) { return (Duration)@{ day * (24LL * 60LL * 60LL * TIMEGRAN) }; }
    89         Duration ?`d( double day ) { return (Duration)@{ day * (24LL * 60LL * 60LL * TIMEGRAN) }; }
    90         Duration ?`w( int64_t week ) { return (Duration)@{ week * (7LL * 24LL * 60LL * 60LL * TIMEGRAN) }; }
    91         Duration ?`w( double week ) { return (Duration)@{ week * (7LL * 24LL * 60LL * 60LL * TIMEGRAN) }; }
     86        Duration ?`h( int64_t hours ) { return (Duration)@{ hours * (60LL * 60LL * TIMEGRAN) }; }
     87        Duration ?`h( double hours ) { return (Duration)@{ hours * (60LL * 60LL * TIMEGRAN) }; }
     88        Duration ?`d( int64_t days ) { return (Duration)@{ days * (24LL * 60LL * 60LL * TIMEGRAN) }; }
     89        Duration ?`d( double days ) { return (Duration)@{ days * (24LL * 60LL * 60LL * TIMEGRAN) }; }
     90        Duration ?`w( int64_t weeks ) { return (Duration)@{ weeks * (7LL * 24LL * 60LL * 60LL * TIMEGRAN) }; }
     91        Duration ?`w( double weeks ) { return (Duration)@{ weeks * (7LL * 24LL * 60LL * 60LL * TIMEGRAN) }; }
    9292
    9393        int64_t ?`ns( Duration dur ) { return dur.tn; }
  • src/AST/Decl.cpp

    r4e08a54 rda87eaf  
    169169}
    170170
    171 const std::string EnumDecl::getUnmangeldArrayName( const ast::EnumAttribute attr ) const {
    172                 switch( attr ) {
    173                         case ast::EnumAttribute::Value: return "values_" + name ;
    174                         case ast::EnumAttribute::Label: return "labels_" + name;
    175                         default: /* Posn does not generate array */
    176                                 return "";
    177                 }
    178         }
    179 
    180171}
    181172
  • src/AST/Decl.hpp

    r4e08a54 rda87eaf  
    303303};
    304304
    305 enum class EnumAttribute{ Value, Posn, Label };
    306305/// enum declaration `enum Foo { ... };`
    307306class EnumDecl final : public AggregateDecl {
     
    327326        const char * typeString() const override { return aggrString( Enum ); }
    328327
    329         const std::string getUnmangeldArrayName( const EnumAttribute attr ) const;
     328
    330329private:
    331330        EnumDecl * clone() const override { return new EnumDecl{ *this }; }
  • src/AST/Expr.cpp

    r4e08a54 rda87eaf  
    246246ConstantExpr * ConstantExpr::from_bool( const CodeLocation & loc, bool b ) {
    247247        return new ConstantExpr{
    248                 loc, new BasicType{ BasicKind::Bool }, b ? "1" : "0", (unsigned long long)b };
     248                loc, new BasicType{ BasicType::Bool }, b ? "1" : "0", (unsigned long long)b };
    249249}
    250250
    251251ConstantExpr * ConstantExpr::from_int( const CodeLocation & loc, int i ) {
    252252        return new ConstantExpr{
    253                 loc, new BasicType{ BasicKind::SignedInt }, std::to_string( i ), (unsigned long long)i };
     253                loc, new BasicType{ BasicType::SignedInt }, std::to_string( i ), (unsigned long long)i };
    254254}
    255255
    256256ConstantExpr * ConstantExpr::from_ulong( const CodeLocation & loc, unsigned long i ) {
    257257        return new ConstantExpr{
    258                 loc, new BasicType{ BasicKind::LongUnsignedInt }, std::to_string( i ),
     258                loc, new BasicType{ BasicType::LongUnsignedInt }, std::to_string( i ),
    259259                (unsigned long long)i };
    260260}
    261261
    262262ConstantExpr * ConstantExpr::from_string( const CodeLocation & loc, const std::string & str ) {
    263         const Type * charType = new BasicType( BasicKind::Char );
     263        const Type * charType = new BasicType( BasicType::Char );
    264264        // Adjust the length of the string for the terminator.
    265265        const Expr * strSize = from_ulong( loc, str.size() + 1 );
     
    277277
    278278SizeofExpr::SizeofExpr( const CodeLocation & loc, const Expr * e )
    279 : Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
     279: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
    280280
    281281SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * t )
    282 : Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
     282: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
    283283
    284284// --- AlignofExpr
    285285
    286286AlignofExpr::AlignofExpr( const CodeLocation & loc, const Expr * e )
    287 : Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
     287: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
    288288
    289289AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * t )
    290 : Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
     290: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
    291291
    292292// --- OffsetofExpr
    293293
    294294OffsetofExpr::OffsetofExpr( const CodeLocation & loc, const Type * ty, const DeclWithType * mem )
    295 : Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), type( ty ), member( mem ) {
     295: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), type( ty ), member( mem ) {
    296296        assert( type );
    297297        assert( member );
     
    302302OffsetPackExpr::OffsetPackExpr( const CodeLocation & loc, const StructInstType * ty )
    303303: Expr( loc, new ArrayType{
    304         new BasicType{ BasicKind::LongUnsignedInt }, nullptr, FixedLen, DynamicDim }
     304        new BasicType{ BasicType::LongUnsignedInt }, nullptr, FixedLen, DynamicDim }
    305305), type( ty ) {
    306306        assert( type );
     
    311311LogicalExpr::LogicalExpr(
    312312        const CodeLocation & loc, const Expr * a1, const Expr * a2, LogicalFlag ia )
    313 : Expr( loc, new BasicType{ BasicKind::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {}
     313: Expr( loc, new BasicType{ BasicType::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {}
    314314
    315315// --- CommaExpr
  • src/AST/Fwd.hpp

    r4e08a54 rda87eaf  
    133133class OneType;
    134134class GlobalScopeType;
    135 class EnumAttrType;
     135class EnumPosType;
    136136
    137137class Designation;
  • src/AST/Pass.hpp

    r4e08a54 rda87eaf  
    222222        const ast::Type *             visit( const ast::UnionInstType        * ) override final;
    223223        const ast::Type *             visit( const ast::EnumInstType         * ) override final;
    224         const ast::Type *             visit( const ast::EnumAttrType         * ) override final;
     224        const ast::Type *             visit( const ast::EnumPosType          * ) override final;
    225225        const ast::Type *             visit( const ast::TraitInstType        * ) override final;
    226226        const ast::Type *             visit( const ast::TypeInstType         * ) override final;
  • src/AST/Pass.impl.hpp

    r4e08a54 rda87eaf  
    477477                                CodeLocation{}, "__func__",
    478478                                new ast::ArrayType{
    479                                         new ast::BasicType{ ast::BasicKind::Char, ast::CV::Const },
     479                                        new ast::BasicType{ ast::BasicType::Char, ast::CV::Const },
    480480                                        nullptr, VariableLen, DynamicDim
    481481                                },
     
    19401940
    19411941//--------------------------------------------------------------------------
    1942 // EnumAttrType
    1943 template< typename core_t >
    1944 const ast::Type * ast::Pass< core_t >::visit( const ast::EnumAttrType * node ) {
    1945         VISIT_START( node );
     1942// EnumPosType
     1943template< typename core_t >
     1944const ast::Type * ast::Pass< core_t >::visit( const ast::EnumPosType * node ) {
     1945        VISIT_START( node );
     1946
    19461947        VISIT_END( Type, node );
    19471948}
  • src/AST/Print.cpp

    r4e08a54 rda87eaf  
    15761576        }
    15771577
    1578         virtual const ast::Type * visit( const ast::EnumAttrType * node ) override final {
    1579                 preprint( node );
    1580                 os << "enum attr ";
    1581         if ( node->attr == ast::EnumAttribute::Label ) {
    1582             os << "Label ";
    1583         } else if ( node->attr == ast::EnumAttribute::Value ) {
    1584             os << "Value ";
    1585         } else {
    1586             os << "Posn ";
    1587         }
     1578        virtual const ast::Type * visit( const ast::EnumPosType * node ) override final {
     1579                preprint( node );
     1580                os << "enum pos with ";
    15881581                (*(node->instance)).accept( *this );
    15891582                return node;
  • src/AST/Type.hpp

    r4e08a54 rda87eaf  
    2222#include <vector>
    2323
    24 #include "BasicKind.hpp"     // for BasicKind
    2524#include "CVQualifiers.hpp"
    2625#include "Decl.hpp"          // for AggregateDecl subclasses
     
    115114class BasicType final : public Type {
    116115public:
    117         BasicKind kind;
     116        // GENERATED START, DO NOT EDIT
     117        // GENERATED BY BasicTypes-gen.cc
     118        enum Kind {
     119                Bool,
     120                Char,
     121                SignedChar,
     122                UnsignedChar,
     123                ShortSignedInt,
     124                ShortUnsignedInt,
     125                SignedInt,
     126                UnsignedInt,
     127                LongSignedInt,
     128                LongUnsignedInt,
     129                LongLongSignedInt,
     130                LongLongUnsignedInt,
     131                SignedInt128,
     132                UnsignedInt128,
     133                uFloat16,
     134                uFloat16Complex,
     135                uFloat32,
     136                uFloat32Complex,
     137                Float,
     138                FloatComplex,
     139                uFloat32x,
     140                uFloat32xComplex,
     141                uFloat64,
     142                uFloat64Complex,
     143                Double,
     144                DoubleComplex,
     145                uFloat64x,
     146                uFloat64xComplex,
     147                uuFloat80,
     148                uFloat128,
     149                uFloat128Complex,
     150                uuFloat128,
     151                LongDouble,
     152                LongDoubleComplex,
     153                uFloat128x,
     154                uFloat128xComplex,
     155                NUMBER_OF_BASIC_TYPES
     156        } kind;
     157        // GENERATED END
     158
     159        /// xxx -- MAX_INTEGER_TYPE should probably be in BasicTypes-gen.cc, rather than hardcoded here
     160        enum { MAX_INTEGER_TYPE = UnsignedInt128 };
    118161
    119162        /// string names of basic types; generated to match with Kind
    120163        static const char *typeNames[];
    121164
    122         BasicType( BasicKind k, CV::Qualifiers q = {}, std::vector<ptr<Attribute>> && as = {} )
     165        BasicType( Kind k, CV::Qualifiers q = {}, std::vector<ptr<Attribute>> && as = {} )
    123166        : Type(q, std::move(as)), kind(k) {}
    124167
    125168        /// Check if this type represents an integer type
    126         bool isInteger() const { return kind <= MAX_INTEGER_TYPE; }
     169        bool isInteger() const { return (unsigned)kind <= (unsigned)MAX_INTEGER_TYPE; }
    127170
    128171        const Type * accept( Visitor & v ) const override { return v.visit( this ); }
     
    319362using EnumInstType = SueInstType<EnumDecl>;
    320363
    321 class EnumAttrType final : public Type {
     364class EnumPosType final : public Type {
    322365public:
    323366        readonly<EnumInstType> instance;
    324     EnumAttribute attr;
    325         const Type * accept( Visitor & v ) const override { return v.visit( this ); }
    326         EnumAttrType( const EnumInstType * instance, EnumAttribute attr = EnumAttribute::Posn )
    327                 : instance(instance), attr(attr) {}
     367        const Type * accept( Visitor & v ) const override { return v.visit( this ); }
     368        EnumPosType( const EnumInstType * instance ): instance(instance) {}
    328369       
    329     bool match( const ast::EnumAttrType * other) const {
    330         return instance->base->name == other->instance->base->name && attr == other->attr;
    331     }
    332 private:
    333         EnumAttrType * clone() const override { return new EnumAttrType{ *this }; }
     370private:
     371        EnumPosType * clone() const override { return new EnumPosType{ *this }; }
    334372        MUTATE_FRIEND
    335373};
     
    387425        TypeInstType( const TypeInstType & o ) = default;
    388426
    389         explicit TypeInstType( const TypeEnvKey & key );
     427        TypeInstType( const TypeEnvKey & key );
    390428
    391429        /// sets `base`, updating `kind` correctly
  • src/AST/Visitor.hpp

    r4e08a54 rda87eaf  
    119119    virtual const ast::Type *             visit( const ast::OneType              * ) = 0;
    120120    virtual const ast::Type *             visit( const ast::GlobalScopeType      * ) = 0;
    121     virtual const ast::Type *             visit( const ast::EnumAttrType         * ) = 0;
     121    virtual const ast::Type *             visit( const ast::EnumPosType          * ) = 0;
    122122    virtual const ast::Designation *      visit( const ast::Designation          * ) = 0;
    123123    virtual const ast::Init *             visit( const ast::SingleInit           * ) = 0;
  • src/AST/module.mk

    r4e08a54 rda87eaf  
    1818        AST/Attribute.cpp \
    1919        AST/Attribute.hpp \
    20         AST/BasicKind.hpp \
    2120        AST/Bitfield.hpp \
    2221        AST/Chain.hpp \
  • src/BasicTypes-gen.cc

    r4e08a54 rda87eaf  
    249249                } // for
    250250        } // for
    251         int lastInteger = NUMBER_OF_BASIC_TYPES;
    252251
    253252        for ( int r = 0; r < NUMBER_OF_BASIC_TYPES; r += 1 ) { // perform breath-first traversal to generate cost graph
     
    260259                } // for
    261260        } // for
    262 
    263         // Find the last integer type.
    264         // Assumes at least 1, and all come before the floating types.
    265         for ( int i = 1 ; i < NUMBER_OF_BASIC_TYPES ; i += 1 ) {
    266                 if ( Floating == graph[i].sign ) {
    267                         lastInteger = (i - 1);
    268                         break;
    269                 }
    270         }
    271261
    272262        #define STARTMK "// GENERATED START, DO NOT EDIT"
     
    282272        size_t start, end;
    283273
    284         #define TypeH_AST TOP_SRCDIR "src/AST/BasicKind.hpp"
     274        #define TypeH_AST TOP_SRCDIR "src/AST/Type.hpp"
    285275        resetInput( file, TypeH_AST, buffer, code, str );
    286276
     
    289279        code << str.substr( 0, start );
    290280
    291         code << BYMK << endl;
    292         code << "enum BasicKind {" << endl;
     281        code << "\t" << BYMK << endl;
     282        code << "\tenum Kind {" << endl;
    293283        for ( int r = 0; r < NUMBER_OF_BASIC_TYPES; r += 1 ) {
    294                 code << "\t" << graph[r].name << "," << endl;
    295         } // for
    296         code << "\tNUMBER_OF_BASIC_TYPES," << endl;
    297         code << "\tMAX_INTEGER_TYPE = " << graph[lastInteger].name << "," << endl;
    298         code << "};" << endl;
     284                code << "\t\t" << graph[r].name << "," << endl;
     285        } // for
     286        code << "\t\tNUMBER_OF_BASIC_TYPES" << endl;
     287        code << "\t} kind;" << endl;
     288        code << "\t";                                                                           // indentation for end marker
    299289
    300290        if ( (start = str.find( ENDMK, start + 1 )) == string::npos ) Abort( "end", TypeH_AST );
     
    357347
    358348        code << "\t" << BYMK << endl;
    359         code << "\tstatic const int costMatrix[ast::BasicKind::NUMBER_OF_BASIC_TYPES][ast::BasicKind::NUMBER_OF_BASIC_TYPES] = { // path length from root to node" << endl
     349        code << "\tstatic const int costMatrix[ast::BasicType::NUMBER_OF_BASIC_TYPES][ast::BasicType::NUMBER_OF_BASIC_TYPES] = { // path length from root to node" << endl
    360350                 << "\t\t/*           ";
    361351        for ( int r = 0; r < NUMBER_OF_BASIC_TYPES; r += 1 ) { // titles
     
    382372
    383373        code << "\t" << BYMK << endl;
    384         code << "\tstatic const int signMatrix[ast::BasicKind::NUMBER_OF_BASIC_TYPES][ast::BasicKind::NUMBER_OF_BASIC_TYPES] = { // number of sign changes in safe conversion" << endl
     374        code << "\tstatic const int signMatrix[ast::BasicType::NUMBER_OF_BASIC_TYPES][ast::BasicType::NUMBER_OF_BASIC_TYPES] = { // number of sign changes in safe conversion" << endl
    385375                 << "\t\t/*           ";
    386376        for ( int r = 0; r < NUMBER_OF_BASIC_TYPES; r += 1 ) { // titles
     
    414404        enum { PER_ROW = 6 };
    415405        code << "\t" << BYMK << endl;
    416         code << "\t#define BT ast::BasicKind::" << endl;
     406        code << "\t#define BT ast::BasicType::" << endl;
    417407        code << "\tstatic const BT Kind commonTypes[BT NUMBER_OF_BASIC_TYPES][BT NUMBER_OF_BASIC_TYPES] = { // nearest common ancestor" << endl
    418408             << "\t\t/*\t\t ";
     
    470460                "//   - \"Ds\" char16_t\n";
    471461
    472         code << "const std::string basicTypes[ast::BasicKind::NUMBER_OF_BASIC_TYPES] = {" << endl;
     462        code << "const std::string basicTypes[ast::BasicType::NUMBER_OF_BASIC_TYPES] = {" << endl;
    473463        for ( int r = 0; r < NUMBER_OF_BASIC_TYPES; r += 1 ) {
    474464                code << "\t\"" << graph[r].mangled << "\"," << setw(9 - strlen(graph[r].mangled)) << ' ' << "// " << graph[r].type << endl;
  • src/CodeGen/FixMain.cc

    r4e08a54 rda87eaf  
    5252ast::ObjectDecl * makeIntObj(){
    5353        return new ast::ObjectDecl( CodeLocation(), "",
    54                 new ast::BasicType( ast::BasicKind::SignedInt ) );
     54                new ast::BasicType( ast::BasicType::SignedInt ) );
    5555}
    5656
     
    5959                new ast::PointerType(
    6060                        new ast::PointerType(
    61                                 new ast::BasicType( ast::BasicKind::Char ) ) ) );
     61                                new ast::BasicType( ast::BasicType::Char ) ) ) );
    6262}
    6363
  • src/CodeGen/GenType.cc

    r4e08a54 rda87eaf  
    4646        void postvisit( ast::UnionInstType const * type );
    4747        void postvisit( ast::EnumInstType const * type );
    48         void postvisit( ast::EnumAttrType const * type );
     48        void postvisit( ast::EnumPosType const * type );
    4949        void postvisit( ast::TypeInstType const * type );
    5050        void postvisit( ast::TupleType const * type );
     
    8787
    8888void GenType::postvisit( ast::BasicType const * type ) {
    89         ast::BasicKind kind = type->kind;
    90         assert( 0 <= kind && kind < ast::BasicKind::NUMBER_OF_BASIC_TYPES );
     89        ast::BasicType::Kind kind = type->kind;
     90        assert( 0 <= kind && kind < ast::BasicType::NUMBER_OF_BASIC_TYPES );
    9191        result = std::string( ast::BasicType::typeNames[kind] ) + " " + result;
    9292        handleQualifiers( type );
     
    240240}
    241241
    242 void GenType::postvisit( ast::EnumAttrType const * type ) {
     242void GenType::postvisit( ast::EnumPosType const * type ) {
    243243        postvisit( type->instance );
    244244}
  • src/Common/CodeLocationTools.cpp

    r4e08a54 rda87eaf  
    188188    macro(UnionInstType, Type) \
    189189    macro(EnumInstType, Type) \
    190     macro(EnumAttrType, Type) \
     190    macro(EnumPosType, Type) \
    191191    macro(TraitInstType, Type) \
    192192    macro(TypeInstType, Type) \
  • src/Common/ResolvProtoDump.cpp

    r4e08a54 rda87eaf  
    229229        void previsit( const ast::EnumInstType * ) {
    230230                // TODO: Add the meaningful text representation of typed enum
    231                 ss << (int)ast::BasicKind::SignedInt;
     231                ss << (int)ast::BasicType::SignedInt;
    232232        }
    233233
     
    255255        // TODO: Support 0 and 1 with their type names and conversions.
    256256        void previsit( const ast::ZeroType * ) {
    257                 ss << (int)ast::BasicKind::SignedInt;
     257                ss << (int)ast::BasicType::SignedInt;
    258258        }
    259259
    260260        void previsit( const ast::OneType * ) {
    261                 ss << (int)ast::BasicKind::SignedInt;
     261                ss << (int)ast::BasicType::SignedInt;
    262262        }
    263263
     
    366366        // TODO: Extra expression to resolve argument.
    367367        void previsit( const ast::SizeofExpr * ) {
    368                 ss << (int)ast::BasicKind::LongUnsignedInt;
     368                ss << (int)ast::BasicType::LongUnsignedInt;
    369369                visit_children = false;
    370370        }
    371371        void previsit( const ast::AlignofExpr * ) {
    372                 ss << (int)ast::BasicKind::LongUnsignedInt;
     372                ss << (int)ast::BasicType::LongUnsignedInt;
    373373                visit_children = false;
    374374        }
    375375        void previsit( const ast::UntypedOffsetofExpr * ) {
    376                 ss << (int)ast::BasicKind::LongUnsignedInt;
     376                ss << (int)ast::BasicType::LongUnsignedInt;
    377377                visit_children = false;
    378378        }
     
    753753                // &? Address of operator.
    754754                out << "#$ptr<T> $addr T" << std::endl;
    755                 const int intId = (int)ast::BasicKind::SignedInt;
     755                const int intId = (int)ast::BasicType::SignedInt;
    756756                // ?&&? ?||? ?: Logical operators.
    757757                out << intId << " $and " << intId << ' ' << intId << std::endl;
  • src/Concurrency/Corun.cpp

    r4e08a54 rda87eaf  
    130130                new ObjectDecl( loc,
    131131                    numProcsName,
    132                     new BasicType( BasicKind::UnsignedInt ),
     132                    new BasicType( BasicType::Kind::UnsignedInt ),
    133133                    new SingleInit( loc,
    134134                        new UntypedExpr( loc,
     
    146146                new ObjectDecl( loc,
    147147                    currProcsName,
    148                     new BasicType( BasicKind::UnsignedInt ),
     148                    new BasicType( BasicType::Kind::UnsignedInt ),
    149149                    new SingleInit( loc, ConstantExpr::from_int( loc, 0 ) )
    150150                )
  • src/Concurrency/Waitfor.cpp

    r4e08a54 rda87eaf  
    244244        ast::ObjectDecl * flag = new ast::ObjectDecl( location,
    245245                namer_flg.newName(),
    246                 new ast::BasicType( ast::BasicKind::Bool ),
     246                new ast::BasicType( ast::BasicType::Bool ),
    247247                new ast::SingleInit( location,
    248248                        ast::ConstantExpr::from_ulong( location, 0 )
     
    349349        ast::ObjectDecl * timeout = new ast::ObjectDecl( topLocation,
    350350                namer_tim.newName(),
    351                 new ast::BasicType( ast::BasicKind::LongLongUnsignedInt ),
     351                new ast::BasicType( ast::BasicType::LongLongUnsignedInt ),
    352352                new ast::SingleInit( topLocation,
    353353                        ast::ConstantExpr::from_int( topLocation, -1 )
     
    397397        ast::ObjectDecl * index = new ast::ObjectDecl( location,
    398398                namer_idx.newName(),
    399                 new ast::BasicType( ast::BasicKind::ShortSignedInt ),
     399                new ast::BasicType( ast::BasicType::ShortSignedInt ),
    400400                new ast::SingleInit( location,
    401401                        ast::ConstantExpr::from_int( location, -1 )
  • src/Concurrency/Waituntil.cpp

    r4e08a54 rda87eaf  
    498498            rightExpr = genPredExpr( loc, currNode->right, idx, genLeaf );
    499499            return new LogicalExpr( loc,
    500                 new CastExpr( loc, leftExpr, new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast ),
    501                 new CastExpr( loc, rightExpr, new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast ),
     500                new CastExpr( loc, leftExpr, new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast ),
     501                new CastExpr( loc, rightExpr, new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast ),
    502502                LogicalFlag::AndExpr
    503503            );
     
    507507            rightExpr = genPredExpr( loc, currNode->right, idx, genLeaf );
    508508            return new LogicalExpr( loc,
    509                 new CastExpr( loc, leftExpr, new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast ),
    510                 new CastExpr( loc, rightExpr, new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast ),
     509                new CastExpr( loc, leftExpr, new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast ),
     510                new CastExpr( loc, rightExpr, new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast ),
    511511                LogicalFlag::OrExpr );
    512512            break;
     
    556556            new ObjectDecl( loc,
    557557                "clause_statuses",
    558                 new PointerType( new BasicType( BasicKind::LongUnsignedInt ) )
     558                new PointerType( new BasicType( BasicType::Kind::LongUnsignedInt ) )
    559559            )
    560560        },
     
    562562            new ObjectDecl( loc,
    563563                "sat_ret",
    564                 new BasicType( BasicKind::Bool )
     564                new BasicType( BasicType::Kind::Bool )
    565565            )
    566566        },
     
    766766                new ObjectDecl( loc,
    767767                    idxName,
    768                     new BasicType( BasicKind::SignedInt ),
     768                    new BasicType( BasicType::Kind::SignedInt ),
    769769                    new SingleInit( loc, ConstantExpr::from_int( loc, 0 ) )
    770770                )
     
    893893                    new ObjectDecl( cLoc,
    894894                        currClause->whenName,
    895                         new BasicType( BasicKind::Bool ),
     895                        new BasicType( BasicType::Kind::Bool ),
    896896                        new SingleInit( cLoc, ast::deepCopy( stmt->clauses.at(i)->when_cond ) )
    897897                    )
     
    915915                new ObjectDecl( stmt->else_cond->location,
    916916                    elseWhenName,
    917                     new BasicType( BasicKind::Bool ),
     917                    new BasicType( BasicType::Kind::Bool ),
    918918                    new SingleInit( stmt->else_cond->location, ast::deepCopy( stmt->else_cond ) )
    919919                )
     
    945945                    new CastExpr( cLoc,
    946946                        new AddressExpr( cLoc, new NameExpr( cLoc, data.at(i)->nodeName ) ),
    947                         new BasicType( BasicKind::LongUnsignedInt ), GeneratedFlag::ExplicitCast
     947                        new BasicType( BasicType::Kind::LongUnsignedInt ), GeneratedFlag::ExplicitCast
    948948                    )
    949949                }
     
    986986                    new CastExpr( cLoc,
    987987                        new NameExpr( cLoc, elseWhenName ),
    988                         new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     988                        new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    989989                    ),
    990990                    new CastExpr( cLoc,
    991991                        raceFnCall,
    992                         new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     992                        new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    993993                    ),
    994994                    LogicalFlag::AndExpr
     
    10161016            new CastExpr( cLoc,
    10171017                new NameExpr( cLoc, data.at(idx)->whenName ),
    1018                 new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1018                new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    10191019            ),
    10201020            new CastExpr( cLoc,
    10211021                baseCond,
    1022                 new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1022                new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    10231023            ),
    10241024            LogicalFlag::AndExpr
     
    10341034                        new NameExpr( cLoc, data.at(idx)->nodeName ),
    10351035                        new AddressExpr( cLoc, new NameExpr( cLoc, data.at(idx)->statusName ) ),
    1036                         ConstantExpr::null( cLoc, new PointerType( new BasicType( BasicKind::SignedInt ) ) )
     1036                        ConstantExpr::null( cLoc, new PointerType( new BasicType( BasicType::Kind::SignedInt ) ) )
    10371037                    }
    10381038                )
     
    10961096        new ObjectDecl( loc,
    10971097            statusName,
    1098             new BasicType( BasicKind::LongUnsignedInt ),
     1098            new BasicType( BasicType::Kind::LongUnsignedInt ),
    10991099            new SingleInit( loc, ConstantExpr::from_int( loc, 0 ) )
    11001100        )
     
    11141114            new NameExpr( cLoc, "?!=?" ),
    11151115            {
    1116                 ConstantExpr::null( cLoc, new PointerType( new BasicType( BasicKind::LongUnsignedInt ) ) ),
     1116                ConstantExpr::null( cLoc, new PointerType( new BasicType( BasicType::Kind::LongUnsignedInt ) ) ),
    11171117                new UntypedExpr( cLoc,
    11181118                    new NameExpr( cLoc, "__get_clause_status" ),
     
    11281128                new CastExpr( cLoc,
    11291129                    new NameExpr( cLoc, clauseData.at(i)->whenName ),
    1130                     new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1130                    new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    11311131                ),
    11321132                new CastExpr( cLoc,
    11331133                    statusPtrCheck,
    1134                     new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1134                    new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    11351135                ),
    11361136                LogicalFlag::AndExpr
     
    11621162                new CastExpr( loc,
    11631163                    new NameExpr( loc, clauseData.at( whenIndices.at(i) )->whenName ),
    1164                     new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1164                    new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    11651165                ),
    11661166                new CastExpr( loc,
    11671167                    lastExpr,
    1168                     new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1168                    new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    11691169                ),
    11701170                LogicalFlag::OrExpr
     
    12201220        new ObjectDecl( loc,
    12211221            pCountName,
    1222             new BasicType( BasicKind::SignedInt ),
     1222            new BasicType( BasicType::Kind::SignedInt ),
    12231223            new SingleInit( loc, ConstantExpr::from_int( loc, 0 ) )
    12241224        )
     
    12291229        new ObjectDecl( loc,
    12301230            statusArrName,
    1231             new ArrayType( new BasicType( BasicKind::LongUnsignedInt ), ConstantExpr::from_int( loc, numClauses ), LengthFlag::FixedLen, DimensionFlag::DynamicDim ),
     1231            new ArrayType( new BasicType( BasicType::Kind::LongUnsignedInt ), ConstantExpr::from_int( loc, numClauses ), LengthFlag::FixedLen, DimensionFlag::DynamicDim ),
    12321232            new ListInit( loc,
    12331233                {
     
    13311331            new CastExpr( cLoc,
    13321332                statusExpr,
    1333                 new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1333                new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    13341334            ),
    13351335            new CastExpr( cLoc,
    13361336                genSelectTraitCall( stmt->clauses.at(i), clauseData.at(i), "unregister_select" ),
    1337                 new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1337                new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    13381338            ),
    13391339            LogicalFlag::AndExpr
     
    13461346                new CastExpr( cLoc,
    13471347                    new NameExpr( cLoc, clauseData.at(i)->whenName ),
    1348                     new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1348                    new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    13491349                ),
    13501350                new CastExpr( cLoc,
    13511351                    statusExpr,
    1352                     new BasicType( BasicKind::Bool ), GeneratedFlag::ExplicitCast
     1352                    new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast
    13531353                ),
    13541354                LogicalFlag::AndExpr
  • src/ControlStruct/ExceptDecl.cpp

    r4e08a54 rda87eaf  
    9999                createExceptionInstType( exceptionName, params ) ) );
    100100        type->returns.push_back( new ast::PointerType(
    101                 new ast::BasicType( ast::BasicKind::Char, ast::CV::Const ) ) );
     101                new ast::BasicType( ast::BasicType::Char, ast::CV::Const ) ) );
    102102        return type;
    103103}
     
    344344                                "",
    345345                                new ast::PointerType(
    346                                         new ast::BasicType( ast::BasicKind::Char, ast::CV::Const ) )
     346                                        new ast::BasicType( ast::BasicType::Char, ast::CV::Const ) )
    347347                        ),
    348348                },
  • src/ControlStruct/ExceptTranslate.cpp

    r4e08a54 rda87eaf  
    182182                location,
    183183                "__handler_index",
    184                 new ast::BasicType( ast::BasicKind::SignedInt )
     184                new ast::BasicType( ast::BasicType::SignedInt )
    185185                );
    186186}
     
    201201                location,
    202202                "__ret_bool",
    203                 new ast::BasicType( ast::BasicKind::Bool ),
     203                new ast::BasicType( ast::BasicType::Bool ),
    204204                nullptr, //init
    205205                ast::Storage::Classes{},
     
    231231                location,
    232232                "__handler_index",
    233                 new ast::BasicType( ast::BasicKind::SignedInt ),
     233                new ast::BasicType(ast::BasicType::SignedInt),
    234234                nullptr,
    235235                ast::Storage::Classes{},
  • src/GenPoly/Box.cpp

    r4e08a54 rda87eaf  
    4343/// The layout type is used to represent sizes, alignments and offsets.
    4444ast::BasicType * makeLayoutType() {
    45         return new ast::BasicType( ast::BasicKind::LongUnsignedInt );
     45        return new ast::BasicType( ast::BasicType::LongUnsignedInt );
    4646}
    4747
    4848/// Fixed version of layout type (just adding a 'C' in C++ style).
    4949ast::BasicType * makeLayoutCType() {
    50         return new ast::BasicType( ast::BasicKind::LongUnsignedInt,
     50        return new ast::BasicType( ast::BasicType::LongUnsignedInt,
    5151                ast::CV::Qualifiers( ast::CV::Const ) );
    5252}
     
    16171617ast::Type * polyToMonoType( CodeLocation const & location,
    16181618                ast::Type const * declType ) {
    1619         auto charType = new ast::BasicType( ast::BasicKind::Char );
     1619        auto charType = new ast::BasicType( ast::BasicType::Char );
    16201620        auto size = new ast::NameExpr( location,
    16211621                sizeofName( Mangle::mangleType( declType ) ) );
  • src/GenPoly/Lvalue.cpp

    r4e08a54 rda87eaf  
    133133                        return func->linkage == ast::Linkage::Intrinsic
    134134                                && lvalueFunctions.count( func->name );
     135                }
     136        }
     137        return false;
     138}
     139
     140bool isGeneratedInstrinct( ast::Expr const * expr ) {
     141        if ( auto app = dynamic_cast<ast::ApplicationExpr const *>( expr ) ) {
     142                if ( app->args.size() == 2 && ast::getFunction( app )->name == "?[?]" ) {
     143                        auto param_1 = dynamic_cast<ast::VariableExpr const *>(app->args.front().get());
     144                        if ( param_1 ) {
     145                                auto param_1_as_obj = param_1->var.as<ast::ObjectDecl>();
     146                                return ( param_1_as_obj->name.find( "values_") != std::string::npos
     147                                        ||  param_1_as_obj->name.find( "labels_" ) != std::string::npos );
     148                        }
    135149                }
    136150        }
     
    162176                ast::ApplicationExpr const * expr ) {
    163177
    164         if ( skip == SkipInProgress || !isIntrinsicReference( expr ) ) {
     178        if ( skip == SkipInProgress || !isIntrinsicReference( expr ) || isGeneratedInstrinct( expr ) ) {
    165179                return expr;
    166180        }
  • src/InitTweak/FixInit.cpp

    r4e08a54 rda87eaf  
    847847
    848848                        // static bool __objName_uninitialized = true
    849                         auto boolType = new ast::BasicType( ast::BasicKind::Bool );
     849                        auto boolType = new ast::BasicType( ast::BasicType::Kind::Bool );
    850850                        auto boolInitExpr = new ast::SingleInit(loc, ast::ConstantExpr::from_int(loc, 1 ) );
    851851                        auto isUninitializedVar = new ast::ObjectDecl(loc, objDecl->mangleName + "_uninitialized", boolType, boolInitExpr, ast::Storage::Static, ast::Linkage::Cforall);
  • src/Makefile.am

    r4e08a54 rda87eaf  
    5353include Virtual/module.mk
    5454
    55 $(addprefix $(srcdir)/, ResolvExpr/ConversionCost.cc ResolvExpr/CommonType.cc SymTab/ManglerCommon.cc) : $(srcdir)/AST/BasicKind.hpp
     55$(addprefix $(srcdir)/, ResolvExpr/ConversionCost.cc ResolvExpr/CommonType.cc SymTab/ManglerCommon.cc) : $(srcdir)/AST/Type.hpp
    5656
    57 $(srcdir)/AST/BasicKind.hpp : BasicTypes-gen.cc
     57$(srcdir)/AST/Type.hpp : BasicTypes-gen.cc
    5858        ${AM_V_GEN}${CXXCOMPILE} $< -o BasicTypes-gen -Wall -Wextra -Werror=return-type
    5959        @./BasicTypes-gen
  • src/Parser/ExpressionNode.cc

    r4e08a54 rda87eaf  
    2323#include <string>                  // for string, operator+, operator==
    2424
    25 #include "AST/BasicKind.hpp"       // for BasicKind
    2625#include "AST/Expr.hpp"            // for NameExpr
    27 #include "AST/Type.hpp"            // for Type, LengthFlag, DimentionFlag
     26#include "AST/Type.hpp"            // for BaseType, SueInstType
    2827#include "Common/SemanticError.h"  // for SemanticError
    2928#include "Common/utility.h"        // for maybeMoveBuild, maybeBuild, CodeLo...
     
    127126ast::Expr * build_constantInteger(
    128127                const CodeLocation & location, string & str ) {
    129         static const ast::BasicKind kind[2][6] = {
     128        static const ast::BasicType::Kind kind[2][6] = {
    130129                // short (h) must be before char (hh) because shorter type has the longer suffix
    131                 { ast::BasicKind::ShortSignedInt, ast::BasicKind::SignedChar, ast::BasicKind::SignedInt, ast::BasicKind::LongSignedInt, ast::BasicKind::LongLongSignedInt, /* BasicKind::SignedInt128 */ ast::BasicKind::LongLongSignedInt, },
    132                 { ast::BasicKind::ShortUnsignedInt, ast::BasicKind::UnsignedChar, ast::BasicKind::UnsignedInt, ast::BasicKind::LongUnsignedInt, ast::BasicKind::LongLongUnsignedInt, /* BasicKind::UnsignedInt128 */ ast::BasicKind::LongLongUnsignedInt, },
     130                { ast::BasicType::ShortSignedInt, ast::BasicType::SignedChar, ast::BasicType::SignedInt, ast::BasicType::LongSignedInt, ast::BasicType::LongLongSignedInt, /* BasicType::SignedInt128 */ ast::BasicType::LongLongSignedInt, },
     131                { ast::BasicType::ShortUnsignedInt, ast::BasicType::UnsignedChar, ast::BasicType::UnsignedInt, ast::BasicType::LongUnsignedInt, ast::BasicType::LongLongUnsignedInt, /* BasicType::UnsignedInt128 */ ast::BasicType::LongLongUnsignedInt, },
    133132        };
    134133
     
    314313                if ( ltype == 6 ) {                                                             // int128, (int128)constant
    315314                        ret2 = new ast::ConstantExpr( location,
    316                                 new ast::BasicType( ast::BasicKind::LongLongSignedInt ),
     315                                new ast::BasicType( ast::BasicType::LongLongSignedInt ),
    317316                                str2,
    318317                                v2 );
     
    380379ast::Expr * build_constantFloat(
    381380                const CodeLocation & location, string & str ) {
    382         static const ast::BasicKind kind[2][12] = {
    383                 { ast::BasicKind::Float, ast::BasicKind::Double, ast::BasicKind::LongDouble, ast::BasicKind::uuFloat80, ast::BasicKind::uuFloat128, ast::BasicKind::uFloat16, ast::BasicKind::uFloat32, ast::BasicKind::uFloat32x, ast::BasicKind::uFloat64, ast::BasicKind::uFloat64x, ast::BasicKind::uFloat128, ast::BasicKind::uFloat128x },
    384                 { ast::BasicKind::FloatComplex, ast::BasicKind::DoubleComplex, ast::BasicKind::LongDoubleComplex, ast::BasicKind::NUMBER_OF_BASIC_TYPES, ast::BasicKind::NUMBER_OF_BASIC_TYPES, ast::BasicKind::uFloat16Complex, ast::BasicKind::uFloat32Complex, ast::BasicKind::uFloat32xComplex, ast::BasicKind::uFloat64Complex, ast::BasicKind::uFloat64xComplex, ast::BasicKind::uFloat128Complex, ast::BasicKind::uFloat128xComplex },
     381        static const ast::BasicType::Kind kind[2][12] = {
     382                { ast::BasicType::Float, ast::BasicType::Double, ast::BasicType::LongDouble, ast::BasicType::uuFloat80, ast::BasicType::uuFloat128, ast::BasicType::uFloat16, ast::BasicType::uFloat32, ast::BasicType::uFloat32x, ast::BasicType::uFloat64, ast::BasicType::uFloat64x, ast::BasicType::uFloat128, ast::BasicType::uFloat128x },
     383                { ast::BasicType::FloatComplex, ast::BasicType::DoubleComplex, ast::BasicType::LongDoubleComplex, ast::BasicType::NUMBER_OF_BASIC_TYPES, ast::BasicType::NUMBER_OF_BASIC_TYPES, ast::BasicType::uFloat16Complex, ast::BasicType::uFloat32Complex, ast::BasicType::uFloat32xComplex, ast::BasicType::uFloat64Complex, ast::BasicType::uFloat64xComplex, ast::BasicType::uFloat128Complex, ast::BasicType::uFloat128xComplex },
    385384        };
    386385
     
    448447
    449448        ast::Expr * ret = new ast::ConstantExpr( location,
    450                 new ast::BasicType( ast::BasicKind::Char ),
     449                new ast::BasicType( ast::BasicType::Char ),
    451450                str,
    452451                (unsigned long long int)(unsigned char)str[1] );
     
    483482        Default:                                                                                        // char default string type
    484483        default:
    485                 strtype = new ast::BasicType( ast::BasicKind::Char );
     484                strtype = new ast::BasicType( ast::BasicType::Char );
    486485        } // switch
    487486        ast::ArrayType * at = new ast::ArrayType(
     
    665664                member->name
    666665        );
    667         ret->result = new ast::BasicType( ast::BasicKind::LongUnsignedInt );
     666        ret->result = new ast::BasicType( ast::BasicType::LongUnsignedInt );
    668667        delete member;
    669668        return ret;
  • src/Parser/TypeData.cc

    r4e08a54 rda87eaf  
    1919#include <ostream>                 // for operator<<, ostream, basic_ostream
    2020
     21#include "AST/Decl.hpp"            // for AggregateDecl, ObjectDecl, TypeDe...
    2122#include "AST/Attribute.hpp"       // for Attribute
    22 #include "AST/Decl.hpp"            // for AggregateDecl, ObjectDecl, TypeDe...
    2323#include "AST/Init.hpp"            // for SingleInit, ListInit
    2424#include "AST/Print.hpp"           // for print
    25 #include "AST/Type.hpp"            // for Type
    2625#include "Common/SemanticError.h"  // for SemanticError
    2726#include "Common/utility.h"        // for splice, spliceBegin
     
    10111010                // fill in implicit int
    10121011                return new ast::BasicType(
    1013                         ast::BasicKind::SignedInt,
     1012                        ast::BasicType::SignedInt,
    10141013                        buildQualifiers( td )
    10151014                );
     
    10961095
    10971096ast::Type * buildBasicType( const TypeData * td ) {
    1098         ast::BasicKind ret;
     1097        ast::BasicType::Kind ret;
    10991098
    11001099        switch ( td->basictype ) {
     
    11171116                } // if
    11181117
    1119                 ret = ast::BasicKind::Bool;
     1118                ret = ast::BasicType::Bool;
    11201119                break;
    11211120
     
    11241123                // character types. The implementation shall define char to have the same range, representation, and behavior as
    11251124                // either signed char or unsigned char.
    1126                 static ast::BasicKind chartype[] = { ast::BasicKind::SignedChar, ast::BasicKind::UnsignedChar, ast::BasicKind::Char };
     1125                static ast::BasicType::Kind chartype[] = { ast::BasicType::SignedChar, ast::BasicType::UnsignedChar, ast::BasicType::Char };
    11271126
    11281127                if ( td->length != TypeData::NoLength ) {
     
    11341133
    11351134        case TypeData::Int:
    1136                 static ast::BasicKind inttype[2][4] = {
    1137                         { ast::BasicKind::ShortSignedInt, ast::BasicKind::LongSignedInt, ast::BasicKind::LongLongSignedInt, ast::BasicKind::SignedInt },
    1138                         { ast::BasicKind::ShortUnsignedInt, ast::BasicKind::LongUnsignedInt, ast::BasicKind::LongLongUnsignedInt, ast::BasicKind::UnsignedInt },
     1135                static ast::BasicType::Kind inttype[2][4] = {
     1136                        { ast::BasicType::ShortSignedInt, ast::BasicType::LongSignedInt, ast::BasicType::LongLongSignedInt, ast::BasicType::SignedInt },
     1137                        { ast::BasicType::ShortUnsignedInt, ast::BasicType::LongUnsignedInt, ast::BasicType::LongLongUnsignedInt, ast::BasicType::UnsignedInt },
    11391138                };
    11401139
     
    11471146
    11481147        case TypeData::Int128:
    1149                 ret = td->signedness == TypeData::Unsigned ? ast::BasicKind::UnsignedInt128 : ast::BasicKind::SignedInt128;
     1148                ret = td->signedness == TypeData::Unsigned ? ast::BasicType::UnsignedInt128 : ast::BasicType::SignedInt128;
    11501149                if ( td->length != TypeData::NoLength ) {
    11511150                        genTSError( TypeData::lengthNames[ td->length ], td->basictype );
     
    11651164        case TypeData::uFloat128:
    11661165        case TypeData::uFloat128x:
    1167                 static ast::BasicKind floattype[2][12] = {
    1168                         { ast::BasicKind::FloatComplex, ast::BasicKind::DoubleComplex, ast::BasicKind::LongDoubleComplex, (ast::BasicKind)-1, (ast::BasicKind)-1, ast::BasicKind::uFloat16Complex, ast::BasicKind::uFloat32Complex, ast::BasicKind::uFloat32xComplex, ast::BasicKind::uFloat64Complex, ast::BasicKind::uFloat64xComplex, ast::BasicKind::uFloat128Complex, ast::BasicKind::uFloat128xComplex, },
    1169                         { ast::BasicKind::Float, ast::BasicKind::Double, ast::BasicKind::LongDouble, ast::BasicKind::uuFloat80, ast::BasicKind::uuFloat128, ast::BasicKind::uFloat16, ast::BasicKind::uFloat32, ast::BasicKind::uFloat32x, ast::BasicKind::uFloat64, ast::BasicKind::uFloat64x, ast::BasicKind::uFloat128, ast::BasicKind::uFloat128x, },
     1166                static ast::BasicType::Kind floattype[2][12] = {
     1167                        { ast::BasicType::FloatComplex, ast::BasicType::DoubleComplex, ast::BasicType::LongDoubleComplex, (ast::BasicType::Kind)-1, (ast::BasicType::Kind)-1, ast::BasicType::uFloat16Complex, ast::BasicType::uFloat32Complex, ast::BasicType::uFloat32xComplex, ast::BasicType::uFloat64Complex, ast::BasicType::uFloat64xComplex, ast::BasicType::uFloat128Complex, ast::BasicType::uFloat128xComplex, },
     1168                        { ast::BasicType::Float, ast::BasicType::Double, ast::BasicType::LongDouble, ast::BasicType::uuFloat80, ast::BasicType::uuFloat128, ast::BasicType::uFloat16, ast::BasicType::uFloat32, ast::BasicType::uFloat32x, ast::BasicType::uFloat64, ast::BasicType::uFloat64x, ast::BasicType::uFloat128, ast::BasicType::uFloat128x, },
    11701169                };
    11711170
     
    12141213
    12151214static ast::Type * buildDefaultType( const TypeData * td ) {
    1216         return ( td ) ? typebuild( td ) : new ast::BasicType( ast::BasicKind::SignedInt );
     1215        return ( td ) ? typebuild( td ) : new ast::BasicType( ast::BasicType::SignedInt );
    12171216} // buildDefaultType
    12181217
     
    15801579                        td->location,
    15811580                        "",
    1582                         new ast::BasicType( ast::BasicKind::SignedInt ),
     1581                        new ast::BasicType( ast::BasicType::SignedInt ),
    15831582                        (ast::Init *)nullptr,
    15841583                        ast::Storage::Classes(),
     
    16681667        } else {
    16691668                ft->returns.push_back(
    1670                         new ast::BasicType( ast::BasicKind::SignedInt ) );
     1669                        new ast::BasicType( ast::BasicType::SignedInt ) );
    16711670        } // if
    16721671        return ft;
  • src/Parser/TypeData.h

    r4e08a54 rda87eaf  
    2020#include <string>                                   // for string
    2121
    22 #include "AST/CVQualifiers.hpp"                     // for CV
    23 #include "AST/Fwd.hpp"                              // for Type
     22#include "AST/Type.hpp"                             // for Type
    2423#include "DeclarationNode.h"                        // for DeclarationNode
    2524
  • src/Parser/parser.yy

    r4e08a54 rda87eaf  
    5555#include "TypedefTable.h"
    5656#include "TypeData.h"
    57 #include "AST/Type.hpp"                                 // for BasicType, BasicKind
    5857#include "Common/SemanticError.h"                                               // error_str
    5958#include "Common/utility.h"                                                             // for maybeMoveBuild, maybeBuild, CodeLo...
     
    261260        ast::ConstantExpr * constant = dynamic_cast<ast::ConstantExpr *>(type->expr.get());
    262261        if ( constant && (constant->rep == "0" || constant->rep == "1") ) {
    263                 type = new ExpressionNode( new ast::CastExpr( location, maybeMoveBuild(type), new ast::BasicType( ast::BasicKind::SignedInt ) ) );
     262                type = new ExpressionNode( new ast::CastExpr( location, maybeMoveBuild(type), new ast::BasicType( ast::BasicType::SignedInt ) ) );
    264263        } // if
    265264        DeclarationNode * initDecl = distAttr(
  • src/ResolvExpr/CandidateFinder.cpp

    r4e08a54 rda87eaf  
    284284                const CodeLocation & location,
    285285                const ast::Type * paramType, const ast::Init * init, const ExplodedArgs & args,
    286                 std::vector< ArgPack > & results, std::size_t & genStart, const ResolveContext & context,
     286                std::vector< ArgPack > & results, std::size_t & genStart, const ast::SymbolTable & symtab,
    287287                unsigned nTuples = 0
    288288        ) {
     
    294294                                // ^^^ need to handle the case where a tuple has a default argument
    295295                                if ( ! instantiateArgument( location,
    296                                         type, nullptr, args, results, genStart, context, nTuples ) ) return false;
     296                                        type, nullptr, args, results, genStart, symtab, nTuples ) ) return false;
    297297                                nTuples = 0;
    298298                        }
     
    509509
    510510                                // attempt to unify types
    511                                 ast::ptr<ast::Type> common;
    512                                 if ( unify( paramType, argType, env, need, have, open, common ) ) {
     511                                if ( unify( paramType, argType, env, need, have, open ) ) {
    513512                                        // add new result
    514                                         assert( common );
    515                                                 results.emplace_back(
    516                                                         i, expr, std::move( env ), std::move( need ), std::move( have ), std::move( open ),
    517                                                         nextArg + 1, nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
    518                                         //}
     513                                        results.emplace_back(
     514                                                i, expr, std::move( env ), std::move( need ), std::move( have ), std::move( open ),
     515                                                nextArg + 1, nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
    519516                                }
    520517                        }
     
    788785                                        auto obj = funcDecl->params[i].strict_as<ast::ObjectDecl>();
    789786                                        if ( !instantiateArgument( location,
    790                                                 funcType->params[i], obj->init, args, results, genStart, context)) return;
     787                                                funcType->params[i], obj->init, args, results, genStart, symtab)) return;
    791788                                }
    792789                                goto endMatch;
     
    798795                        // no default args for indirect calls
    799796                        if ( !instantiateArgument( location,
    800                                 param, nullptr, args, results, genStart, context ) ) return;
     797                                param, nullptr, args, results, genStart, symtab ) ) return;
    801798                }
    802799
     
    893890                } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) {
    894891                        addAggMembers( unionInst, aggrExpr, *cand, Cost::unsafe, "" );
    895                 } else if ( auto enumInst = aggrExpr->result.as< ast::EnumInstType >() ) {
    896                         if ( enumInst->base->base ) {
    897                                 CandidateFinder finder( context, tenv );
    898                                 auto location = aggrExpr->location;
    899                                 auto callExpr = new ast::UntypedExpr(
    900                                         location, new ast::NameExpr( location, "valueE" ), {aggrExpr}
    901                                 );
    902                                 finder.find( callExpr );
    903                                 CandidateList winners = findMinCost( finder.candidates );
    904                                 if (winners.size() != 1) {
    905                                         SemanticError( callExpr, "Ambiguous expression in valueE..." );
    906                                 }
    907                                 CandidateRef & choice = winners.front();
    908                                 choice->cost.incVar();
    909                                 candidates.emplace_back( std::move(choice) );
    910                         }
    911 
     892                }
     893                else if ( auto enumInst = aggrExpr->result.as< ast::EnumInstType >() ) {
     894                        if (enumInst->base && enumInst->base->base) {
     895            const CodeLocation &location = cand->expr->location;
     896
     897            CandidateFinder funcFinder(context, tenv);
     898            auto nameExpr = new ast::NameExpr(location, "valueE");
     899            ResolveMode mode = {true, false, selfFinder.candidates.empty()};
     900            funcFinder.find( nameExpr, mode );
     901
     902            // make variableExpr itself the candidate for the value Call
     903            ExplodedArgs argExpansions;
     904            argExpansions.emplace_back();
     905            auto &argE = argExpansions.back();
     906
     907            argE.emplace_back(*cand, symtab); // Use the typed name expr as param for value
     908
     909            CandidateList found;
     910            SemanticErrorException errors;
     911
     912            for (CandidateRef &func : funcFinder) {
     913                try {
     914                    const ast::Type *funcResult =
     915                        func->expr->result->stripReferences();
     916                    if (auto pointer = dynamic_cast<const ast::PointerType *>(
     917                            funcResult)) {
     918                        if (auto function =
     919                                pointer->base.as<ast::FunctionType>()) {
     920                            CandidateRef newFunc{new Candidate{*func}};
     921                            newFunc->expr = referenceToRvalueConversion(
     922                                newFunc->expr, newFunc->cost);
     923                            makeFunctionCandidates( location,
     924                                                   newFunc, function,
     925                                                   argExpansions, found );
     926                        }
     927                    }
     928                } catch (SemanticErrorException &e) {
     929                    std::cerr
     930                        << "Resolving value function should cause an error"
     931                        << std::endl;
     932                    errors.append(e);
     933                }
     934            }
     935
     936            if (found.empty()) {
     937                std::cerr << "Resolve value function should always success"
     938                          << std::endl;
     939            }
     940
     941            for (CandidateRef &withFunc : found) {
     942                withFunc->cost.incSafe();
     943                Cost cvtCost =
     944                    computeApplicationConversionCost(withFunc, symtab);
     945                assert(cvtCost != Cost::infinity);
     946
     947                candidates.emplace_back(std::move(withFunc));
     948            }
     949        }
    912950                }
    913951        }
     
    13761414                        ast::Expr * newExpr = data.combine( nameExpr->location, cost );
    13771415
    1378                         bool bentConversion = false;
    1379                         if ( auto inst = newExpr->result.as<ast::EnumInstType>() ) {
    1380                                 if ( inst->base && inst->base->base ) {
    1381                                         bentConversion = true;
    1382                                 }
    1383                         }
    1384 
    13851416                        CandidateRef newCand = std::make_shared<Candidate>(
    1386                                 newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, bentConversion? Cost::safe: Cost::zero,
     1417                                newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero,
    13871418                                cost );
    13881419
     
    14171448        auto cand = new Candidate(variableExpr, tenv);
    14181449        candidates.emplace_back(cand);
     1450
     1451        if (auto enumInst = dynamic_cast<const ast::EnumInstType *>(
     1452                variableExpr->var->get_type())) {
     1453            if (enumInst->base && enumInst->base->base) {
     1454                const CodeLocation &location = cand->expr->location;
     1455
     1456                CandidateFinder funcFinder(context, tenv);
     1457                auto nameExpr = new ast::NameExpr(location, "valueE");
     1458                ResolveMode mode = {true, false, selfFinder.candidates.empty()};
     1459                funcFinder.find( nameExpr, mode );
     1460
     1461                // make variableExpr itself the candidate for the value Call
     1462                ExplodedArgs argExpansions;
     1463                argExpansions.emplace_back();
     1464                auto &argE = argExpansions.back();
     1465
     1466                argE.emplace_back(*cand, symtab);
     1467
     1468                CandidateList found;
     1469                SemanticErrorException errors;
     1470
     1471                for (CandidateRef &func : funcFinder) {
     1472                    try {
     1473                    const ast::Type *funcResult =
     1474                        func->expr->result->stripReferences();
     1475                    if (auto pointer = dynamic_cast<const ast::PointerType *>(
     1476                            funcResult)) {
     1477                        if (auto function =
     1478                                pointer->base.as<ast::FunctionType>()) {
     1479                            CandidateRef newFunc{new Candidate{*func}};
     1480                            newFunc->expr = referenceToRvalueConversion(
     1481                                newFunc->expr, newFunc->cost);
     1482                            makeFunctionCandidates(variableExpr->location,
     1483                                                   newFunc, function,
     1484                                                   argExpansions, found);
     1485                        }
     1486                    }
     1487                    } catch (SemanticErrorException &e) {
     1488                        std::cerr
     1489                            << "Resolving value function should cause an error"
     1490                            << std::endl;
     1491                        errors.append(e);
     1492                    }
     1493                }
     1494
     1495                if (found.empty()) {
     1496                    std::cerr << "Resolve value function should always success"
     1497                            << std::endl;
     1498                }
     1499
     1500                for (CandidateRef &withFunc : found) {
     1501                    withFunc->cost.incSafe();
     1502                    Cost cvtCost =
     1503                        computeApplicationConversionCost(withFunc, symtab);
     1504                    assert(cvtCost != Cost::infinity);
     1505
     1506                    candidates.emplace_back(std::move(withFunc));
     1507                }
     1508            }
     1509        }
    14191510    }
    14201511
     
    17481839
    17491840                                // unification run for side-effects
    1750                                 ast::ptr<ast::Type> common;
    1751                                 bool canUnify = unify( toType, cand->expr->result, env, need, have, open, common );
     1841                                bool canUnify = unify( toType, cand->expr->result, env, need, have, open );
    17521842                                (void) canUnify;
    17531843                                Cost thisCost = computeConversionCost( cand->expr->result, toType, cand->expr->get_lvalue(),
     
    17741864                                        // ambiguous case, still output candidates to print in error message
    17751865                                        if ( cand->cost == minExprCost && thisCost == minCastCost ) {
    1776                                                 auto commonAsEnumAttr = common.as<ast::EnumAttrType>();
    1777                                                 if ( commonAsEnumAttr && commonAsEnumAttr->attr == ast::EnumAttribute::Value ) {
    1778                                                         auto callExpr = new ast::UntypedExpr(
    1779                                                                 cand->expr->location, new ast::NameExpr( cand->expr->location, "valueE"), {cand->expr} );
    1780                                                         CandidateFinder finder( context, env );
    1781                                                         finder.find( callExpr );
    1782                                                         CandidateList winners = findMinCost( finder.candidates );
    1783                                                         if (winners.size() != 1) {
    1784                                                                 SemanticError( callExpr, "Ambiguous expression in valueE..." );
    1785                                                         }
    1786                                                         CandidateRef & choice = winners.front();
    1787                                                         // assert( valueCall->result );
    1788                                                         CandidateRef newCand = std::make_shared<Candidate>(
    1789                                                                 new ast::InitExpr{
    1790                                                                         initExpr->location,
    1791                                                                         // restructureCast( cand->expr, toType ),
    1792                                                                         choice->expr,
    1793                                                                         initAlt.designation },
    1794                                                                 std::move(env), std::move( open ), std::move( need ), cand->cost + thisCost );
    1795                                                                 inferParameters( newCand, matches );
    1796                                                 } else {
    1797                                                         CandidateRef newCand = std::make_shared<Candidate>(
    1798                                                                 new ast::InitExpr{
    1799                                                                         initExpr->location,
    1800                                                                         restructureCast( cand->expr, toType ),
    1801                                                                         initAlt.designation },
    1802                                                                 std::move(env), std::move( open ), std::move( need ), cand->cost + thisCost );
    1803                                                         // currently assertions are always resolved immediately so this should have no effect.
    1804                                                         // if this somehow changes in the future (e.g. delayed by indeterminate return type)
    1805                                                         // we may need to revisit the logic.
    1806                                                         inferParameters( newCand, matches );
    1807                                                 }
     1866                                                CandidateRef newCand = std::make_shared<Candidate>(
     1867                                                        new ast::InitExpr{
     1868                                                                initExpr->location,
     1869                                                                restructureCast( cand->expr, toType ),
     1870                                                                initAlt.designation },
     1871                                                        std::move(env), std::move( open ), std::move( need ), cand->cost + thisCost );
     1872                                                // currently assertions are always resolved immediately so this should have no effect.
     1873                                                // if this somehow changes in the future (e.g. delayed by indeterminate return type)
     1874                                                // we may need to revisit the logic.
     1875                                                inferParameters( newCand, matches );
    18081876                                        }
    18091877                                }
     
    18321900                                                std::make_shared<Candidate>(
    18331901                                                        newExpr, copy( tenv ), ast::OpenVarSet{},
    1834                                                         ast::AssertionSet{}, Cost::safe, cost
     1902                                                        ast::AssertionSet{}, Cost::zero, cost
    18351903                                                );
    18361904
     
    21322200}
    21332201
    2134 // get the valueE(...) ApplicationExpr that returns the enum value
    2135 const ast::Expr * getValueEnumCall(
    2136         const ast::Expr * expr,
    2137         const ResolvExpr::ResolveContext & context, const ast::TypeEnvironment & env ) {
    2138                 auto callExpr = new ast::UntypedExpr(
    2139                         expr->location, new ast::NameExpr( expr->location, "valueE"), {expr} );
    2140                 CandidateFinder finder( context, env );
    2141                 finder.find( callExpr );
    2142                 CandidateList winners = findMinCost( finder.candidates );
    2143                 if (winners.size() != 1) {
    2144                         SemanticError( callExpr, "Ambiguous expression in valueE..." );
    2145                 }
    2146                 CandidateRef & choice = winners.front();
    2147                 return choice->expr;
    2148 }
    2149 
    21502202const ast::Expr * createCondExpr( const ast::Expr * expr ) {
    21512203        assert( expr );
     
    21602212                        }
    21612213                ),
    2162                 new ast::BasicType( ast::BasicKind::SignedInt )
     2214                new ast::BasicType( ast::BasicType::SignedInt )
    21632215        );
    21642216}
  • src/ResolvExpr/CandidateFinder.hpp

    r4e08a54 rda87eaf  
    3030struct CandidateFinder {
    3131        CandidateList candidates;          ///< List of candidate resolutions
    32         const ResolveContext & context;    ///< Information about where the canditates are being found.
     32        const ResolveContext & context;  ///< Information about where the canditates are being found.
    3333        const ast::TypeEnvironment & env;  ///< Substitutions performed in this resolution
    3434        ast::ptr< ast::Type > targetType;  ///< Target type for resolution
    3535        bool strictMode = false;           ///< If set to true, requires targetType to be exact match (inside return cast)
    3636        bool allowVoid = false;            ///< If set to true, allow void-returning function calls (only top level, cast to void and first in comma)
    37         std::set< std::string > otypeKeys; ///< different type may map to same key
     37        std::set< std::string > otypeKeys;  /// different type may map to same key
    3838
    3939        CandidateFinder(
     
    7070        const ast::Expr * expr, Cost & cost );
    7171
    72 /// Get the valueE application that returns the enum's value.
    73 const ast::Expr * getValueEnumCall( const ast::Expr * expr,
    74         const ResolveContext & context, const ast::TypeEnvironment & env );
    75 
    7672/// Wrap an expression to convert the result to a conditional result.
    7773const ast::Expr * createCondExpr( const ast::Expr * expr );
  • src/ResolvExpr/CommonType.cc

    r4e08a54 rda87eaf  
    3838        // GENERATED START, DO NOT EDIT
    3939        // GENERATED BY BasicTypes-gen.cc
    40         #define BT ast::BasicKind::
    41         static const ast::BasicKind commonTypes[BT NUMBER_OF_BASIC_TYPES][BT NUMBER_OF_BASIC_TYPES] = { // nearest common ancestor
     40        #define BT ast::BasicType::
     41        static const BT Kind commonTypes[BT NUMBER_OF_BASIC_TYPES][BT NUMBER_OF_BASIC_TYPES] = { // nearest common ancestor
    4242                /*                                      B                       C                      SC                      UC                      SI                     SUI
    4343                                                        I                      UI                      LI                     LUI                     LLI                    LLUI
     
    339339        // GENERATED END
    340340        static_assert(
    341                 sizeof(commonTypes)/sizeof(commonTypes[0][0]) == ast::BasicKind::NUMBER_OF_BASIC_TYPES * ast::BasicKind::NUMBER_OF_BASIC_TYPES,
     341                sizeof(commonTypes)/sizeof(commonTypes[0][0]) == ast::BasicType::NUMBER_OF_BASIC_TYPES * ast::BasicType::NUMBER_OF_BASIC_TYPES,
    342342                "Each basic type kind should have a corresponding row in the combined type matrix"
    343343        );
     
    366366        void postvisit( const ast::BasicType * basic ) {
    367367                if ( auto basic2 = dynamic_cast< const ast::BasicType * >( type2 ) ) {
    368                         ast::BasicKind kind;
     368                        ast::BasicType::Kind kind;
    369369                        if (basic->kind != basic2->kind && !widen.first && !widen.second) return;
    370370                        else if (!widen.first) kind = basic->kind; // widen.second
     
    385385                } else if ( const ast::EnumInstType * enumInst = dynamic_cast< const ast::EnumInstType * >( type2 ) ) {
    386386                        const ast::EnumDecl* enumDecl = enumInst->base;
    387                         if ( !enumDecl->base ) {
    388                                 ast::BasicKind kind = commonTypes[ basic->kind ][ ast::BasicKind::SignedInt ];
     387                        if ( enumDecl->base ) {
     388                                result = enumDecl->base.get();
     389                        } else {
     390                                ast::BasicType::Kind kind = commonTypes[ basic->kind ][ ast::BasicType::SignedInt ];
    389391                                if (
    390392                                        ( ( kind == basic->kind && basic->qualifiers >= type2->qualifiers )
     
    396398                                }
    397399                        }
    398                 } else if ( auto type2AsAttr = dynamic_cast< const ast::EnumAttrType * >( type2 ) ) {
    399             if ( type2AsAttr->attr == ast::EnumAttribute::Posn ) {
    400                             ast::BasicKind kind = commonTypes[ basic->kind ][ ast::BasicKind::SignedInt ];
    401                             if (
    402                                     ( ( kind == basic->kind && basic->qualifiers >= type2->qualifiers )
    403                                             || widen.first )
    404                                     && ( ( kind != basic->kind && basic->qualifiers <= type2->qualifiers )
    405                                             || widen.second )
    406                             ) {
    407                                     result = new ast::BasicType{ kind, basic->qualifiers | type2->qualifiers };
    408                             }
    409             }
     400                } else if ( dynamic_cast< const ast::EnumPosType * >( type2 ) ) {
     401                        ast::BasicType::Kind kind = commonTypes[ basic->kind ][ ast::BasicType::SignedInt ];
     402                        if (
     403                                ( ( kind == basic->kind && basic->qualifiers >= type2->qualifiers )
     404                                        || widen.first )
     405                                && ( ( kind != basic->kind && basic->qualifiers <= type2->qualifiers )
     406                                        || widen.second )
     407                        ) {
     408                                result = new ast::BasicType{ kind, basic->qualifiers | type2->qualifiers };
     409                        }
    410410                }
    411411        }
     
    426426                result = voidPtr;
    427427                add_qualifiers( result, oPtr->qualifiers );
     428        }
     429
     430        // For a typed enum, we want to unify type1 with the base type of the enum
     431        bool tryResolveWithTypedEnum( const ast::Type * type1 ) {
     432                if (auto enumInst = dynamic_cast<const ast::EnumInstType *> (type2) ) {
     433                        ast::OpenVarSet newOpen{ open };
     434                        if (enumInst->base->base
     435                                && unifyExact(type1, enumInst->base->base, tenv, need, have, newOpen, widen)) {
     436                                        result = type1;
     437                                return true;
     438                        }
     439                }
     440                return false;
    428441        }
    429442
     
    594607                        result = pointer;
    595608                        add_qualifiers( result, type2->qualifiers );
    596                 }
    597         }
    598 
    599         void postvisit( const ast::ArrayType * ) {}
     609                } else {
     610                        tryResolveWithTypedEnum( pointer );
     611                }
     612        }
     613
     614        void postvisit( const ast::ArrayType * arr ) {
     615                // xxx - does it make sense?
     616                tryResolveWithTypedEnum( arr );
     617        }
    600618
    601619        void postvisit( const ast::ReferenceType * ref ) {
     
    641659        }
    642660
    643         void postvisit( const ast::FunctionType * ) {}
    644 
    645         void postvisit( const ast::StructInstType * ) {}
    646 
    647         void postvisit( const ast::UnionInstType * ) {}
     661        void postvisit( const ast::FunctionType * func) {
     662                tryResolveWithTypedEnum( func );
     663        }
     664
     665        void postvisit( const ast::StructInstType * inst ) {
     666                tryResolveWithTypedEnum( inst );
     667        }
     668
     669        void postvisit( const ast::UnionInstType * inst ) {
     670                tryResolveWithTypedEnum( inst );
     671        }
    648672
    649673        void postvisit( const ast::EnumInstType * enumInst ) {
    650                 if ( enumInst->base && !enumInst->base->base ) {
    651                         auto basicType = new ast::BasicType( ast::BasicKind::UnsignedInt );
    652                         result = commonType( basicType, type2, tenv, need, have, open, widen);
    653                 }
    654         }
    655 
    656         void postvisit( const ast::EnumAttrType * ) {}
     674                // if ( dynamic_cast<const ast::EnumPosType *>(enumInst) ) {
     675                //      result = enumInst;
     676                // } else
     677                if (!dynamic_cast<const ast::EnumInstType *>(type2)) {
     678                        result = commonType( type2, enumInst, tenv, need, have, open, widen);
     679                }
     680        }
     681
     682        void postvisit( const ast::EnumPosType * enumPos ) {
     683                if ( auto type2AsPos = dynamic_cast<const ast::EnumPosType *>(type2) ) {
     684                        // result = commonType( type2AsPos->instance, enumPos->instance, tenv, need, have, open, widen );
     685                        // result = enumPos;
     686                        if ( enumPos->instance->base->name == type2AsPos->instance->base->name ) {
     687                                result = type2;
     688                        }
     689                } else if ( dynamic_cast<const ast::BasicType *>(type2) ) {
     690                        result = type2;
     691                }
     692        }
    657693
    658694        void postvisit( const ast::TraitInstType * ) {}
     
    660696        void postvisit( const ast::TypeInstType * ) {}
    661697
    662         void postvisit( const ast::TupleType * ) {}
     698        void postvisit( const ast::TupleType * tuple ) {
     699                tryResolveWithTypedEnum( tuple );
     700        }
    663701
    664702        void postvisit( const ast::VarArgsType * ) {}
     
    674712                } else if ( widen.second && dynamic_cast< const ast::OneType * >( type2 ) ) {
    675713                        result = new ast::BasicType{
    676                                 ast::BasicKind::SignedInt, zero->qualifiers | type2->qualifiers };
     714                                ast::BasicType::SignedInt, zero->qualifiers | type2->qualifiers };
    677715                } else if ( const ast::EnumInstType * enumInst = dynamic_cast< const ast::EnumInstType * >( type2 ) ) {
    678716                        const ast::EnumDecl * enumDecl = enumInst->base;
    679                         if ( !enumDecl->base ) {
     717                        if ( enumDecl->base ) {
     718                                if ( tryResolveWithTypedEnum( zero ) )
     719                                        add_qualifiers( result, zero->qualifiers );
     720                        } else {
    680721                                if ( widen.second || zero->qualifiers <= type2->qualifiers ) {
    681722                                        result = type2;
     
    695736                } else if ( widen.second && dynamic_cast< const ast::ZeroType * >( type2 ) ) {
    696737                        result = new ast::BasicType{
    697                                 ast::BasicKind::SignedInt, one->qualifiers | type2->qualifiers };
     738                                ast::BasicType::SignedInt, one->qualifiers | type2->qualifiers };
    698739                } else if ( const ast::EnumInstType * enumInst = dynamic_cast< const ast::EnumInstType * >( type2 ) ) {
    699                         const ast::EnumDecl * enumDecl = enumInst->base;
    700                         if ( !enumDecl->base ) {
     740                        const ast::EnumDecl * enumBase = enumInst->base;
     741                        if ( enumBase->base ) {
     742                                if ( tryResolveWithTypedEnum( one ))
     743                                        add_qualifiers( result, one->qualifiers );
     744                        } else {
    701745                                if ( widen.second || one->qualifiers <= type2->qualifiers ) {
    702746                                        result = type2;
  • src/ResolvExpr/ConversionCost.cc

    r4e08a54 rda87eaf  
    5959        // GENERATED START, DO NOT EDIT
    6060        // GENERATED BY BasicTypes-gen.cc
    61         static const int costMatrix[ast::BasicKind::NUMBER_OF_BASIC_TYPES][ast::BasicKind::NUMBER_OF_BASIC_TYPES] = { // path length from root to node
     61        static const int costMatrix[ast::BasicType::NUMBER_OF_BASIC_TYPES][ast::BasicType::NUMBER_OF_BASIC_TYPES] = { // path length from root to node
    6262                /*               B    C   SC   UC   SI  SUI    I   UI   LI  LUI  LLI LLUI   IB  UIB  _FH  _FH   _F  _FC    F   FC  _FX _FXC   FD _FDC    D   DC F80X_FDXC  F80  _FB_FLDC   FB   LD  LDC _FBX_FLDXC */
    6363                /*      B */ {   0,   1,   1,   2,   2,   3,   3,   4,   4,   5,   5,   6,   6,   7,   7,   8,   8,   9,   9,  10,  10,  11,  11,  12,  12,  13,  13,  14,  14,  15,  15,  16,  17,  16,  18,  17, },
     
    101101        // GENERATED END
    102102        static_assert(
    103                 sizeof(costMatrix)/sizeof(costMatrix[0][0]) == ast::BasicKind::NUMBER_OF_BASIC_TYPES * ast::BasicKind::NUMBER_OF_BASIC_TYPES,
     103                sizeof(costMatrix)/sizeof(costMatrix[0][0]) == ast::BasicType::NUMBER_OF_BASIC_TYPES * ast::BasicType::NUMBER_OF_BASIC_TYPES,
    104104                "Missing row in the cost matrix"
    105105        );
     
    107107        // GENERATED START, DO NOT EDIT
    108108        // GENERATED BY BasicTypes-gen.cc
    109         static const int signMatrix[ast::BasicKind::NUMBER_OF_BASIC_TYPES][ast::BasicKind::NUMBER_OF_BASIC_TYPES] = { // number of sign changes in safe conversion
     109        static const int signMatrix[ast::BasicType::NUMBER_OF_BASIC_TYPES][ast::BasicType::NUMBER_OF_BASIC_TYPES] = { // number of sign changes in safe conversion
    110110                /*               B    C   SC   UC   SI  SUI    I   UI   LI  LUI  LLI LLUI   IB  UIB  _FH  _FH   _F  _FC    F   FC  _FX _FXC   FD _FDC    D   DC F80X_FDXC  F80  _FB_FLDC   FB   LD  LDC _FBX_FLDXC */
    111111                /*      B */ {   0,   0,   0,   1,   0,   1,   0,   1,   0,   1,   0,   1,   0,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, },
     
    148148        // GENERATED END
    149149        static_assert(
    150                 sizeof(signMatrix)/sizeof(signMatrix[0][0]) == ast::BasicKind::NUMBER_OF_BASIC_TYPES * ast::BasicKind::NUMBER_OF_BASIC_TYPES,
     150                sizeof(signMatrix)/sizeof(signMatrix[0][0]) == ast::BasicType::NUMBER_OF_BASIC_TYPES * ast::BasicType::NUMBER_OF_BASIC_TYPES,
    151151                "Missing row in the sign matrix"
    152152        );
     
    278278        if ( const ast::BasicType * dstAsBasic = dynamic_cast< const ast::BasicType * >( dst ) ) {
    279279                conversionCostFromBasicToBasic( basicType, dstAsBasic );
    280         } else if ( dynamic_cast< const ast::EnumAttrType *>(dst) ) {
    281                 static ast::ptr<ast::BasicType> integer = { new ast::BasicType( ast::BasicKind::SignedInt ) };
     280        }
     281        else if ( const ast::EnumInstType * enumInst = dynamic_cast< const ast::EnumInstType * >( dst ) ) {
     282                auto enumDecl = enumInst->base;
     283                if ( enumDecl->base.get() ) {
     284                        // cost = costCalc( basicType, baseType, srcIsLvalue, symtab, env );
     285                        // cost.incUnsafe();
     286                        cost = Cost::infinity;
     287                } else {
     288            cost = Cost::unsafe;
     289                }
     290        } else if ( dynamic_cast< const ast::EnumPosType *>(dst) ) {
     291                static ast::ptr<ast::BasicType> integer = { new ast::BasicType( ast::BasicType::SignedInt ) };
    282292                cost = costCalc( basicType, integer, srcIsLvalue, symtab, env );
    283         } else if ( auto dstAsEnumInst = dynamic_cast< const ast::EnumInstType * >( dst ) ) {
    284                 if ( dstAsEnumInst->base && !dstAsEnumInst->base->base ) {
    285                         cost = Cost::zero;
    286                         cost.incUnsafe();
    287                 }
    288293        }
    289294}
     
    361366}
    362367
    363 void ConversionCost::postvisit( const ast::EnumInstType * inst ) {
    364         if ( auto dstAsInst = dynamic_cast<const ast::EnumInstType *>( dst ) ) {
    365                 if (inst->base && dstAsInst->base) {
    366                         if (inst->base->name == dstAsInst->base->name) {
    367                                 cost = Cost::zero;
    368                                 return;
    369                         }
    370                 }
    371                 return;
    372         }
    373         static ast::ptr<ast::BasicType> integer = { new ast::BasicType( ast::BasicKind::SignedInt ) };
     368void ConversionCost::postvisit( const ast::EnumInstType * ) {
     369        static ast::ptr<ast::BasicType> integer = { new ast::BasicType( ast::BasicType::SignedInt ) };
    374370        cost = costCalc( integer, dst, srcIsLvalue, symtab, env );
    375371        if ( cost < Cost::unsafe ) {
     
    378374}
    379375
    380 void ConversionCost::postvisit( const ast::EnumAttrType * src ) {
    381     auto dstAsEnumAttrType = dynamic_cast<const ast::EnumAttrType *>(dst);
    382         assert( src->attr != ast::EnumAttribute::Label );
    383     if ( src->attr == ast::EnumAttribute::Value ) {
    384         if ( dstAsEnumAttrType && dstAsEnumAttrType->attr == ast::EnumAttribute::Value) {
    385             cost = costCalc( src->instance, dstAsEnumAttrType->instance, srcIsLvalue, symtab, env );
    386         } else {
    387             auto baseType = src->instance->base->base;
    388             cost = costCalc( baseType, dst, srcIsLvalue, symtab, env );
    389                         if ( cost < Cost::infinity ) {
    390                                 cost.incUnsafe();
    391                         }
    392         }
    393     } else { // ast::EnumAttribute::Posn
    394         if ( auto dstBase = dynamic_cast<const ast::EnumInstType *>( dst ) ) {
    395                     cost = costCalc( src->instance, dstBase, srcIsLvalue, symtab, env );
    396                     if ( cost < Cost::unsafe ) cost.incSafe();
    397             } else {
    398                     static ast::ptr<ast::BasicType> integer = { new ast::BasicType( ast::BasicKind::SignedInt ) };
    399                     cost = costCalc( integer, dst, srcIsLvalue, symtab, env );
    400                     if ( cost < Cost::unsafe ) {
    401                             cost.incSafe();
    402                     }
    403             }
    404     }
     376void ConversionCost::postvisit( const ast::EnumPosType * src ) {
     377        if ( dynamic_cast<const ast::EnumPosType *>( dst ) ) {
     378                // cost = costCalc( src->instance, dstBase->instance, srcIsLvalue, symtab, env );
     379                // if ( cost < Cost::unsafe ) cost.incSafe();
     380                cost = Cost::zero;
     381        } else if ( auto dstBase = dynamic_cast<const ast::EnumInstType *>( dst ) ) {
     382                cost = costCalc( src->instance, dstBase, srcIsLvalue, symtab, env );
     383                if ( cost < Cost::unsafe ) cost.incSafe();
     384        } else {
     385                static ast::ptr<ast::BasicType> integer = { new ast::BasicType( ast::BasicType::SignedInt ) };
     386                cost = costCalc( integer, dst, srcIsLvalue, symtab, env );
     387                if ( cost < Cost::unsafe ) {
     388                        cost.incSafe();
     389                }
     390        }
     391
    405392}
    406393
     
    461448        } else if ( const ast::BasicType * dstAsBasic =
    462449                        dynamic_cast< const ast::BasicType * >( dst ) ) {
    463                 int tableResult = costMatrix[ ast::BasicKind::SignedInt ][ dstAsBasic->kind ];
     450                int tableResult = costMatrix[ ast::BasicType::SignedInt ][ dstAsBasic->kind ];
    464451                if ( -1 == tableResult ) {
    465452                        cost = Cost::unsafe;
     
    467454                        cost = Cost::zero;
    468455                        cost.incSafe( tableResult + 1 );
    469                         cost.incSign( signMatrix[ ast::BasicKind::SignedInt ][ dstAsBasic->kind ] );
     456                        cost.incSign( signMatrix[ ast::BasicType::SignedInt ][ dstAsBasic->kind ] );
    470457                }
    471458                // this has the effect of letting any expr such as x+0, x+1 to be typed
     
    479466                cost.incSafe( maxIntCost + 2 );
    480467                // assuming 0p is supposed to be used for pointers?
    481         } else if ( auto dstAsEnumInst = dynamic_cast< const ast::EnumInstType * >( dst ) ) {
    482                 if ( dstAsEnumInst->base && !dstAsEnumInst->base->base ) {
    483                         cost = Cost::zero;
    484                         cost.incUnsafe();
    485                 }
    486468        }
    487469}
     
    493475        } else if ( const ast::BasicType * dstAsBasic =
    494476                        dynamic_cast< const ast::BasicType * >( dst ) ) {
    495                 int tableResult = costMatrix[ ast::BasicKind::SignedInt ][ dstAsBasic->kind ];
     477                int tableResult = costMatrix[ ast::BasicType::SignedInt ][ dstAsBasic->kind ];
    496478                if ( -1 == tableResult ) {
    497479                        cost = Cost::unsafe;
     
    499481                        cost = Cost::zero;
    500482                        cost.incSafe( tableResult + 1 );
    501                         cost.incSign( signMatrix[ ast::BasicKind::SignedInt ][ dstAsBasic->kind ] );
    502                 }
    503         } else if ( auto dstAsEnumInst = dynamic_cast< const ast::EnumInstType * >( dst ) ) {
    504                 if ( dstAsEnumInst->base && !dstAsEnumInst->base->base ) {
    505                         cost = Cost::zero;
    506                         cost.incUnsafe();
     483                        cost.incSign( signMatrix[ ast::BasicType::SignedInt ][ dstAsBasic->kind ] );
    507484                }
    508485        }
  • src/ResolvExpr/ConversionCost.h

    r4e08a54 rda87eaf  
    7272        void postvisit( const ast::ZeroType * zeroType );
    7373        void postvisit( const ast::OneType * oneType );
    74         void postvisit( const ast::EnumAttrType * posType );
     74        void postvisit( const ast::EnumPosType * posType );
    7575private:
    7676        // refactor for code resue
  • src/ResolvExpr/PtrsCastable.cc

    r4e08a54 rda87eaf  
    100100                                result = 1;
    101101                        } else if ( auto bt = dynamic_cast< const ast::BasicType * >( dst ) ) {
    102                                 if ( bt->kind == ast::BasicKind::SignedInt ) {
     102                                if ( bt->kind == ast::BasicType::SignedInt ) {
    103103                                        result = 0;
    104104                                } else {
  • src/ResolvExpr/ResolveTypeof.cc

    r4e08a54 rda87eaf  
    6363                        if ( newType.as< ast::EnumInstType >() ) {
    6464                                newType = new ast::BasicType(
    65                                         ast::BasicKind::SignedInt, newType->qualifiers, copy(newType->attributes) );
     65                                        ast::BasicType::SignedInt, newType->qualifiers, copy(newType->attributes) );
    6666                        }
    6767                        reset_qualifiers(
     
    9191                auto mutType = mutate(arrayType);
    9292                auto globalSizeType = context.global.sizeType;
    93                 ast::ptr<ast::Type> sizetype = globalSizeType ? globalSizeType : new ast::BasicType( ast::BasicKind::LongUnsignedInt );
     93                ast::ptr<ast::Type> sizetype = globalSizeType ? globalSizeType : new ast::BasicType(ast::BasicType::LongUnsignedInt);
    9494                mutType->dimension = findSingleExpression(arrayType->dimension, sizetype, context );
    9595
  • src/ResolvExpr/Resolver.cc

    r4e08a54 rda87eaf  
    351351        bool isCharType( const ast::Type * t ) {
    352352                if ( auto bt = dynamic_cast< const ast::BasicType * >( t ) ) {
    353                         return bt->kind == ast::BasicKind::Char
    354                                 || bt->kind == ast::BasicKind::SignedChar
    355                                 || bt->kind == ast::BasicKind::UnsignedChar;
     353                        return bt->kind == ast::BasicType::Char
     354                                || bt->kind == ast::BasicType::SignedChar
     355                                || bt->kind == ast::BasicType::UnsignedChar;
    356356                }
    357357                return false;
     
    458458                        if (attr->params.size() == 1) {
    459459                                auto arg = attr->params.front();
    460                                 auto resolved = ResolvExpr::findSingleExpression( arg, new ast::BasicType( ast::BasicKind::LongLongSignedInt ), context );
     460                                auto resolved = ResolvExpr::findSingleExpression( arg, new ast::BasicType( ast::BasicType::LongLongSignedInt ), context );
    461461                                auto result = eval(arg);
    462462
     
    624624                        objectDecl = fixObjectType( objectDecl, context );
    625625                        currentObject = ast::CurrentObject{
    626                                 objectDecl->location, new ast::BasicType{ ast::BasicKind::SignedInt } };
     626                                objectDecl->location, new ast::BasicType{ ast::BasicType::SignedInt } };
    627627                }
    628628        } else {
     
    10951095                // resolve the timeout as a size_t, the conditions like IfStmt, and stmts normally
    10961096                ast::ptr< ast::Type > target =
    1097                         new ast::BasicType{ ast::BasicKind::LongLongUnsignedInt };
     1097                        new ast::BasicType{ ast::BasicType::LongLongUnsignedInt };
    10981098                auto timeout_time = findSingleExpression( stmt->timeout_time, target, context );
    10991099                auto timeout_cond = findCondExpression( stmt->timeout_cond, context );
  • src/ResolvExpr/Unify.cc

    r4e08a54 rda87eaf  
    274274                void previsit( const ast::Node * ) { visit_children = false; }
    275275
    276                 void postvisit( const ast::VoidType * vt) {
    277                         result = dynamic_cast< const ast::VoidType * >( type2 )
    278                                 || tryToUnifyWithEnumValue(vt, type2, tenv, need, have, open, noWiden());
    279                         ;
     276                void postvisit( const ast::VoidType * ) {
     277                        result = dynamic_cast< const ast::VoidType * >( type2 );
    280278                }
    281279
     
    284282                                result = basic->kind == basic2->kind;
    285283                        }
    286                         result = result || tryToUnifyWithEnumValue(basic, type2, tenv, need, have, open, noWiden());
    287284                }
    288285
     
    293290                                        noWiden());
    294291                        }
    295                         result = result || tryToUnifyWithEnumValue(pointer, type2, tenv, need, have, open, noWiden());
    296292                }
    297293
     
    311307
    312308                        result = unifyExact(
    313                                 array->base, array2->base, tenv, need, have, open, noWiden())
    314                                 || tryToUnifyWithEnumValue(array, type2, tenv, need, have, open, noWiden());
     309                                array->base, array2->base, tenv, need, have, open, noWiden());
    315310                }
    316311
     
    404399                }
    405400
    406                 bool tryToUnifyWithEnumValue( const ast::Type * type1, const ast::Type * type2, ast::TypeEnvironment & env,
    407                         ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
    408                         WidenMode widen) {
    409                         if ( auto attrType2 = dynamic_cast<const ast::EnumAttrType *>(type2)) {
    410                                 if (attrType2->attr == ast::EnumAttribute::Value) {
    411                                         return unifyExact( type1, attrType2->instance->base->base, env, need, have, open,
    412                                                 widen);
    413                                 } else if (attrType2->attr == ast::EnumAttribute::Posn) {
    414                                         return unifyExact( type1, attrType2->instance, env, need, have, open, widen );
    415                                 }
    416                         }
    417                         return false;
    418                 }
    419 
    420401        public:
    421402                void postvisit( const ast::FunctionType * func ) {
     
    526507                void postvisit( const ast::StructInstType * aggrType ) {
    527508                        handleGenericRefType( aggrType, type2 );
    528                         result = result || tryToUnifyWithEnumValue(aggrType, type2, tenv, need, have, open, noWiden());
    529509                }
    530510
    531511                void postvisit( const ast::UnionInstType * aggrType ) {
    532512                        handleGenericRefType( aggrType, type2 );
    533                         result = result || tryToUnifyWithEnumValue(aggrType, type2, tenv, need, have, open, noWiden());
    534513                }
    535514
    536515                void postvisit( const ast::EnumInstType * aggrType ) {
    537516                        handleRefType( aggrType, type2 );
    538                         result = result || tryToUnifyWithEnumValue(aggrType, type2, tenv, need, have, open, noWiden());
    539                 }
    540 
    541                 void postvisit( const ast::EnumAttrType * enumAttr ) {
     517                }
     518
     519                void postvisit( const ast::EnumPosType * posType ) {
    542520                        // Lazy approach for now
    543                         if ( auto otherPos = dynamic_cast< const ast::EnumAttrType *>(type2) ) {
    544                             if ( enumAttr->match(otherPos) ) {
    545                                     result = otherPos;
    546                             }
    547             } 
     521                        auto otherPos = dynamic_cast< const ast::EnumPosType *>(type2);
     522                        if ( otherPos ) {
     523                                if ( otherPos->instance->base->name == posType->instance->base->name )
     524                                        result = otherPos;
     525                        }
    548526                }
    549527
    550528                void postvisit( const ast::TraitInstType * aggrType ) {
    551529                        handleRefType( aggrType, type2 );
    552                         result = result || tryToUnifyWithEnumValue(aggrType, type2, tenv, need, have, open, noWiden());
    553530                }
    554531
     
    559536                                this->result = otherInst;
    560537                        }
    561                         result = result || tryToUnifyWithEnumValue(typeInst, type2, tenv, need, have, open, noWiden());
    562538                }
    563539
     
    634610                        auto types2 = flatten( flat2 );
    635611
    636                         result = unifyList( types, types2, tenv, need, have, open )
    637                                 || tryToUnifyWithEnumValue(tuple, type2, tenv, need, have, open, noWiden());
    638                 }
    639 
    640                 void postvisit( const ast::VarArgsType * vat) {
    641                         result = dynamic_cast< const ast::VarArgsType * >( type2 )
    642                                 || tryToUnifyWithEnumValue(vat, type2, tenv, need, have, open, noWiden());
    643                 }
    644 
    645                 void postvisit( const ast::ZeroType * zt) {
    646                         result = dynamic_cast< const ast::ZeroType * >( type2 )
    647                                 || tryToUnifyWithEnumValue(zt, type2, tenv, need, have, open, noWiden());
    648                 }
    649 
    650                 void postvisit( const ast::OneType * ot) {
    651                         result = dynamic_cast< const ast::OneType * >( type2 )
    652                                 || tryToUnifyWithEnumValue(ot, type2, tenv, need, have, open, noWiden());
     612                        result = unifyList( types, types2, tenv, need, have, open );
     613                }
     614
     615                void postvisit( const ast::VarArgsType * ) {
     616                        result = dynamic_cast< const ast::VarArgsType * >( type2 );
     617                }
     618
     619                void postvisit( const ast::ZeroType * ) {
     620                        result = dynamic_cast< const ast::ZeroType * >( type2 );
     621                }
     622
     623                void postvisit( const ast::OneType * ) {
     624                        result = dynamic_cast< const ast::OneType * >( type2 );
    653625                }
    654626        };
  • src/SymTab/GenImplicitCall.cpp

    r4e08a54 rda87eaf  
    133133
    134134        ast::ptr< ast::DeclWithType > index = new ast::ObjectDecl(
    135                 loc, indexName.newName(), new ast::BasicType( ast::BasicKind::SignedInt ),
     135                loc, indexName.newName(), new ast::BasicType( ast::BasicType::SignedInt ),
    136136                new ast::SingleInit( loc, begin ) );
    137137        ast::ptr< ast::Expr > indexVar = new ast::VariableExpr( loc, index );
  • src/SymTab/Mangler.cc

    r4e08a54 rda87eaf  
    5858        void postvisit( const ast::OneType * oneType );
    5959        void postvisit( const ast::QualifiedType * qualType );
    60         void postvisit( const ast::EnumAttrType * posType );
     60
     61        void postvisit( const ast::EnumPosType * posType );
    6162
    6263        /// The result is the current constructed mangled name.
     
    142143void Mangler::postvisit( const ast::BasicType * basicType ) {
    143144        printQualifiers( basicType );
    144         assertf( basicType->kind < ast::BasicKind::NUMBER_OF_BASIC_TYPES, "Unhandled basic type: %d", basicType->kind );
     145        assertf( basicType->kind < ast::BasicType::NUMBER_OF_BASIC_TYPES, "Unhandled basic type: %d", basicType->kind );
    145146        mangleName += Encoding::basicTypes[ basicType->kind ];
    146147}
     
    280281}
    281282
    282 void Mangler::postvisit( const ast::EnumAttrType * enumAttr ) {
    283         postvisit( enumAttr->instance );
    284         // mangleName += "_pos";
    285     switch ( enumAttr->attr )
    286     {
    287         case ast::EnumAttribute::Label:
    288             mangleName += "_label_";
    289             break;
    290         case ast::EnumAttribute::Posn:
    291                         mangleName += "_posn_";
    292             break;
    293         case ast::EnumAttribute::Value:
    294             mangleName += "_value_";
    295             break;
    296     }
    297 
     283void Mangler::postvisit( const ast::EnumPosType * pos ) {
     284        postvisit( pos->instance );
     285        mangleName += "_pos";
    298286}
    299287
  • src/SymTab/ManglerCommon.cc

    r4e08a54 rda87eaf  
    4141//   - "Di" char32_t
    4242//   - "Ds" char16_t
    43 const std::string basicTypes[ast::BasicKind::NUMBER_OF_BASIC_TYPES] = {
     43const std::string basicTypes[ast::BasicType::NUMBER_OF_BASIC_TYPES] = {
    4444        "b",        // _Bool
    4545        "c",        // char
     
    8181// GENERATED END
    8282static_assert(
    83         sizeof(basicTypes) / sizeof(basicTypes[0]) == ast::BasicKind::NUMBER_OF_BASIC_TYPES,
     83        sizeof(basicTypes) / sizeof(basicTypes[0]) == ast::BasicType::NUMBER_OF_BASIC_TYPES,
    8484        "Each basic type kind should have a corresponding mangler letter"
    8585);
  • src/Tuples/TupleAssignment.cc

    r4e08a54 rda87eaf  
    3535#include "InitTweak/GenInit.h"             // for genCtorInit
    3636#include "InitTweak/InitTweak.h"           // for getPointerBase, isAssignment
    37 #include "ResolvExpr/CandidateFinder.hpp"  // for CandidateFinder
    3837#include "ResolvExpr/Cost.h"               // for Cost
    3938#include "ResolvExpr/Resolver.h"           // for resolveCtorInit
  • src/Tuples/TupleExpansion.cpp

    r4e08a54 rda87eaf  
    106106                        assignUnq = commaExpr->arg1;
    107107                }
    108                 auto finished = new ast::ObjectDecl( loc, toString( "_unq", id, "_finished_" ), new ast::BasicType( ast::BasicKind::Bool ),
     108                auto finished = new ast::ObjectDecl( loc, toString( "_unq", id, "_finished_" ), new ast::BasicType( ast::BasicType::Kind::Bool ),
    109109                        new ast::SingleInit( loc, ast::ConstantExpr::from_int( loc, 0 ) ), {}, ast::Linkage::Cforall );
    110110                declsToAddBefore.push_back( finished );
     
    175175                        new ast::ObjectDecl( location,
    176176                                "dummy",
    177                                 new ast::BasicType( ast::BasicKind::SignedInt ),
     177                                new ast::BasicType( ast::BasicType::SignedInt ),
    178178                                nullptr,
    179179                                ast::Storage::Classes(),
  • src/Tuples/Tuples.h

    r4e08a54 rda87eaf  
    2121#include "AST/Fwd.hpp"
    2222#include "AST/Node.hpp"
    23 namespace ResolvExpr {
    24         class CandidateFinder;
    25 }
     23#include "ResolvExpr/CandidateFinder.hpp"
    2624
    2725namespace Tuples {
  • src/Validate/Autogen.cpp

    r4e08a54 rda87eaf  
    196196
    197197        bool shouldAutogen() const final { return true; }
     198        void genAttrFuncForward();
     199        void genPosFunctions();
    198200private:
    199201        void genFuncBody( ast::FunctionDecl * decl ) final;
    200202        void genFieldCtors() final;
    201203        const ast::Decl * getDecl() const final { return decl; }
     204
     205        ast::FunctionDecl * genPosProto() const;
     206        ast::FunctionDecl * genLabelProto() const;
     207        ast::FunctionDecl * genValueProto() const;
     208        ast::FunctionDecl * genSuccProto() const;
     209        ast::FunctionDecl * genPredProto() const;
     210
     211        ast::FunctionDecl * genSuccPosProto() const;
     212        ast::FunctionDecl * genPredPosProto() const;
     213
     214        ast::FunctionDecl * genSuccPredFunc( bool succ );
     215        // ast::FunctionDecl * genPredFunc();
    202216};
    203217
     
    242256        enumInst.base = enumDecl;
    243257        EnumFuncGenerator gen( enumDecl, &enumInst, functionNesting );
     258        if ( enumDecl->base ) {
     259                gen.genAttrFuncForward();
     260                gen.genPosFunctions();
     261        }
    244262        gen.generateAndAppendFunctions( declsToAddAfter );
    245263}
     
    400418}
    401419
    402 /// Use the current type T to create `void ^?{}(T & _dst)`.
     420/// Use the current type T to create `void ?{}(T & _dst)`.
    403421ast::FunctionDecl * FuncGenerator::genDtorProto() const {
    404422        // The destructor must be mutex on a concurrent type.
     
    759777}
    760778
     779ast::FunctionDecl * EnumFuncGenerator::genPosProto() const {
     780        return genProto( "posE",
     781                { new ast::ObjectDecl( getLocation(), "_i",
     782                new ast::EnumInstType( decl ) )},
     783                { new ast::ObjectDecl( getLocation(), "_ret",
     784                new ast::BasicType{ ast::BasicType::UnsignedInt } )} );
     785}
     786
     787ast::FunctionDecl * EnumFuncGenerator::genLabelProto() const {
     788        return genProto( "labelE",
     789                { new ast::ObjectDecl( getLocation(), "_i",
     790                new ast::EnumInstType( decl ) ) },
     791                { new ast::ObjectDecl( getLocation(), "_ret",
     792                new ast::PointerType( new ast::BasicType{ ast::BasicType::Char } ) ) } );
     793}
     794
     795ast::FunctionDecl * EnumFuncGenerator::genValueProto() const {
     796        return genProto( "valueE",
     797                { new ast::ObjectDecl( getLocation(), "_i", new ast::EnumInstType( decl ) )},
     798                { new ast::ObjectDecl( getLocation(), "_ret", ast::deepCopy( decl->base ) ) } );
     799}
     800
     801ast::FunctionDecl * EnumFuncGenerator::genSuccProto() const {
     802        return genProto( "succ",
     803                { new ast::ObjectDecl( getLocation(), "_i", new ast::EnumInstType( decl ) )},
     804                { new ast::ObjectDecl( getLocation(), "_ret", new ast::EnumInstType( decl ))} );
     805}
     806
     807ast::FunctionDecl * EnumFuncGenerator::genPredProto() const {
     808        return genProto( "pred",
     809                { new ast::ObjectDecl( getLocation(), "_i", new ast::EnumInstType( decl ))},
     810                { new ast::ObjectDecl( getLocation(), "_ret", new ast::EnumInstType( decl ))} );
     811}
     812
     813ast::FunctionDecl * EnumFuncGenerator::genSuccPosProto() const {
     814        return genProto( "_successor_",
     815                { new ast::ObjectDecl( getLocation(), "_i",
     816                        new ast::EnumPosType( new ast::EnumInstType( decl ) ) )},
     817                {
     818                        new ast::ObjectDecl( getLocation(), "_ret",
     819                        new ast::EnumPosType( new ast::EnumInstType( decl ) ) )
     820                } );
     821}
     822
     823ast::FunctionDecl * EnumFuncGenerator::genPredPosProto() const {
     824        return genProto( "_predessor_",
     825                { new ast::ObjectDecl( getLocation(), "_i",
     826                        new ast::EnumPosType( new ast::EnumInstType( decl ) ) )},
     827                {
     828                        new ast::ObjectDecl( getLocation(), "_ret",
     829                        new ast::EnumPosType( new ast::EnumInstType( decl ) ) )
     830                } );
     831}
     832
     833ast::FunctionDecl * EnumFuncGenerator::genSuccPredFunc( bool succ ) {
     834        ast::FunctionDecl * decl = succ? genSuccPosProto(): genPredPosProto();
     835        produceForwardDecl( decl );
     836
     837        const CodeLocation& location = getLocation();
     838
     839        auto & params = decl->params;
     840        assert( params.size() == 1 );
     841        auto param = params.front().strict_as<ast::ObjectDecl>();
     842
     843        auto newReturn = new ast::ObjectDecl( location, "_returns",
     844                new ast::BasicType{ ast::BasicType::SignedInt} );
     845       
     846
     847        ast::UntypedExpr * addOneExpr = new ast::UntypedExpr( location,
     848                new ast::NameExpr( location, succ? "?+?": "?-?" )
     849        );
     850        addOneExpr->args.push_back(
     851                new ast::CastExpr( location,
     852                        new ast::VariableExpr( location, param ),
     853                        new ast::BasicType{ ast::BasicType::SignedInt }
     854                )
     855        );
     856        addOneExpr->args.push_back(
     857                ast::ConstantExpr::from_int( location, 1 )
     858        );
     859
     860        ast::UntypedExpr * assignExpr = new ast::UntypedExpr( location,
     861                new ast::NameExpr( location, "?=?" )
     862        );
     863        assignExpr->args.push_back(     
     864                new ast::VariableExpr( location, newReturn )
     865        );
     866        assignExpr->args.push_back(
     867                addOneExpr
     868        );
     869
     870        decl->stmts = new ast::CompoundStmt( location,
     871                {
     872                        new ast::DeclStmt( location, newReturn ),
     873                        new ast::ExprStmt( location, assignExpr ),
     874                        new ast::ReturnStmt( location,
     875                                new ast::VariableExpr( location, newReturn ))
     876                } );
     877       
     878        return decl;
     879}
     880
     881void EnumFuncGenerator::genAttrFuncForward() { 
     882        if ( decl->base ) {
     883                ast::FunctionDecl *(EnumFuncGenerator::*attrProtos[5])() const = {
     884                        &EnumFuncGenerator::genPosProto, &EnumFuncGenerator::genLabelProto,
     885                        &EnumFuncGenerator::genValueProto, &EnumFuncGenerator::genSuccProto,
     886                        &EnumFuncGenerator::genPredProto
     887                        // ,&EnumFuncGenerator::genSuccPosProto,
     888                        // &EnumFuncGenerator::genPredPosProto
     889                };
     890                for ( auto & generator : attrProtos ) {
     891                        produceForwardDecl( (this->*generator)() );
     892                }
     893        }
     894}
     895
     896void EnumFuncGenerator::genPosFunctions() {
     897        if ( decl->base ) {
     898                ast::FunctionDecl * succ = genSuccPredFunc( true );
     899                ast::FunctionDecl * pred = genSuccPredFunc( false );
     900                produceDecl( succ );
     901                produceDecl( pred );
     902        }
     903
     904}
     905
    761906void TypeFuncGenerator::genFieldCtors() {
    762907        // Opaque types do not have field constructors.
  • src/Validate/GenericParameter.cpp

    r4e08a54 rda87eaf  
    289289                return new ast::TypeExpr( expr->location,
    290290                        new ast::ArrayType(
    291                                 new ast::BasicType( ast::BasicKind::Char ),
     291                                new ast::BasicType( ast::BasicType::Char ),
    292292                                expr,
    293293                                ast::VariableLen,
  • src/Validate/ReplacePseudoFunc.cpp

    r4e08a54 rda87eaf  
    1717namespace {
    1818
     19std::set<std::string> queryLabels;
     20std::set<std::string> queryValues;
     21
     22struct ReplaceEnumInstWithPos final : public ast::WithShortCircuiting {
     23    const ast::ObjectDecl* postvisit(const ast::ObjectDecl* decl) {
     24        auto enumInst = decl->type.strict_as<ast::EnumInstType>();
     25        auto enumPos = new ast::EnumPosType(enumInst);
     26        auto ret = ast::mutate_field(decl, &ast::ObjectDecl::type, enumPos);
     27        ret = ast::mutate_field(ret, &ast::ObjectDecl::mangleName,
     28                                Mangle::mangle(ret));
     29        return ret;
     30    }
     31};
     32
     33const inline std::string getValueArrayName(std::string enumName) {
     34    return "values_" + enumName;
     35}
     36
     37// struct AutoInit {
     38//     ast::EnumDecl const* postvisit( const ast::EnumDecl* expr );
     39// };
     40
     41struct WrapEnumValueExpr final : public ast::WithShortCircuiting,
     42                                 public ast::WithSymbolTable,
     43                                 public ast::WithConstTranslationUnit {
     44    void previsit(const ast::DeclStmt* expr);
     45    void previsit(const ast::ApplicationExpr* expr);
     46    void previsit(const ast::CastExpr* expr);
     47    void previsit(const ast::VariableExpr*) { visit_children = false; }
     48
     49    ast::Expr const* postvisit(const ast::VariableExpr* expr);
     50};
     51
     52struct FindGenEnumArray final : public ast::WithShortCircuiting {
     53    void previsit(const ast::ApplicationExpr* enumDecl);
     54};
     55
     56struct PseudoFuncGenerateRoutine final : public ast::WithDeclsToAdd<>,
     57                                         public ast::WithSymbolTable,
     58                                         public ast::WithShortCircuiting,
     59                                         public ast::WithConstTranslationUnit {
     60    void previsit(const ast::EnumDecl* enumDecl);
     61};
     62
     63struct ReplacePseudoFuncCore : public ast::WithShortCircuiting,
     64                               public ast::WithSymbolTable,
     65                               public ast::WithConstTranslationUnit {
     66    ast::Expr const* postvisit(ast::ApplicationExpr const* decl);
     67};
     68
     69// ast::EnumDecl const * AutoInit::postvisit( const ast::EnumDecl * expr ) {
     70//     for ( size_t i = 0; i < expr->members.size(); i++ ) {
     71//         auto mem = expr->members[i].as<ast::ObjectDecl>();
     72//         assert( mem );
     73//         if ( mem->init )
     74//     }
     75//     return expr;
     76// }
     77
     78void WrapEnumValueExpr::previsit(const ast::ApplicationExpr* expr) {
     79    auto varExpr = expr->func.as<ast::VariableExpr>();
     80    auto fname = ast::getFunctionName(expr);
     81    if (!varExpr || varExpr->var->linkage == ast::Linkage::Intrinsic) {
     82        if (fname == "?{}" || fname == "?=?") visit_children = false;
     83    }
     84
     85    if (fname == "labelE" || fname == "valueE" || fname == "posE" ||
     86        fname == "pred" || fname == "succ") {
     87        visit_children = false;
     88    }
     89}
     90
     91void WrapEnumValueExpr::previsit(const ast::DeclStmt*) {
     92    visit_children = false;
     93}
     94
     95void WrapEnumValueExpr::previsit(const ast::CastExpr* expr) {
     96    if (expr->result && expr->result.as<ast::ReferenceType>()) {
     97        visit_children = false;
     98    }
     99}
     100
     101ast::Expr const* WrapEnumValueExpr::postvisit(const ast::VariableExpr* expr) {
     102    if (!expr->result) {
     103        return expr;
     104    }
     105    if (auto enumInst = expr->result.as<ast::EnumInstType>()) {
     106        if (enumInst->base && enumInst->base->base) {
     107            auto untyped = new ast::UntypedExpr(
     108                expr->location, new ast::NameExpr(expr->location, "valueE"),
     109                {std::move(expr)});
     110            ResolvExpr::ResolveContext context{symtab, transUnit().global};
     111            auto result = ResolvExpr::findVoidExpression(untyped, context);
     112            ast::ptr<ast::ApplicationExpr> ret =
     113                result.strict_as<ast::ApplicationExpr>();
     114            return ast::deepCopy(ret);
     115        }
     116    }
     117    return expr;
     118}
     119
     120void FindGenEnumArray::previsit(const ast::ApplicationExpr* expr) {
     121    auto fname = ast::getFunctionName(expr);
     122    if (fname == "labelE" || fname == "valueE") {
     123        if (expr->args.size() != 1) {
     124            SemanticError(expr, "Position Expression only take one parameter");
     125        }
     126        const ast::VariableExpr* arg =
     127            expr->args.front().as<const ast::VariableExpr>();
     128        if (!arg) {
     129            SemanticError(expr, "Unimplement Pseudo Function Cases");
     130        }
     131        const ast::ObjectDecl* argAsVar = arg->var.as<const ast::ObjectDecl>();
     132        const std::string referredName = argAsVar->name;
     133        const ast::EnumInstType* argType =
     134            argAsVar->type.as<const ast::EnumInstType>();
     135        if (!argType) {
     136            SemanticError(
     137                argAsVar,
     138                "Position can only be used on an enumeration instance");
     139        }
     140        ast::ptr<ast::EnumDecl> base = argType->base;
     141        assert(base);
     142        if (fname == "labelE") queryLabels.insert(base->name);
     143        if (fname == "valueE") queryValues.insert(base->name);
     144    }
     145}
     146
     147const ast::Init* getAutoInit(const CodeLocation& location,
     148                             const ast::Type* type,
     149                             ResolvExpr::ResolveContext context,
     150                             const ast::Init* prev) {
     151    if (auto prevInit = dynamic_cast<const ast::SingleInit*>(prev)) {
     152        auto prevInitExpr = prevInit->value;
     153        if (auto constInit = prevInitExpr.as<ast::ConstantExpr>()) {
     154            // Assume no string literal for now
     155            return new ast::SingleInit(
     156                location, ast::ConstantExpr::from_int(
     157                              location, constInit->intValue() + 1));
     158        } else {
     159            auto untypedThisInit = new ast::UntypedExpr(
     160                location, new ast::NameExpr(location, "?++"), {prevInitExpr});
     161            auto typedInit = ResolvExpr::findSingleExpression(untypedThisInit,
     162                                                              type, context);
     163            return new ast::SingleInit(location, typedInit);
     164        }
     165    }
     166    SemanticError(prev, "Auto Init a List is not implemented");
     167    return prev;
     168}
     169
     170void PseudoFuncGenerateRoutine::previsit(const ast::EnumDecl* enumDecl) {
     171    visit_children = false;
     172    const CodeLocation& location = enumDecl->location;
     173    if (enumDecl->members.size() == 0 || !enumDecl->base) return;
     174
     175    std::vector<ast::ptr<ast::Init>> inits;
     176    std::vector<ast::ptr<ast::Init>> labels;
     177    auto type = enumDecl->base;
     178
     179    for (size_t i = 0; i < enumDecl->members.size(); i++) {
     180        ast::ptr<ast::Decl> mem = enumDecl->members.at(i);
     181        auto memAsObjectDecl = mem.as<ast::ObjectDecl>();
     182        assert(memAsObjectDecl);
     183        if (memAsObjectDecl->init) {
     184            inits.emplace_back(memAsObjectDecl->init);
     185        } else {
     186            const CodeLocation& location = mem->location;
     187            if (i == 0) {
     188                inits.emplace_back(new ast::SingleInit(
     189                    location, ast::ConstantExpr::from_int(mem->location, 0)));
     190            } else {
     191                inits.emplace_back(getAutoInit(
     192                    location, enumDecl->base,
     193                    ResolvExpr::ResolveContext{symtab, transUnit().global},
     194                    inits.at(i - 1).as<ast::SingleInit>()));
     195            }
     196        }
     197        labels.emplace_back(new ast::SingleInit(
     198            location, ast::ConstantExpr::from_string(location, mem->name)));
     199    }
     200    if (queryValues.count(enumDecl->name)) {
     201        auto init = new ast::ListInit(location, std::move(inits));
     202        const ast::ArrayType* arrT = new ast::ArrayType(
     203            enumDecl->base,
     204            ast::ConstantExpr::from_int(location, enumDecl->members.size()),
     205            ast::LengthFlag::FixedLen, ast::DimensionFlag::DynamicDim);
     206        ast::ObjectDecl* values = new ast::ObjectDecl(
     207            location, "values_" + enumDecl->name, arrT, init,
     208            ast::Storage::Static, ast::Linkage::AutoGen);
     209        symtab.addId(values);
     210        values->mangleName = Mangle::mangle(values);
     211        declsToAddAfter.push_back(values);
     212    }
     213    if (queryLabels.count(enumDecl->name)) {
     214        auto label_strings = new ast::ListInit(location, std::move(labels));
     215        auto labels = new ast::ObjectDecl(
     216            location, "labels_" + enumDecl->name,
     217            new ast::ArrayType(
     218                new ast::PointerType(new ast::BasicType{ast::BasicType::Char}),
     219                ast::ConstantExpr::from_int(location, enumDecl->members.size()),
     220                ast::LengthFlag::FixedLen, ast::DimensionFlag::DynamicDim),
     221            label_strings, ast::Storage::Static, ast::Linkage::AutoGen);
     222        symtab.addId(labels);
     223        labels->mangleName = Mangle::mangle(labels);
     224        declsToAddAfter.push_back(labels);
     225    }
     226}
     227
     228ast::ApplicationExpr const* resolveAttributeFunctions(
     229    const CodeLocation location, ResolvExpr::ResolveContext context,
     230    const ast::VariableExpr* arg, const ast::EnumDecl* base,
     231    const std::string& name) {
     232    ast::Expr* toResolve = new ast::NameExpr(location, name + base->name);
     233    // Find the request arrary
     234    auto arr = ResolvExpr::findVoidExpression(toResolve, context);
     235    assert(arr.get());
     236    auto arrAsVar = arr.strict_as<ast::VariableExpr>();
     237    // change EnumInstType to EnumPosType to avoid recursive resolution
     238    auto argAsDecl = arg->var.as<ast::ObjectDecl>();
     239    if (argAsDecl->type.as<ast::EnumInstType>()) {
     240        ast::Pass<ReplaceEnumInstWithPos> replacer;
     241        auto rep = argAsDecl->accept(replacer);
     242        auto mutatedArg = ast::mutate_field(arg, &ast::VariableExpr::var, rep);
     243        mutatedArg = ast::mutate_field(mutatedArg, &ast::VariableExpr::result,
     244                                       mutatedArg->var->get_type());
     245        auto untyped =
     246            new ast::UntypedExpr(location, new ast::NameExpr(location, "?[?]"),
     247                                 {std::move(arrAsVar), mutatedArg});
     248        auto typedResult = ResolvExpr::findVoidExpression(untyped, context);
     249        ast::ptr<ast::ApplicationExpr> ret =
     250            typedResult.strict_as<ast::ApplicationExpr>();
     251        return ast::deepCopy(ret);
     252    } else {
     253        auto untyped =
     254            new ast::UntypedExpr(location, new ast::NameExpr(location, "?[?]"),
     255                                 {std::move(arrAsVar), arg});
     256        auto typedResult = ResolvExpr::findVoidExpression(untyped, context);
     257
     258        ast::ptr<ast::ApplicationExpr> ret =
     259            typedResult.strict_as<ast::ApplicationExpr>();
     260        return ast::deepCopy(ret);
     261    }
     262}
     263
     264ast::Expr const* ReplacePseudoFuncCore::postvisit(
     265    ast::ApplicationExpr const* expr) {
     266    auto fname = ast::getFunctionName(expr);
     267    auto location = expr->location;
     268    if (fname == "posE" || fname == "valueE" || fname == "labelE") {
     269        if (expr->args.size() != 1) {
     270            SemanticError(expr,
     271                          "Pseudo Enum Expression only take one parameter");
     272        }
     273        ast::ptr<ast::VariableExpr> arg =
     274            expr->args.front().as<const ast::VariableExpr>();
     275        if (!arg) {
     276            SemanticError(expr, "Unimplement Pseudo Function Cases");
     277        }
     278        const ast::ObjectDecl* argAsVar = arg->var.as<const ast::ObjectDecl>();
     279        const std::string referredName = argAsVar->name;
     280
     281        if (const ast::EnumInstType* argTypeAsEnumInst =
     282                argAsVar->type.as<const ast::EnumInstType>()) {
     283            const ast::EnumDecl* base = argTypeAsEnumInst->base;
     284            ResolvExpr::ResolveContext context{symtab, transUnit().global};
     285            // If resolvable as constant
     286            for (size_t i = 0; i < base->members.size(); i++) {
     287                if (base->members[i]->name == referredName) {
     288                    if (fname == "posE")
     289                        return ast::ConstantExpr::from_int(expr->location, i);
     290                    else if (fname == "labelE")
     291                        return ast::ConstantExpr::from_string(expr->location,
     292                                                              referredName);
     293                    else {
     294                        return resolveAttributeFunctions(
     295                            location, context, arg.get(), base, "values_");
     296                    }
     297                }
     298            }
     299
     300            if (fname == "labelE") {
     301                if (auto labelExpr = resolveAttributeFunctions(
     302                        location, context, arg.get(), base, "labels_")) {
     303                    return labelExpr;
     304                }
     305            } else if (fname == "valueE") {
     306                if (auto valueExpr = resolveAttributeFunctions(
     307                        location, context, arg.get(), base, "values_")) {
     308                    return valueExpr;
     309                }
     310            } else {  // it is position; replace itself
     311                return std::move(arg.get());
     312            }
     313        } else if (const ast::EnumPosType* argTypeAsPos =
     314                       argAsVar->type.as<const ast::EnumPosType>()) {
     315            const ast::EnumDecl* base = argTypeAsPos->instance->base;
     316            ResolvExpr::ResolveContext context{symtab, transUnit().global};
     317            if (fname == "labelE") {
     318                if (auto labelExpr = resolveAttributeFunctions(
     319                        location, context, arg.get(), base, "labels_")) {
     320                    return labelExpr;
     321                }
     322            } else if (fname == "valueE") {
     323                if (auto valueExpr = resolveAttributeFunctions(
     324                        location, context, arg.get(), base, "values_")) {
     325                    return valueExpr;
     326                }
     327            } else {  // it is position; replace itself
     328                return std::move(arg.get());
     329            }
     330        } else {
     331            SemanticError(argAsVar,
     332                          "Pseudo Enum Expression can only be used on an "
     333                          "enumeration instance");
     334        }
     335    }
     336    return expr;
     337}
     338
    19339ast::ptr<ast::Expr> reduceCastExpr(ast::ptr<ast::Expr> expr) {
    20340    if (auto castExpr = expr.as<ast::CastExpr>()) {
     
    37357                    if (auto enumInst =
    38358                            argAsDecl->type.as<ast::EnumInstType>()) {
    39                         auto castTo = new ast::EnumAttrType(
    40                             enumInst, ast::EnumAttribute::Posn);
     359                        auto castTo = new ast::EnumPosType(enumInst);
    41360                        auto castExpr =
    42361                            new ast::CastExpr(param->location, param, castTo);
     
    55374                            typedResult.strict_as<ast::ApplicationExpr>();
    56375                        return ast::deepCopy(ret);
    57                     } else if (argAsDecl->type.as<ast::EnumAttrType>()) {
    58                         std::cerr << "PseudoFunc: succ/pred should not be applied on EnumAttrType directly" << std::endl;
     376                    } else if (auto posType =
     377                                   argAsDecl->type.as<ast::EnumPosType>()) {
     378                        // Very nasty fix. Must be revisit
     379                        if (auto paramAsVar = param.as<ast::VariableExpr>()) {
     380                            if (paramAsVar->result.as<ast::EnumInstType>()) {
     381                                auto paramToUse = ast::mutate_field(
     382                                    paramAsVar, &ast::VariableExpr::result,
     383                                    posType);
     384                                auto untyped = new ast::UntypedExpr(
     385                                    expr->location,
     386                                    new ast::NameExpr(location,
     387                                                      fname == "succ"
     388                                                          ? "_successor_"
     389                                                          : "_predessor_"),
     390                                    {paramToUse});
     391                                ResolvExpr::ResolveContext context{
     392                                    symtab, transUnit().global};
     393                                auto typedResult =
     394                                    ResolvExpr::findVoidExpression(untyped,
     395                                                                   context);
     396                                ast::ptr<ast::ApplicationExpr> ret =
     397                                    typedResult
     398                                        .strict_as<ast::ApplicationExpr>();
     399                                return ast::deepCopy(ret);
     400                            }
     401                        }
     402                        auto untyped = new ast::UntypedExpr(
     403                            expr->location,
     404                            new ast::NameExpr(location, fname == "succ"
     405                                                            ? "_successor_"
     406                                                            : "_predessor_"),
     407                            {param});
     408                        ResolvExpr::ResolveContext context{symtab,
     409                                                           transUnit().global};
     410                        auto typedResult =
     411                            ResolvExpr::findVoidExpression(untyped, context);
     412                        ast::ptr<ast::ApplicationExpr> ret =
     413                            typedResult.strict_as<ast::ApplicationExpr>();
     414                        return ast::deepCopy(ret);
    59415                    }
    60416                }
     
    68424
    69425void replacePseudoFunc(ast::TranslationUnit& translationUnit) {
     426    ast::Pass<WrapEnumValueExpr>::run(translationUnit);
     427    ast::Pass<FindGenEnumArray>::run(translationUnit);
     428
     429    ast::Pass<PseudoFuncGenerateRoutine>::run(translationUnit);
     430    ast::Pass<ReplacePseudoFuncCore>::run(translationUnit);
     431
    70432    ast::Pass<ReplaceSuccAndPred>::run(translationUnit);
    71433}
  • src/Validate/ReplaceTypedef.cpp

    r4e08a54 rda87eaf  
    349349                // Perhaps this should be a warning instead.
    350350                translationUnit.global.sizeType =
    351                         new ast::BasicType( ast::BasicKind::LongUnsignedInt );
     351                        new ast::BasicType( ast::BasicType::LongUnsignedInt );
    352352        }
    353353}
  • src/Validate/module.mk

    r4e08a54 rda87eaf  
    5454        Validate/VerifyCtorDtorAssign.hpp \
    5555        Validate/ReplacePseudoFunc.cpp \
    56         Validate/ReplacePseudoFunc.hpp \
    57         Validate/ImplementEnumFunc.cpp \
    58         Validate/ImplementEnumFunc.hpp
     56        Validate/ReplacePseudoFunc.hpp
    5957
    6058SRCDEMANGLE += $(SRC_VALIDATE)
  • src/main.cc

    r4e08a54 rda87eaf  
    6666#include "Tuples/Tuples.h"                  // for expandMemberTuples, expan...
    6767#include "Validate/Autogen.hpp"             // for autogenerateRoutines
    68 #include "Validate/ImplementEnumFunc.hpp"   // for implementEnumFunc
     68// #include "Validate/ImplementEnumFunc.hpp"   // for implementEnumFunc
    6969#include "Validate/CompoundLiteral.hpp"     // for handleCompoundLiterals
    7070#include "Validate/EliminateTypedef.hpp"    // for eliminateTypedef
     
    333333
    334334                PASS( "Generate Autogen Routines", Validate::autogenerateRoutines, transUnit );
    335                 PASS( "Generate Enum Attributes Functions", Validate::implementEnumFunc, transUnit );
     335                // PASS( "Generate Enum Attributes Functions", Validate::implementEnumFunc, transUnit );
    336336
    337337                PASS( "Implement Actors", Concurrency::implementActors, transUnit );
     
    382382                DUMP( exprp, std::move( transUnit ) );
    383383                PASS( "Replace Pseudo Func", Validate::replacePseudoFunc, transUnit );
    384                 PASS( "Fix Init", InitTweak::fix, transUnit, buildingLibrary() ); // Here
     384                DUMP( reppseu, std::move( transUnit ) );
     385                PASS( "Fix Init", InitTweak::fix, transUnit, buildingLibrary() );
    385386                PASS( "Erase With", ResolvExpr::eraseWith, transUnit );
    386387
     
    533534        { "instgen", genericsp, true, "print AST after instantiate generics" },
    534535        { "bbox", bboxp, true, "print AST before box pass" },
    535         { "bcodegen", bcodegenp, true, "print AST before code generation" }
     536        { "bcodegen", bcodegenp, true, "print AST before code generation" },
     537        { "reppseu", reppseu, true, "print AST after replacing pseudo functions" }
    536538};
    537539enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
Note: See TracChangeset for help on using the changeset viewer.