source: src/Parser/ExpressionNode.cc @ 9dcb653

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 9dcb653 was e612146c, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

third attempt at user-defined literals

  • Property mode set to 100644
File size: 18.7 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 : Sun Sep  3 22:21:21 2017
13// Update Count     : 639
14//
15
16#include <cassert>                 // for assert
17#include <stdio.h>                 // for sscanf, size_t
18#include <climits>                 // for LLONG_MAX, LONG_MAX, INT_MAX, UINT...
19#include <list>                    // for list
20#include <sstream>                 // for basic_istream::operator>>, basic_i...
21#include <string>                  // for string, operator+, operator==
22
23#include "Common/SemanticError.h"  // for SemanticError
24#include "Common/utility.h"        // for maybeMoveBuild, maybeBuild, CodeLo...
25#include "ParseNode.h"             // for ExpressionNode, maybeMoveBuildType
26#include "SynTree/Constant.h"      // for Constant
27#include "SynTree/Declaration.h"   // for EnumDecl, StructDecl, UnionDecl
28#include "SynTree/Expression.h"    // for Expression, ConstantExpr, NameExpr
29#include "SynTree/Statement.h"     // for CompoundStmt, Statement
30#include "SynTree/Type.h"          // for BasicType, Type, Type::Qualifiers
31#include "parserutility.h"         // for notZeroExpr
32
33class Initializer;
34
35using namespace std;
36
37//##############################################################################
38
39// Difficult to separate extra parts of constants during lexing because actions are not allow in the middle of patterns:
40//
41//              prefix action constant action suffix
42//
43// Alternatively, breaking a pattern using BEGIN does not work if the following pattern can be empty:
44//
45//              constant BEGIN CONT ...
46//              <CONT>(...)? BEGIN 0 ... // possible empty suffix
47//
48// because the CONT rule is NOT triggered if the pattern is empty. Hence, constants are reparsed here to determine their
49// type.
50
51extern const Type::Qualifiers noQualifiers;             // no qualifiers on constants
52
53static inline bool checkU( char c ) { return c == 'u' || c == 'U'; }
54static inline bool checkL( char c ) { return c == 'l' || c == 'L'; }
55static inline bool checkF( char c ) { return c == 'f' || c == 'F'; }
56static inline bool checkD( char c ) { return c == 'd' || c == 'D'; }
57static inline bool checkI( char c ) { return c == 'i' || c == 'I'; }
58static inline bool checkX( char c ) { return c == 'x' || c == 'X'; }
59
60static void sepNumeric( string & str, string & units ) {
61        string::size_type posn = str.find_first_of( "`" );
62        if ( posn != string::npos ) {
63                units = "?" + str.substr( posn );                               // extract units
64                str.erase( posn );                                                              // remove units
65        } // if
66} // sepNumeric
67
68Expression * build_constantInteger( string & str ) {
69        static const BasicType::Kind kind[2][3] = {
70                { BasicType::SignedInt, BasicType::LongSignedInt, BasicType::LongLongSignedInt },
71                { BasicType::UnsignedInt, BasicType::LongUnsignedInt, BasicType::LongLongUnsignedInt },
72        };
73
74        string units;                                                                           // units
75        sepNumeric( str, units );                                                       // separate constant from units
76
77        bool dec = true, Unsigned = false;                                      // decimal, unsigned constant
78        int size;                                                                                       // 0 => int, 1 => long, 2 => long long
79        unsigned long long int v;                                                       // converted integral value
80        size_t last = str.length() - 1;                                         // last character of constant
81        Expression * ret;
82
83        // ROB: what do we do with units on 0 and 1?
84        // special constants
85        if ( str == "0" ) {
86                ret = new ConstantExpr( Constant( (Type *)new ZeroType( noQualifiers ), str, (unsigned long long int)0 ) );
87                goto CLEANUP;
88        } // if
89        if ( str == "1" ) {
90                ret = new ConstantExpr( Constant( (Type *)new OneType( noQualifiers ), str, (unsigned long long int)1 ) );
91                goto CLEANUP;
92        } // if
93
94        if ( str[0] == '0' ) {                                                          // octal/hex constant ?
95                dec = false;
96                if ( last != 0 && checkX( str[1] ) ) {                  // hex constant ?
97                        sscanf( (char *)str.c_str(), "%llx", &v );
98                        //printf( "%llx %llu\n", v, v );
99                } else {                                                                                // octal constant
100                        sscanf( (char *)str.c_str(), "%llo", &v );
101                        //printf( "%llo %llu\n", v, v );
102                } // if
103        } else {                                                                                        // decimal constant ?
104                sscanf( (char *)str.c_str(), "%llu", &v );
105                //printf( "%llu %llu\n", v, v );
106        } // if
107
108        if ( v <= INT_MAX ) {                                                           // signed int
109                size = 0;
110        } else if ( v <= UINT_MAX && ! dec ) {                          // unsigned int
111                size = 0;
112                Unsigned = true;                                                                // unsigned
113        } else if ( v <= LONG_MAX ) {                                           // signed long int
114                size = 1;
115        } else if ( v <= ULONG_MAX && ( ! dec || LONG_MAX == LLONG_MAX ) ) { // signed long int
116                size = 1;
117                Unsigned = true;                                                                // unsigned long int
118        } else if ( v <= LLONG_MAX ) {                                          // signed long long int
119                size = 2;
120        } else {                                                                                        // unsigned long long int
121                size = 2;
122                Unsigned = true;                                                                // unsigned long long int
123        } // if
124
125        if ( checkU( str[last] ) ) {                                            // suffix 'u' ?
126                Unsigned = true;
127                if ( last > 0 && checkL( str[last - 1] ) ) {    // suffix 'l' ?
128                        size = 1;
129                        if ( last > 1 && checkL( str[last - 2] ) ) { // suffix 'll' ?
130                                size = 2;
131                        } // if
132                } // if
133        } else if ( checkL( str[ last ] ) ) {                           // suffix 'l' ?
134                size = 1;
135                if ( last > 0 && checkL( str[last - 1] ) ) {    // suffix 'll' ?
136                        size = 2;
137                        if ( last > 1 && checkU( str[last - 2] ) ) { // suffix 'u' ?
138                                Unsigned = true;
139                        } // if
140                } else {
141                        if ( last > 0 && checkU( str[last - 1] ) ) { // suffix 'u' ?
142                                Unsigned = true;
143                        } // if
144                } // if
145        } // if
146
147        ret = new ConstantExpr( Constant( new BasicType( noQualifiers, kind[Unsigned][size] ), str, v ) );
148  CLEANUP:
149        if ( units.length() != 0 ) {
150                ret = new UntypedExpr( new NameExpr( units ), { ret } );
151        } // if
152
153        delete &str;                                                                            // created by lex
154        return ret;
155} // build_constantInteger
156
157Expression * build_constantFloat( string & str ) {
158        static const BasicType::Kind kind[2][3] = {
159                { BasicType::Float, BasicType::Double, BasicType::LongDouble },
160                { BasicType::FloatComplex, BasicType::DoubleComplex, BasicType::LongDoubleComplex },
161        };
162
163        string units;                                                                           // units
164        sepNumeric( str, units );                                                       // separate constant from units
165
166        bool complx = false;                                                            // real, complex
167        int size = 1;                                                                           // 0 => float, 1 => double (default), 2 => long double
168        // floating-point constant has minimum of 2 characters: 1. or .1
169        size_t last = str.length() - 1;
170        double v;
171
172        sscanf( str.c_str(), "%lg", &v );
173
174        if ( checkI( str[last] ) ) {                                            // imaginary ?
175                complx = true;
176                last -= 1;                                                                              // backup one character
177        } // if
178
179        if ( checkF( str[last] ) ) {                                            // float ?
180                size = 0;
181        } else if ( checkD( str[last] ) ) {                                     // double ?
182                size = 1;
183        } else if ( checkL( str[last] ) ) {                                     // long double ?
184                size = 2;
185        } // if
186        if ( ! complx && checkI( str[last - 1] ) ) {            // imaginary ?
187                complx = true;
188        } // if
189
190        Expression * ret = new ConstantExpr( Constant( new BasicType( noQualifiers, kind[complx][size] ), str, v ) );
191        if ( units.length() != 0 ) {
192                ret = new UntypedExpr( new NameExpr( units ), { ret } );
193        } // if
194
195        delete &str;                                                                            // created by lex
196        return ret;
197} // build_constantFloat
198
199static void sepString( string & str, string & units, char delimit ) {
200        string::size_type posn = str.find_last_of( delimit ) + 1;
201        if ( posn != str.length() ) {
202                units = "?" + str.substr( posn );                               // extract units
203                str.erase( posn );                                                              // remove units
204        } // if
205} // sepString
206
207Expression * build_constantChar( string & str ) {
208        string units;                                                                           // units
209        sepString( str, units, '\'' );                                          // separate constant from units
210
211        Expression * ret = new ConstantExpr( Constant( new BasicType( noQualifiers, BasicType::Char ), str, (unsigned long long int)(unsigned char)str[1] ) );
212        if ( units.length() != 0 ) {
213                ret = new UntypedExpr( new NameExpr( units ), { ret } );
214        } // if
215
216        delete &str;                                                                            // created by lex
217        return ret;
218} // build_constantChar
219
220Expression * build_constantStr( string & str ) {
221        string units;                                                                           // units
222        sepString( str, units, '"' );                                           // separate constant from units
223
224        BasicType::Kind strtype = BasicType::Char;                      // default string type
225        switch ( str[0] ) {                                                                     // str has >= 2 characters, i.e, null string ""
226          case 'u':
227                if ( str[1] == '8' ) break;                                             // utf-8 characters
228                strtype = BasicType::ShortUnsignedInt;
229                break;
230          case 'U':
231                strtype = BasicType::UnsignedInt;
232                break;
233          case 'L':
234                strtype = BasicType::SignedInt;
235                break;
236        } // switch
237        ArrayType * at = new ArrayType( noQualifiers, new BasicType( Type::Qualifiers( Type::Const ), strtype ),
238                                                                        new ConstantExpr( Constant::from_ulong( str.size() + 1 - 2 ) ), // +1 for '\0' and -2 for '"'
239                                                                        false, false );
240        Expression * ret = new ConstantExpr( Constant( at, str, (unsigned long long int)0 ) ); // constant 0 is ignored for pure string value
241        if ( units.length() != 0 ) {
242                ret = new UntypedExpr( new NameExpr( units ), { ret } );
243        } // if
244
245        delete &str;                                                                            // created by lex
246        return ret;
247} // build_constantStr
248
249Expression * build_field_name_FLOATINGconstant( const string & str ) {
250        // str is of the form A.B -> separate at the . and return member expression
251        int a, b;
252        char dot;
253        stringstream ss( str );
254        ss >> a >> dot >> b;
255        UntypedMemberExpr * ret = new UntypedMemberExpr( new ConstantExpr( Constant::from_int( b ) ), new ConstantExpr( Constant::from_int( a ) ) );
256        delete &str;
257        return ret;
258} // build_field_name_FLOATINGconstant
259
260Expression * make_field_name_fraction_constants( Expression * fieldName, Expression * fracts ) {
261        if ( fracts ) {
262                if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * >( fracts ) ) {
263                        memberExpr->set_member( make_field_name_fraction_constants( fieldName, memberExpr->get_aggregate() ) );
264                        return memberExpr;
265                } else {
266                        return new UntypedMemberExpr( fracts, fieldName );
267                } // if
268        } // if
269        return fieldName;
270} // make_field_name_fraction_constants
271
272Expression * build_field_name_fraction_constants( Expression * fieldName, ExpressionNode * fracts ) {
273        return make_field_name_fraction_constants( fieldName, maybeMoveBuild< Expression >( fracts ) );
274} // build_field_name_fraction_constants
275
276Expression * build_field_name_REALFRACTIONconstant( const string & str ) {
277        if ( str.find_first_not_of( "0123456789", 1 ) != string::npos ) throw SemanticError( "invalid tuple index " + str );
278        Expression * ret = build_constantInteger( *new string( str.substr(1) ) );
279        delete &str;
280        return ret;
281} // build_field_name_REALFRACTIONconstant
282
283Expression * build_field_name_REALDECIMALconstant( const string & str ) {
284        if ( str[str.size()-1] != '.' ) throw SemanticError( "invalid tuple index " + str );
285        Expression * ret = build_constantInteger( *new string( str.substr( 0, str.size()-1 ) ) );
286        delete &str;
287        return ret;
288} // build_field_name_REALDECIMALconstant
289
290NameExpr * build_varref( const string * name ) {
291        NameExpr * expr = new NameExpr( *name, nullptr );
292        delete name;
293        return expr;
294} // build_varref
295
296// TODO: get rid of this and OperKinds and reuse code from OperatorTable
297static const char * OperName[] = {                                              // must harmonize with OperKinds
298        // diadic
299        "SizeOf", "AlignOf", "OffsetOf", "?+?", "?-?", "?\\?", "?*?", "?/?", "?%?", "||", "&&",
300        "?|?", "?&?", "?^?", "Cast", "?<<?", "?>>?", "?<?", "?>?", "?<=?", "?>=?", "?==?", "?!=?",
301        "?=?", "?@=?", "?\\=?", "?*=?", "?/=?", "?%=?", "?+=?", "?-=?", "?<<=?", "?>>=?", "?&=?", "?^=?", "?|=?",
302        "?[?]", "...",
303        // monadic
304        "+?", "-?", "AddressOf", "*?", "!?", "~?", "++?", "?++", "--?", "?--",
305}; // OperName
306
307Expression * build_cast( DeclarationNode * decl_node, ExpressionNode * expr_node ) {
308        Type * targetType = maybeMoveBuildType( decl_node );
309        if ( dynamic_cast< VoidType * >( targetType ) ) {
310                delete targetType;
311                return new CastExpr( maybeMoveBuild< Expression >(expr_node) );
312        } else {
313                return new CastExpr( maybeMoveBuild< Expression >(expr_node), targetType );
314        } // if
315} // build_cast
316
317Expression * build_virtual_cast( DeclarationNode * decl_node, ExpressionNode * expr_node ) {
318        Type * targetType = maybeMoveBuildType( decl_node );
319        Expression * castArg = maybeMoveBuild< Expression >( expr_node );
320        return new VirtualCastExpr( castArg, targetType );
321} // build_virtual_cast
322
323Expression * build_fieldSel( ExpressionNode * expr_node, Expression * member ) {
324        UntypedMemberExpr * ret = new UntypedMemberExpr( member, maybeMoveBuild< Expression >(expr_node) );
325        return ret;
326} // build_fieldSel
327
328Expression * build_pfieldSel( ExpressionNode * expr_node, Expression * member ) {
329        UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
330        deref->location = expr_node->location;
331        deref->get_args().push_back( maybeMoveBuild< Expression >(expr_node) );
332        UntypedMemberExpr * ret = new UntypedMemberExpr( member, deref );
333        return ret;
334} // build_pfieldSel
335
336Expression * build_addressOf( ExpressionNode * expr_node ) {
337                return new AddressExpr( maybeMoveBuild< Expression >(expr_node) );
338} // build_addressOf
339
340Expression * build_sizeOfexpr( ExpressionNode * expr_node ) {
341        return new SizeofExpr( maybeMoveBuild< Expression >(expr_node) );
342} // build_sizeOfexpr
343
344Expression * build_sizeOftype( DeclarationNode * decl_node ) {
345        return new SizeofExpr( maybeMoveBuildType( decl_node ) );
346} // build_sizeOftype
347
348Expression * build_alignOfexpr( ExpressionNode * expr_node ) {
349        return new AlignofExpr( maybeMoveBuild< Expression >(expr_node) );
350} // build_alignOfexpr
351
352Expression * build_alignOftype( DeclarationNode * decl_node ) {
353        return new AlignofExpr( maybeMoveBuildType( decl_node) );
354} // build_alignOftype
355
356Expression * build_offsetOf( DeclarationNode * decl_node, NameExpr * member ) {
357        Expression * ret = new UntypedOffsetofExpr( maybeMoveBuildType( decl_node ), member->get_name() );
358        delete member;
359        return ret;
360} // build_offsetOf
361
362Expression * build_and_or( ExpressionNode * expr_node1, ExpressionNode * expr_node2, bool kind ) {
363        return new LogicalExpr( notZeroExpr( maybeMoveBuild< Expression >(expr_node1) ), notZeroExpr( maybeMoveBuild< Expression >(expr_node2) ), kind );
364} // build_and_or
365
366Expression * build_unary_val( OperKinds op, ExpressionNode * expr_node ) {
367        list< Expression * > args;
368        args.push_back( maybeMoveBuild< Expression >(expr_node) );
369        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
370} // build_unary_val
371
372Expression * build_unary_ptr( OperKinds op, ExpressionNode * expr_node ) {
373        list< Expression * > args;
374        args.push_back(  maybeMoveBuild< Expression >(expr_node) ); // xxx -- this is exactly the same as the val case now, refactor this code.
375        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
376} // build_unary_ptr
377
378Expression * build_binary_val( OperKinds op, ExpressionNode * expr_node1, ExpressionNode * expr_node2 ) {
379        list< Expression * > args;
380        args.push_back( maybeMoveBuild< Expression >(expr_node1) );
381        args.push_back( maybeMoveBuild< Expression >(expr_node2) );
382        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
383} // build_binary_val
384
385Expression * build_binary_ptr( OperKinds op, ExpressionNode * expr_node1, ExpressionNode * expr_node2 ) {
386        list< Expression * > args;
387        args.push_back( maybeMoveBuild< Expression >(expr_node1) );
388        args.push_back( maybeMoveBuild< Expression >(expr_node2) );
389        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
390} // build_binary_ptr
391
392Expression * build_cond( ExpressionNode * expr_node1, ExpressionNode * expr_node2, ExpressionNode * expr_node3 ) {
393        return new ConditionalExpr( notZeroExpr( maybeMoveBuild< Expression >(expr_node1) ), maybeMoveBuild< Expression >(expr_node2), maybeMoveBuild< Expression >(expr_node3) );
394} // build_cond
395
396Expression * build_comma( ExpressionNode * expr_node1, ExpressionNode * expr_node2 ) {
397        return new CommaExpr( maybeMoveBuild< Expression >(expr_node1), maybeMoveBuild< Expression >(expr_node2) );
398} // build_comma
399
400Expression * build_attrexpr( NameExpr * var, ExpressionNode * expr_node ) {
401        return new AttrExpr( var, maybeMoveBuild< Expression >(expr_node) );
402} // build_attrexpr
403
404Expression * build_attrtype( NameExpr * var, DeclarationNode * decl_node ) {
405        return new AttrExpr( var, maybeMoveBuildType( decl_node ) );
406} // build_attrtype
407
408Expression * build_tuple( ExpressionNode * expr_node ) {
409        list< Expression * > exprs;
410        buildMoveList( expr_node, exprs );
411        return new UntypedTupleExpr( exprs );;
412} // build_tuple
413
414Expression * build_func( ExpressionNode * function, ExpressionNode * expr_node ) {
415        list< Expression * > args;
416        buildMoveList( expr_node, args );
417        return new UntypedExpr( maybeMoveBuild< Expression >(function), args, nullptr );
418} // build_func
419
420Expression * build_range( ExpressionNode * low, ExpressionNode * high ) {
421        return new RangeExpr( maybeMoveBuild< Expression >( low ), maybeMoveBuild< Expression >( high ) );
422} // build_range
423
424Expression * build_asmexpr( ExpressionNode * inout, Expression * constraint, ExpressionNode * operand ) {
425        return new AsmExpr( maybeMoveBuild< Expression >( inout ), constraint, maybeMoveBuild< Expression >(operand) );
426} // build_asmexpr
427
428Expression * build_valexpr( StatementNode * s ) {
429        return new StmtExpr( dynamic_cast< CompoundStmt * >(maybeMoveBuild< Statement >(s) ) );
430} // build_valexpr
431
432Expression * build_typevalue( DeclarationNode * decl ) {
433        return new TypeExpr( maybeMoveBuildType( decl ) );
434} // build_typevalue
435
436Expression * build_compoundLiteral( DeclarationNode * decl_node, InitializerNode * kids ) {
437        Declaration * newDecl = maybeBuild< Declaration >(decl_node); // compound literal type
438        if ( DeclarationWithType * newDeclWithType = dynamic_cast< DeclarationWithType * >( newDecl ) ) { // non-sue compound-literal type
439                return new CompoundLiteralExpr( newDeclWithType->get_type(), maybeMoveBuild< Initializer >(kids) );
440        // these types do not have associated type information
441        } else if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( newDecl )  ) {
442                if ( newDeclStructDecl->has_body() ) {
443                        return new CompoundLiteralExpr( new StructInstType( Type::Qualifiers(), newDeclStructDecl ), maybeMoveBuild< Initializer >(kids) );
444                } else {
445                        return new CompoundLiteralExpr( new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
446                } // if
447        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( newDecl )  ) {
448                if ( newDeclUnionDecl->has_body() ) {
449                        return new CompoundLiteralExpr( new UnionInstType( Type::Qualifiers(), newDeclUnionDecl ), maybeMoveBuild< Initializer >(kids) );
450                } else {
451                        return new CompoundLiteralExpr( new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
452                } // if
453        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( newDecl )  ) {
454                if ( newDeclEnumDecl->has_body() ) {
455                        return new CompoundLiteralExpr( new EnumInstType( Type::Qualifiers(), newDeclEnumDecl ), maybeMoveBuild< Initializer >(kids) );
456                } else {
457                        return new CompoundLiteralExpr( new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
458                } // if
459        } else {
460                assert( false );
461        } // if
462} // build_compoundLiteral
463
464// Local Variables: //
465// tab-width: 4 //
466// mode: c++ //
467// compile-command: "make install" //
468// End: //
Note: See TracBrowser for help on using the repository browser.