source: src/Parser/ExpressionNode.cc @ b93c544

Last change on this file since b93c544 was 6cef439, checked in by Andrew Beach <ajbeach@…>, 3 months ago

Return 'TypeData? *' from some parse rules. Moved TypeData? construction over to that file.

  • Property mode set to 100644
File size: 28.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// ExpressionNode.cc --
8//
9// Author           : Peter A. Buhr
10// Created On       : Sat May 16 13:17:07 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Dec 14 18:57:07 2023
13// Update Count     : 1087
14//
15
16#include "ExpressionNode.h"
17
18#include <cassert>                 // for assert
19#include <stdio.h>                 // for sscanf, size_t
20#include <climits>                 // for LLONG_MAX, LONG_MAX, INT_MAX, UINT...
21#include <list>                    // for list
22#include <sstream>                 // for basic_istream::operator>>, basic_i...
23#include <string>                  // for string, operator+, operator==
24
25#include "AST/Expr.hpp"            // for NameExpr
26#include "AST/Type.hpp"            // for BaseType, SueInstType
27#include "Common/SemanticError.h"  // for SemanticError
28#include "Common/utility.h"        // for maybeMoveBuild, maybeBuild, CodeLo...
29#include "DeclarationNode.h"       // for DeclarationNode
30#include "InitializerNode.h"       // for InitializerNode
31#include "TypeData.h"              // for addType, build_basic_type, build_c...
32#include "parserutility.h"         // for notZeroExpr
33
34using namespace std;
35
36//##############################################################################
37
38// Difficult to separate extra parts of constants during lexing because actions are not allow in the middle of patterns:
39//
40//              prefix action constant action suffix
41//
42// Alternatively, breaking a pattern using BEGIN does not work if the following pattern can be empty:
43//
44//              constant BEGIN CONT ...
45//              <CONT>(...)? BEGIN 0 ... // possible empty suffix
46//
47// because the CONT rule is NOT triggered if the pattern is empty. Hence, constants are reparsed here to determine their
48// type.
49
50// static inline bool checkH( char c ) { return c == 'h' || c == 'H'; }
51// static inline bool checkZ( char c ) { return c == 'z' || c == 'Z'; }
52// static inline bool checkU( char c ) { return c == 'u' || c == 'U'; }
53static inline bool checkF( char c ) { return c == 'f' || c == 'F'; }
54static inline bool checkD( char c ) { return c == 'd' || c == 'D'; }
55static inline bool checkF80( char c ) { return c == 'w' || c == 'W'; }
56static inline bool checkF128( char c ) { return c == 'q' || c == 'Q'; }
57static inline bool checkL( char c ) { return c == 'l' || c == 'L'; }
58static inline bool checkI( char c ) { return c == 'i' || c == 'I'; }
59static inline bool checkB( char c ) { return c == 'b' || c == 'B'; }
60static inline bool checkX( char c ) { return c == 'x' || c == 'X'; }
61// static inline bool checkN( char c ) { return c == 'n' || c == 'N'; }
62
63void lnthSuffix( string & str, int & type, int & ltype ) {
64        // 'u' can appear before or after length suffix
65        string::size_type posn = str.find_last_of( "lL" );
66
67        if ( posn == string::npos ) return;                                     // no suffix
68        size_t end = str.length() - 1;
69        if ( posn == end ) { type = 3; return; }                        // no length after 'l' => long
70
71        string::size_type next = posn + 1;                                      // advance to length
72        if ( str[next] == '3' ) {                                                       // 32
73                type = ltype = 2;
74        } else if ( str[next] == '6' ) {                                        // 64
75                type = ltype = 3;
76        } else if ( str[next] == '8' ) {                                        // 8
77                type = ltype = 1;
78        } else if ( str[next] == '1' ) {
79                if ( str[next + 1] == '6' ) {                                   // 16
80                        type = ltype = 0;
81                } else {                                                                                // 128
82                        type = 5; ltype = 6;
83                } // if
84        } // if
85
86        char fix = '\0';
87        if ( str[end] == 'u' || str[end] == 'U' ) fix = str[end]; // ends with 'uU' ?
88        str.erase( posn );                                                                      // remove length suffix and possibly uU
89        if ( type == 5 ) {                                                                      // L128 does not need uU
90                end = str.length() - 1;
91                if ( str[end] == 'u' || str[end] == 'U' ) str.erase( end ); // ends with 'uU' ? remove
92        } else if ( fix != '\0' ) str += fix;                           // put 'uU' back if removed
93} // lnthSuffix
94
95void valueToType( unsigned long long int & v, bool dec, int & type, bool & Unsigned ) {
96        // use value to determine type
97        if ( v <= INT_MAX ) {                                                           // signed int
98                type = 2;
99        } else if ( v <= UINT_MAX && ! dec ) {                          // unsigned int
100                type = 2;
101                Unsigned = true;                                                                // unsigned
102        } else if ( v <= LONG_MAX ) {                                           // signed long int
103                type = 3;
104        } else if ( v <= ULONG_MAX && ( ! dec || LONG_MAX == LLONG_MAX ) ) { // signed long int
105                type = 3;
106                Unsigned = true;                                                                // unsigned long int
107        } else if ( v <= LLONG_MAX ) {                                          // signed long long int
108                type = 4;
109        } else {                                                                                        // unsigned long long int
110                type = 4;
111                Unsigned = true;                                                                // unsigned long long int
112        } // if
113} // valueToType
114
115static void scanbin( string & str, unsigned long long int & v ) {
116        v = 0;
117        size_t last = str.length() - 1;                                         // last subscript of constant
118        for ( unsigned int i = 2;; ) {                                          // ignore prefix
119                if ( str[i] == '1' ) v |= 1;
120                i += 1;
121                if ( i == last - 1 || (str[i] != '0' && str[i] != '1') ) break;
122                v <<= 1;
123        } // for
124} // scanbin
125
126ast::Expr * build_constantInteger(
127                const CodeLocation & location, string & str ) {
128        static const ast::BasicType::Kind kind[2][6] = {
129                // short (h) must be before char (hh) because shorter type has the longer suffix
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, },
132        };
133
134        static const char * lnthsInt[2][6] = {
135                { "int16_t",  "int8_t",  "int32_t",  "int64_t",  "size_t",  "uintptr_t", },
136                { "uint16_t", "uint8_t", "uint32_t", "uint64_t", "size_t",  "uintptr_t", },
137        }; // lnthsInt
138
139        string str2( "0x0" );
140        unsigned long long int v, v2 = 0;                                       // converted integral value
141        ast::Expr * ret, * ret2;
142
143        int type = -1;                                                                          // 0 => short, 1 => char, 2 => int, 3 => long int, 4 => long long int, 5 => int128
144        int ltype = -1;                                                                         // 0 => 16 bits, 1 => 8 bits, 2 => 32 bits, 3 => 64 bits, 4 => size_t, 5 => intptr, 6 => pointer
145        bool dec = true, Unsigned = false;                                      // decimal, unsigned constant
146
147        // special constants
148        if ( str == "0" ) {
149                ret = new ast::ConstantExpr( location, new ast::ZeroType(), str, 0 );
150                goto CLEANUP;
151        } // if
152        if ( str == "1" ) {
153                ret = new ast::ConstantExpr( location, new ast::OneType(), str, 1 );
154                goto CLEANUP;
155        } // if
156
157        // 'u' can appear before or after length suffix
158        if ( str.find_last_of( "uU" ) != string::npos ) Unsigned = true;
159
160        if ( isdigit( str[str.length() - 1] ) ) {                       // no suffix ?
161                lnthSuffix( str, type, ltype );                                 // could have length suffix
162        } else {
163                // At least one digit in integer constant, so safe to backup while looking for suffix.
164                // This declaration and the comma expressions in the conditions mimic
165                // the declare and check pattern allowed in later compiler versions.
166                // (Only some early compilers/C++ standards do not support it.)
167                string::size_type posn;
168                // pointer value
169                if ( posn = str.find_last_of( "pP" ), posn != string::npos ) {
170                        ltype = 5; str.erase( posn, 1 );
171                // size_t
172                } else if ( posn = str.find_last_of( "zZ" ), posn != string::npos ) {
173                        Unsigned = true; type = 2; ltype = 4; str.erase( posn, 1 );
174                // signed char
175                } else if ( posn = str.rfind( "hh" ), posn != string::npos ) {
176                        type = 1; str.erase( posn, 2 );
177                // signed char
178                } else if ( posn = str.rfind( "HH" ), posn != string::npos ) {
179                        type = 1; str.erase( posn, 2 );
180                // short
181                } else if ( posn = str.find_last_of( "hH" ), posn != string::npos ) {
182                        type = 0; str.erase( posn, 1 );
183                // int (natural number)
184                } else if ( posn = str.find_last_of( "nN" ), posn != string::npos ) {
185                        type = 2; str.erase( posn, 1 );
186                } else if ( str.rfind( "ll" ) != string::npos || str.rfind( "LL" ) != string::npos ) {
187                        type = 4;
188                } else {
189                        lnthSuffix( str, type, ltype );
190                } // if
191        } // if
192
193        // Cannot be just "0"/"1"; sscanf stops at the suffix, if any; value goes over the wall => always generate
194
195#if ! defined(__SIZEOF_INT128__)
196        if ( type == 5 ) SemanticError( yylloc, "int128 constant is not supported on this target \"%s\"", str.c_str() );
197#endif // ! __SIZEOF_INT128__
198
199        if ( str[0] == '0' ) {                                                          // radix character ?
200                dec = false;
201                if ( checkX( str[1] ) ) {                                               // hex constant ?
202                        if ( type < 5 ) {                                                       // not L128 ?
203                                sscanf( (char *)str.c_str(), "%llx", &v );
204#if defined(__SIZEOF_INT128__)
205                        } else {                                                                        // hex int128 constant
206                                unsigned int len = str.length();
207                                if ( len > (2 + 16 + 16) ) SemanticError( yylloc, "128-bit hexadecimal constant to large \"%s\"", str.c_str() );
208                                // hex digits < 2^64
209                                if ( len > (2 + 16) ) {
210                                        str2 = "0x" + str.substr( len - 16 );
211                                        sscanf( (char *)str2.c_str(), "%llx", &v2 );
212                                        str = str.substr( 0, len - 16 );
213                                } // if
214                                sscanf( (char *)str.c_str(), "%llx", &v );
215#endif // __SIZEOF_INT128__
216                        } // if
217                        //printf( "%llx %llu\n", v, v );
218                } else if ( checkB( str[1] ) ) {                                // binary constant ?
219#if defined(__SIZEOF_INT128__)
220                        unsigned int len = str.length();
221                        if ( type == 5 && len > 2 + 64 ) {
222                                if ( len > 2 + 64 + 64 ) SemanticError( yylloc, "128-bit binary constant to large \"%s\".", str.c_str() );
223                                str2 = "0b" + str.substr( len - 64 );
224                                str = str.substr( 0, len - 64 );
225                                scanbin( str2, v2 );
226                        } // if
227#endif // __SIZEOF_INT128__
228                        scanbin( str, v );
229                        //printf( "%#llx %llu\n", v, v );
230                } else {                                                                                // octal constant
231                        if ( type < 5 ) {                                                       // not L128 ?
232                                sscanf( (char *)str.c_str(), "%llo", &v );
233#if defined(__SIZEOF_INT128__)
234                        } else {                                                                        // octal int128 constant
235                                unsigned int len = str.length();
236                                if ( len > 1 + 43 || (len == 1 + 43 && str[0] > '3') ) SemanticError( yylloc, "128-bit octal constant to large \"%s\"", str.c_str() );
237                                char buf[32];
238                                if ( len <= 1 + 21 ) {                                  // value < 21 octal digitis
239                                        sscanf( (char *)str.c_str(), "%llo", &v );
240                                } else {
241                                        sscanf( &str[len - 21], "%llo", &v );
242                                        __int128 val = v;                                       // accumulate bits
243                                        str[len - 21] ='\0';                            // shorten string
244                                        sscanf( &str[len == 43 ? 1 : 0], "%llo", &v );
245                                        val |= (__int128)v << 63;                       // store bits
246                                        if ( len == 1 + 43 ) {                          // most significant 2 bits ?
247                                                str[2] = '\0';                                  // shorten string
248                                                sscanf( &str[1], "%llo", &v );  // process most significant 2 bits
249                                                val |= (__int128)v << 126;              // store bits
250                                        } // if
251                                        v = val >> 64; v2 = (uint64_t)val;      // replace octal constant with 2 hex constants
252                                        sprintf( buf, "%#llx", v2 );
253                                        str2 = buf;
254                                } // if
255                                sprintf( buf, "%#llx", v );
256                                str = buf;
257#endif // __SIZEOF_INT128__
258                        } // if
259                        //printf( "%#llo %llu\n", v, v );
260                } // if
261        } else {                                                                                        // decimal constant ?
262                if ( type < 5 ) {                                                               // not L128 ?
263                        sscanf( (char *)str.c_str(), "%llu", &v );
264#if defined(__SIZEOF_INT128__)
265                } else {                                                                                // decimal int128 constant
266                        #define P10_UINT64 10'000'000'000'000'000'000ULL // 19 zeroes
267                        unsigned int len = str.length();
268                        if ( str.length() == 39 && str > (Unsigned ? "340282366920938463463374607431768211455" : "170141183460469231731687303715884105727") )
269                                SemanticError( yylloc, "128-bit decimal constant to large \"%s\".", str.c_str() );
270                        char buf[32];
271                        if ( len <= 19 ) {                                                      // value < 19 decimal digitis
272                                sscanf( (char *)str.c_str(), "%llu", &v );
273                        } else {
274                                sscanf( &str[len - 19], "%llu", &v );
275                                __int128 val = v;                                               // accumulate bits
276                                str[len - 19] ='\0';                                    // shorten string
277                                sscanf( &str[len == 39 ? 1 : 0], "%llu", &v );
278                                val += (__int128)v * (__int128)P10_UINT64; // store bits
279                                if ( len == 39 ) {                                              // most significant 2 bits ?
280                                        str[1] = '\0';                                          // shorten string
281                                        sscanf( &str[0], "%llu", &v );          // process most significant 2 bits
282                                        val += (__int128)v * (__int128)P10_UINT64 * (__int128)P10_UINT64; // store bits
283                                } // if
284                                v = val >> 64; v2 = (uint64_t)val;              // replace decimal constant with 2 hex constants
285                                sprintf( buf, "%#llx", v2 );
286                                str2 = buf;
287                        } // if
288                        sprintf( buf, "%#llx", v );
289                        str = buf;
290#endif // __SIZEOF_INT128__
291                } // if
292                //printf( "%llu\n", v );
293        } // if
294
295        if ( type == -1 ) {                                                                     // no suffix => determine type from value size
296                valueToType( v, dec, type, Unsigned );
297        } // if
298        /* printf( "%s %llo %s %llo\n", str.c_str(), v, str2.c_str(), v2 ); */
299
300        //if ( !( 0 <= type && type <= 6 ) ) { printf( "%s %lu %d %s\n", fred.c_str(), fred.length(), type, str.c_str() ); }
301        assert( 0 <= type && type <= 6 );
302
303        // Constant type is correct for overload resolving.
304        ret = new ast::ConstantExpr( location,
305                new ast::BasicType( kind[Unsigned][type] ), str, v );
306        if ( Unsigned && type < 2 ) {                                           // hh or h, less than int ?
307                // int i = -1uh => 65535 not -1, so cast is necessary for unsigned, which unfortunately eliminates warnings for large values.
308                ret = new ast::CastExpr( location,
309                        ret,
310                        new ast::BasicType( kind[Unsigned][type] ),
311                        ast::ExplicitCast );
312        } else if ( ltype != -1 ) {                                                     // explicit length ?
313                if ( ltype == 6 ) {                                                             // int128, (int128)constant
314                        ret2 = new ast::ConstantExpr( location,
315                                new ast::BasicType( ast::BasicType::LongLongSignedInt ),
316                                str2,
317                                v2 );
318                        ret = build_compoundLiteral( location,
319                                DeclarationNode::newFromTypeData(
320                                        addType(
321                                                build_basic_type( DeclarationNode::Int128 ),
322                                                build_signedness( DeclarationNode::Unsigned ) ) ),
323                                new InitializerNode(
324                                        (new InitializerNode( new ExpressionNode( v2 == 0 ? ret2 : ret ) ))->set_last( new InitializerNode( new ExpressionNode( v2 == 0 ? ret : ret2 ) ) ), true )
325                        );
326                } else {                                                                                // explicit length, (length_type)constant
327                        ret = new ast::CastExpr( location,
328                                ret,
329                                new ast::TypeInstType( lnthsInt[Unsigned][ltype], ast::TypeDecl::Dtype ),
330                                ast::ExplicitCast );
331                        if ( ltype == 5 ) {                                                     // pointer, intptr( (uintptr_t)constant )
332                                ret = build_func( location,
333                                        new ExpressionNode(
334                                                build_varref( location, new string( "intptr" ) ) ),
335                                        new ExpressionNode( ret ) );
336                        } // if
337                } // if
338        } // if
339
340  CLEANUP: ;
341        delete &str;                                                                            // created by lex
342        return ret;
343} // build_constantInteger
344
345
346static inline void checkFnxFloat( string & str, size_t last, bool & explnth, int & type ) {
347        string::size_type posn;
348        // floating-point constant has minimum of 2 characters, 1. or .1, so safe to look ahead
349        if ( str[1] == 'x' ) {                                                          // hex ?
350                posn = str.find_last_of( "pP" );                                // back for exponent (must have)
351                posn = str.find_first_of( "fF", posn + 1 );             // forward for size (fF allowed in hex constant)
352        } else {
353                posn = str.find_last_of( "fF" );                                // back for size (fF not allowed)
354        } // if
355  if ( posn == string::npos ) return;
356        explnth = true;
357        posn += 1;                                                                                      // advance to size
358        if ( str[posn] == '3' ) {                                                       // 32
359                if ( str[last] != 'x' ) type = 6;
360                else type = 7;
361        } else if ( str[posn] == '6' ) {                                        // 64
362                if ( str[last] != 'x' ) type = 8;
363                else type = 9;
364        } else if ( str[posn] == '8' ) {                                        // 80
365                type = 3;
366        } else if ( str[posn] == '1' ) {                                        // 16/128
367                if ( str[posn + 1] == '6' ) {                                   // 16
368                        type = 5;
369                } else {                                                                                // 128
370                        if ( str[last] != 'x' ) type = 10;
371                        else type = 11;
372                } // if
373        } else {
374                assertf( false, "internal error, bad floating point length %s", str.c_str() );
375        } // if
376} // checkFnxFloat
377
378
379ast::Expr * build_constantFloat(
380                const CodeLocation & location, string & str ) {
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 },
384        };
385
386        // floating-point constant has minimum of 2 characters 1. or .1
387        size_t last = str.length() - 1;
388        double v;
389        int type;                                                                                       // 0 => float, 1 => double, 3 => long double, ...
390        bool complx = false;                                                            // real, complex
391        bool explnth = false;                                                           // explicit literal length
392
393        sscanf( str.c_str(), "%lg", &v );
394
395        if ( checkI( str[last] ) ) {                                            // imaginary ?
396                complx = true;
397                last -= 1;                                                                              // backup one character
398        } // if
399
400        if ( checkF( str[last] ) ) {                                            // float ?
401                type = 0;
402        } else if ( checkD( str[last] ) ) {                                     // double ?
403                type = 1;
404        } else if ( checkL( str[last] ) ) {                                     // long double ?
405                type = 2;
406        } else if ( checkF80( str[last] ) ) {                           // __float80 ?
407                type = 3;
408        } else if ( checkF128( str[last] ) ) {                          // __float128 ?
409                type = 4;
410        } else {
411                type = 1;                                                                               // double (default if no suffix)
412                checkFnxFloat( str, last, explnth, type );
413        } // if
414
415        if ( ! complx && checkI( str[last - 1] ) ) {            // imaginary ?
416                complx = true;
417        } // if
418
419        assert( 0 <= type && type < 12 );
420        ast::Expr * ret = new ast::ConstantExpr( location,
421                new ast::BasicType( kind[complx][type] ),
422                str,
423                v );
424        // explicit length ?
425        if ( explnth ) {
426                ret = new ast::CastExpr( location,
427                        ret,
428                        new ast::BasicType( kind[complx][type] ),
429                        ast::ExplicitCast );
430        } // if
431
432        delete &str;                                                                            // created by lex
433        return ret;
434} // build_constantFloat
435
436static void sepString( string & str, string & units, char delimit ) {
437        string::size_type posn = str.find_last_of( delimit ) + 1;
438        if ( posn != str.length() ) {
439                units = "?" + str.substr( posn );                               // extract units
440                str.erase( posn );                                                              // remove units
441        } // if
442} // sepString
443
444ast::Expr * build_constantChar( const CodeLocation & location, string & str ) {
445        string units;                                                                           // units
446        sepString( str, units, '\'' );                                          // separate constant from units
447
448        ast::Expr * ret = new ast::ConstantExpr( location,
449                new ast::BasicType( ast::BasicType::Char ),
450                str,
451                (unsigned long long int)(unsigned char)str[1] );
452        if ( units.length() != 0 ) {
453                ret = new ast::UntypedExpr( location,
454                        new ast::NameExpr( location, units ),
455                        { ret } );
456        } // if
457
458        delete &str;                                                                            // created by lex
459        return ret;
460} // build_constantChar
461
462ast::Expr * build_constantStr(
463                const CodeLocation & location,
464                string & str ) {
465        assert( str.length() > 0 );
466        string units;                                                                           // units
467        sepString( str, units, '"' );                                           // separate constant from units
468
469        ast::Type * strtype;
470        switch ( str[0] ) {                                                                     // str has >= 2 characters, i.e, null string "" => safe to look at subscripts 0/1
471        case 'u':
472                if ( str[1] == '8' ) goto Default;                              // utf-8 characters => array of char
473                // lookup type of associated typedef
474                strtype = new ast::TypeInstType( "char16_t", ast::TypeDecl::Dtype );
475                break;
476        case 'U':
477                strtype = new ast::TypeInstType( "char32_t", ast::TypeDecl::Dtype );
478                break;
479        case 'L':
480                strtype = new ast::TypeInstType( "wchar_t", ast::TypeDecl::Dtype );
481                break;
482        Default:                                                                                        // char default string type
483        default:
484                strtype = new ast::BasicType( ast::BasicType::Char );
485        } // switch
486        ast::ArrayType * at = new ast::ArrayType(
487                strtype,
488                // Length is adjusted: +1 for '\0' and -2 for '"'
489                ast::ConstantExpr::from_ulong( location, str.size() + 1 - 2 ),
490                ast::FixedLen,
491                ast::DynamicDim );
492        ast::Expr * ret = new ast::ConstantExpr( location, at, str, std::nullopt );
493        if ( units.length() != 0 ) {
494                ret = new ast::UntypedExpr( location,
495                        new ast::NameExpr( location, units ),
496                        { ret } );
497        } // if
498
499        delete &str;                                                                            // created by lex
500        return ret;
501} // build_constantStr
502
503ast::Expr * build_field_name_FLOATING_FRACTIONconstant(
504                const CodeLocation & location, const string & str ) {
505        if ( str.find_first_not_of( "0123456789", 1 ) != string::npos ) SemanticError( yylloc, "invalid tuple index \"%s\".", str.c_str() );
506        ast::Expr * ret = build_constantInteger( location,
507                *new string( str.substr(1) ) );
508        delete &str;
509        return ret;
510} // build_field_name_FLOATING_FRACTIONconstant
511
512ast::Expr * build_field_name_FLOATING_DECIMALconstant(
513                const CodeLocation & location, const string & str ) {
514        if ( str[str.size() - 1] != '.' ) SemanticError( yylloc, "invalid tuple index \"%s\".", str.c_str() );
515        ast::Expr * ret = build_constantInteger(
516                location, *new string( str.substr( 0, str.size()-1 ) ) );
517        delete &str;
518        return ret;
519} // build_field_name_FLOATING_DECIMALconstant
520
521ast::Expr * build_field_name_FLOATINGconstant( const CodeLocation & location,
522                const string & str ) {
523        // str is of the form A.B -> separate at the . and return member expression
524        int a, b;
525        char dot;
526        stringstream ss( str );
527        ss >> a >> dot >> b;
528        auto ret = new ast::UntypedMemberExpr( location,
529                ast::ConstantExpr::from_int( location, b ),
530                ast::ConstantExpr::from_int( location, a )
531        );
532        delete &str;
533        return ret;
534} // build_field_name_FLOATINGconstant
535
536ast::Expr * make_field_name_fraction_constants( const CodeLocation & location,
537                ast::Expr * fieldName,
538                ast::Expr * fracts ) {
539        if ( nullptr == fracts ) {
540                return fieldName;
541        } else if ( auto memberExpr = dynamic_cast<ast::UntypedMemberExpr *>( fracts ) ) {
542                memberExpr->member = make_field_name_fraction_constants( location,
543                        fieldName,
544                        ast::mutate( memberExpr->aggregate.get() ) );
545                return memberExpr;
546        } else {
547                return new ast::UntypedMemberExpr( location, fracts, fieldName );
548        } // if
549} // make_field_name_fraction_constants
550
551ast::Expr * build_field_name_fraction_constants( const CodeLocation & location,
552                ast::Expr * fieldName,
553                ExpressionNode * fracts ) {
554        return make_field_name_fraction_constants( location, fieldName, maybeMoveBuild( fracts ) );
555} // build_field_name_fraction_constants
556
557ast::NameExpr * build_varref( const CodeLocation & location,
558                const string * name ) {
559        ast::NameExpr * expr = new ast::NameExpr( location, *name );
560        delete name;
561        return expr;
562} // build_varref
563
564ast::QualifiedNameExpr * build_qualified_expr( const CodeLocation & location,
565                const DeclarationNode * decl_node,
566                const ast::NameExpr * name ) {
567        ast::Decl * newDecl = maybeBuild( decl_node );
568        if ( ast::DeclWithType * newDeclWithType = dynamic_cast<ast::DeclWithType *>( newDecl ) ) {
569                if ( const ast::Type * t = newDeclWithType->get_type() ) {
570                        if ( auto typeInst = dynamic_cast<const ast::TypeInstType *>( t ) ) {
571                                newDecl = new ast::EnumDecl( location, typeInst->name );
572                        }
573                }
574        }
575        return new ast::QualifiedNameExpr( location, newDecl, name->name );
576}
577
578ast::QualifiedNameExpr * build_qualified_expr( const CodeLocation & location,
579                const ast::EnumDecl * decl,
580                const ast::NameExpr * name ) {
581        return new ast::QualifiedNameExpr( location, decl, name->name );
582}
583
584ast::DimensionExpr * build_dimensionref( const CodeLocation & location,
585                const string * name ) {
586        ast::DimensionExpr * expr = new ast::DimensionExpr( location, *name );
587        delete name;
588        return expr;
589} // build_varref
590
591// TODO: get rid of this and OperKinds and reuse code from OperatorTable
592static const char * OperName[] = {                                              // must harmonize with OperKinds
593        // diadic
594        "SizeOf", "AlignOf", "OffsetOf", "?+?", "?-?", "?\\?", "?*?", "?/?", "?%?", "||", "&&",
595        "?|?", "?&?", "?^?", "Cast", "?<<?", "?>>?", "?<?", "?>?", "?<=?", "?>=?", "?==?", "?!=?",
596        "?=?", "?@=?", "?\\=?", "?*=?", "?/=?", "?%=?", "?+=?", "?-=?", "?<<=?", "?>>=?", "?&=?", "?^=?", "?|=?",
597        "?[?]", "...",
598        // monadic
599        "+?", "-?", "AddressOf", "*?", "!?", "~?", "++?", "?++", "--?", "?--",
600}; // OperName
601
602ast::Expr * build_cast( const CodeLocation & location,
603                DeclarationNode * decl_node,
604                ExpressionNode * expr_node,
605                ast::CastExpr::CastKind kind ) {
606        ast::Type * targetType = maybeMoveBuildType( decl_node );
607        if ( dynamic_cast<ast::VoidType *>( targetType ) ) {
608                delete targetType;
609                return new ast::CastExpr( location,
610                        maybeMoveBuild( expr_node ),
611                        ast::ExplicitCast, kind );
612        } else {
613                return new ast::CastExpr( location,
614                        maybeMoveBuild( expr_node ),
615                        targetType,
616                        ast::ExplicitCast, kind );
617        } // if
618} // build_cast
619
620ast::Expr * build_keyword_cast( const CodeLocation & location,
621                ast::AggregateDecl::Aggregate target,
622                ExpressionNode * expr_node ) {
623        return new ast::KeywordCastExpr( location,
624                maybeMoveBuild( expr_node ),
625                target
626        );
627}
628
629ast::Expr * build_virtual_cast( const CodeLocation & location,
630                DeclarationNode * decl_node,
631                ExpressionNode * expr_node ) {
632        return new ast::VirtualCastExpr( location,
633                maybeMoveBuild( expr_node ),
634                maybeMoveBuildType( decl_node )
635        );
636} // build_virtual_cast
637
638ast::Expr * build_fieldSel( const CodeLocation & location,
639                ExpressionNode * expr_node,
640                ast::Expr * member ) {
641        return new ast::UntypedMemberExpr( location,
642                member,
643                maybeMoveBuild( expr_node )
644        );
645} // build_fieldSel
646
647ast::Expr * build_pfieldSel( const CodeLocation & location,
648                ExpressionNode * expr_node,
649                ast::Expr * member ) {
650        auto deref = new ast::UntypedExpr( location,
651                new ast::NameExpr( location, "*?" )
652        );
653        deref->location = expr_node->location;
654        deref->args.push_back( maybeMoveBuild( expr_node ) );
655        auto ret = new ast::UntypedMemberExpr( location, member, deref );
656        return ret;
657} // build_pfieldSel
658
659ast::Expr * build_offsetOf( const CodeLocation & location,
660                DeclarationNode * decl_node,
661                ast::NameExpr * member ) {
662        ast::Expr * ret = new ast::UntypedOffsetofExpr( location,
663                maybeMoveBuildType( decl_node ),
664                member->name
665        );
666        ret->result = new ast::BasicType( ast::BasicType::LongUnsignedInt );
667        delete member;
668        return ret;
669} // build_offsetOf
670
671ast::Expr * build_and_or( const CodeLocation & location,
672                ExpressionNode * expr_node1,
673                ExpressionNode * expr_node2,
674                ast::LogicalFlag flag ) {
675        return new ast::LogicalExpr( location,
676                maybeMoveBuild( expr_node1 ),
677                maybeMoveBuild( expr_node2 ),
678                flag
679        );
680} // build_and_or
681
682ast::Expr * build_unary_val( const CodeLocation & location,
683                OperKinds op,
684                ExpressionNode * expr_node ) {
685        std::vector<ast::ptr<ast::Expr>> args;
686        args.push_back( maybeMoveBuild( expr_node ) );
687        return new ast::UntypedExpr( location,
688                new ast::NameExpr( location, OperName[ (int)op ] ),
689                std::move( args )
690        );
691} // build_unary_val
692
693ast::Expr * build_binary_val( const CodeLocation & location,
694                OperKinds op,
695                ExpressionNode * expr_node1,
696                ExpressionNode * expr_node2 ) {
697        std::vector<ast::ptr<ast::Expr>> args;
698        args.push_back( maybeMoveBuild( expr_node1 ) );
699        args.push_back( maybeMoveBuild( expr_node2 ) );
700        return new ast::UntypedExpr( location,
701                new ast::NameExpr( location, OperName[ (int)op ] ),
702                std::move( args )
703        );
704} // build_binary_val
705
706ast::Expr * build_cond( const CodeLocation & location,
707                ExpressionNode * expr_node1,
708                ExpressionNode * expr_node2,
709                ExpressionNode * expr_node3 ) {
710        return new ast::ConditionalExpr( location,
711                maybeMoveBuild( expr_node1 ),
712                maybeMoveBuild( expr_node2 ),
713                maybeMoveBuild( expr_node3 )
714        );
715} // build_cond
716
717ast::Expr * build_tuple( const CodeLocation & location,
718                ExpressionNode * expr_node ) {
719        std::vector<ast::ptr<ast::Expr>> exprs;
720        buildMoveList( expr_node, exprs );
721        return new ast::UntypedTupleExpr( location, std::move( exprs ) );
722} // build_tuple
723
724ast::Expr * build_func( const CodeLocation & location,
725                ExpressionNode * function,
726                ExpressionNode * expr_node ) {
727        std::vector<ast::ptr<ast::Expr>> args;
728        buildMoveList( expr_node, args );
729        return new ast::UntypedExpr( location,
730                maybeMoveBuild( function ),
731                std::move( args )
732        );
733} // build_func
734
735ast::Expr * build_compoundLiteral( const CodeLocation & location,
736                DeclarationNode * decl_node,
737                InitializerNode * kids ) {
738        // compound literal type
739        ast::Decl * newDecl = maybeBuild( decl_node );
740        // non-sue compound-literal type
741        if ( ast::DeclWithType * newDeclWithType = dynamic_cast<ast::DeclWithType *>( newDecl ) ) {
742                return new ast::CompoundLiteralExpr( location,
743                        newDeclWithType->get_type(),
744                        maybeMoveBuild( kids ) );
745        // these types do not have associated type information
746        } else if ( auto newDeclStructDecl = dynamic_cast<ast::StructDecl *>( newDecl ) ) {
747                if ( newDeclStructDecl->body ) {
748                        return new ast::CompoundLiteralExpr( location,
749                                new ast::StructInstType( newDeclStructDecl ),
750                                maybeMoveBuild( kids ) );
751                } else {
752                        return new ast::CompoundLiteralExpr( location,
753                                new ast::StructInstType( newDeclStructDecl->name ),
754                                maybeMoveBuild( kids ) );
755                } // if
756        } else if ( auto newDeclUnionDecl = dynamic_cast<ast::UnionDecl *>( newDecl )  ) {
757                if ( newDeclUnionDecl->body ) {
758                        return new ast::CompoundLiteralExpr( location,
759                                new ast::UnionInstType( newDeclUnionDecl ),
760                                maybeMoveBuild( kids ) );
761                } else {
762                        return new ast::CompoundLiteralExpr( location,
763                                new ast::UnionInstType( newDeclUnionDecl->name ),
764                                maybeMoveBuild( kids ) );
765                } // if
766        } else if ( auto newDeclEnumDecl = dynamic_cast<ast::EnumDecl *>( newDecl )  ) {
767                if ( newDeclEnumDecl->body ) {
768                        return new ast::CompoundLiteralExpr( location,
769                                new ast::EnumInstType( newDeclEnumDecl ),
770                                maybeMoveBuild( kids ) );
771                } else {
772                        return new ast::CompoundLiteralExpr( location,
773                                new ast::EnumInstType( newDeclEnumDecl->name ),
774                                maybeMoveBuild( kids ) );
775                } // if
776        } else {
777                assert( false );
778        } // if
779} // build_compoundLiteral
780
781// Local Variables: //
782// tab-width: 4 //
783// End: //
Note: See TracBrowser for help on using the repository browser.