source: src/Parser/ExpressionNode.cc @ 76c62b2

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 76c62b2 was 76c62b2, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

first attempt at user-defined constants (units)

  • Property mode set to 100644
File size: 18.4 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           : Rodolfo G. Esteves
10// Created On       : Sat May 16 13:17:07 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Aug 31 21:05:04 2017
13// Update Count     : 605
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( std::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//      if ( units.length() == 0 ) {
148                ret = new ConstantExpr( Constant( new BasicType( noQualifiers, kind[Unsigned][size] ), str, v ) );
149//      } else {
150//              // ROB: generate call to units routine
151//              ret = nullptr;
152//      } // if
153  CLEANUP:
154        delete &str;                                                                            // created by lex
155        return ret;
156} // build_constantInteger
157
158Expression * build_constantFloat( std::string & str ) {
159        static const BasicType::Kind kind[2][3] = {
160                { BasicType::Float, BasicType::Double, BasicType::LongDouble },
161                { BasicType::FloatComplex, BasicType::DoubleComplex, BasicType::LongDoubleComplex },
162        };
163
164        string units;                                                                           // units
165        sepNumeric( str, units );                                                       // separate constant from units
166
167        bool complx = false;                                                            // real, complex
168        int size = 1;                                                                           // 0 => float, 1 => double (default), 2 => long double
169        // floating-point constant has minimum of 2 characters: 1. or .1
170        size_t last = str.length() - 1;
171        double v;
172
173        sscanf( str.c_str(), "%lg", &v );
174
175        if ( checkI( str[last] ) ) {                                            // imaginary ?
176                complx = true;
177                last -= 1;                                                                              // backup one character
178        } // if
179
180        if ( checkF( str[last] ) ) {                                            // float ?
181                size = 0;
182        } else if ( checkD( str[last] ) ) {                                     // double ?
183                size = 1;
184        } else if ( checkL( str[last] ) ) {                                     // long double ?
185                size = 2;
186        } // if
187        if ( ! complx && checkI( str[last - 1] ) ) {            // imaginary ?
188                complx = true;
189        } // if
190
191        Expression * ret;
192//      if ( units.length() == 0 ) {
193                ret = new ConstantExpr( Constant( new BasicType( noQualifiers, kind[complx][size] ), str, v ) );
194//      } else {
195//              ret = nullptr;
196//              // ROB: generate call to units routine
197//      } // if
198
199        delete &str;                                                                            // created by lex
200        return ret;
201} // build_constantFloat
202
203static void sepString( string & str, string & units, char delimit ) {
204        string::size_type posn = str.find_last_of( delimit ) + 1;
205        if ( posn != str.length() ) {
206                units = str.substr( posn );                                             // extract units
207                str.erase( posn );                                                              // remove units
208        } // if
209} // sepString
210
211Expression * build_constantChar( std::string & str ) {
212        string units;                                                                           // units
213        sepString( str, units, '\'' );                                          // separate constant from units
214
215        Expression * ret;
216//      if ( units.length() == 0 ) {
217                ret = new ConstantExpr( Constant( new BasicType( noQualifiers, BasicType::Char ), str, (unsigned long long int)(unsigned char)str[1] ) );
218//      } else {
219//              ret = nullptr;
220//              // ROB: generate call to units routine
221//      } // if
222
223        delete &str;                                                                            // created by lex
224        return ret;
225} // build_constantChar
226
227ConstantExpr * build_constantStr( std::string & str ) {
228        string units;                                                                           // units
229        sepString( str, units, '"' );                                           // separate constant from units
230
231        ConstantExpr * ret;
232//      if ( units.length() == 0 ) {
233                // string should probably be a primitive type
234                ArrayType * at = new ArrayType( noQualifiers, new BasicType( Type::Qualifiers( Type::Const ), BasicType::Char ),
235                                                                                new ConstantExpr( Constant::from_ulong( str.size() + 1 - 2 ) ), // +1 for '\0' and -2 for '"'
236                                                                                false, false );
237                ret = new ConstantExpr( Constant( at, str, (unsigned long long int)0 ) ); // constant 0 is ignored for pure string value
238//      } else {
239//              ret = nullptr;
240//              // ROB: generate call to units routine
241//      } // if
242               
243        delete &str;                                                                            // created by lex
244        return ret;
245} // build_constantStr
246
247Expression * build_field_name_FLOATINGconstant( const std::string & str ) {
248        // str is of the form A.B -> separate at the . and return member expression
249        int a, b;
250        char dot;
251        std::stringstream ss( str );
252        ss >> a >> dot >> b;
253        UntypedMemberExpr * ret = new UntypedMemberExpr( new ConstantExpr( Constant::from_int( b ) ), new ConstantExpr( Constant::from_int( a ) ) );
254        delete &str;
255        return ret;
256} // build_field_name_FLOATINGconstant
257
258Expression * make_field_name_fraction_constants( Expression * fieldName, Expression * fracts ) {
259        if ( fracts ) {
260                if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * >( fracts ) ) {
261                        memberExpr->set_member( make_field_name_fraction_constants( fieldName, memberExpr->get_aggregate() ) );
262                        return memberExpr;
263                } else {
264                        return new UntypedMemberExpr( fracts, fieldName );
265                }
266        }
267        return fieldName;
268} // make_field_name_fraction_constants
269
270Expression * build_field_name_fraction_constants( Expression * fieldName, ExpressionNode * fracts ) {
271        return make_field_name_fraction_constants( fieldName, maybeMoveBuild< Expression >( fracts ) );
272} // build_field_name_fraction_constants
273
274Expression * build_field_name_REALFRACTIONconstant( const std::string & str ) {
275        if ( str.find_first_not_of( "0123456789", 1 ) != string::npos ) throw SemanticError( "invalid tuple index " + str );
276        Expression * ret = build_constantInteger( *new std::string( str.substr(1) ) );
277        delete &str;
278        return ret;
279} // build_field_name_REALFRACTIONconstant
280
281Expression * build_field_name_REALDECIMALconstant( const std::string & str ) {
282        if ( str[str.size()-1] != '.' ) throw SemanticError( "invalid tuple index " + str );
283        Expression * ret = build_constantInteger( *new std::string( str.substr( 0, str.size()-1 ) ) );
284        delete &str;
285        return ret;
286} // build_field_name_REALDECIMALconstant
287
288NameExpr * build_varref( const string * name ) {
289        NameExpr * expr = new NameExpr( *name, nullptr );
290        delete name;
291        return expr;
292} // build_varref
293
294
295static const char * OperName[] = {                                              // must harmonize with OperKinds
296        // diadic
297        "SizeOf", "AlignOf", "OffsetOf", "?+?", "?-?", "?\\?", "?*?", "?/?", "?%?", "||", "&&",
298        "?|?", "?&?", "?^?", "Cast", "?<<?", "?>>?", "?<?", "?>?", "?<=?", "?>=?", "?==?", "?!=?",
299        "?=?", "?@=?", "?\\=?", "?*=?", "?/=?", "?%=?", "?+=?", "?-=?", "?<<=?", "?>>=?", "?&=?", "?^=?", "?|=?",
300        "?[?]", "...",
301        // monadic
302        "+?", "-?", "AddressOf", "*?", "!?", "~?", "++?", "?++", "--?", "?--", "&&"
303}; // OperName
304
305Expression * build_cast( DeclarationNode * decl_node, ExpressionNode * expr_node ) {
306        Type * targetType = maybeMoveBuildType( decl_node );
307        if ( dynamic_cast< VoidType * >( targetType ) ) {
308                delete targetType;
309                return new CastExpr( maybeMoveBuild< Expression >(expr_node) );
310        } else {
311                return new CastExpr( maybeMoveBuild< Expression >(expr_node), targetType );
312        } // if
313} // build_cast
314
315Expression * build_virtual_cast( DeclarationNode * decl_node, ExpressionNode * expr_node ) {
316        Type * targetType = maybeMoveBuildType( decl_node );
317        Expression * castArg = maybeMoveBuild< Expression >( expr_node );
318        return new VirtualCastExpr( castArg, targetType );
319} // build_virtual_cast
320
321Expression * build_fieldSel( ExpressionNode * expr_node, Expression * member ) {
322        UntypedMemberExpr * ret = new UntypedMemberExpr( member, maybeMoveBuild< Expression >(expr_node) );
323        return ret;
324} // build_fieldSel
325
326Expression * build_pfieldSel( ExpressionNode * expr_node, Expression * member ) {
327        UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
328        deref->location = expr_node->location;
329        deref->get_args().push_back( maybeMoveBuild< Expression >(expr_node) );
330        UntypedMemberExpr * ret = new UntypedMemberExpr( member, deref );
331        return ret;
332} // build_pfieldSel
333
334Expression * build_addressOf( ExpressionNode * expr_node ) {
335                return new AddressExpr( maybeMoveBuild< Expression >(expr_node) );
336} // build_addressOf
337
338Expression * build_sizeOfexpr( ExpressionNode * expr_node ) {
339        return new SizeofExpr( maybeMoveBuild< Expression >(expr_node) );
340} // build_sizeOfexpr
341
342Expression * build_sizeOftype( DeclarationNode * decl_node ) {
343        return new SizeofExpr( maybeMoveBuildType( decl_node ) );
344} // build_sizeOftype
345
346Expression * build_alignOfexpr( ExpressionNode * expr_node ) {
347        return new AlignofExpr( maybeMoveBuild< Expression >(expr_node) );
348} // build_alignOfexpr
349
350Expression * build_alignOftype( DeclarationNode * decl_node ) {
351        return new AlignofExpr( maybeMoveBuildType( decl_node) );
352} // build_alignOftype
353
354Expression * build_offsetOf( DeclarationNode * decl_node, NameExpr * member ) {
355        Expression * ret = new UntypedOffsetofExpr( maybeMoveBuildType( decl_node ), member->get_name() );
356        delete member;
357        return ret;
358} // build_offsetOf
359
360Expression * build_and_or( ExpressionNode * expr_node1, ExpressionNode * expr_node2, bool kind ) {
361        return new LogicalExpr( notZeroExpr( maybeMoveBuild< Expression >(expr_node1) ), notZeroExpr( maybeMoveBuild< Expression >(expr_node2) ), kind );
362} // build_and_or
363
364Expression * build_unary_val( OperKinds op, ExpressionNode * expr_node ) {
365        std::list< Expression * > args;
366        args.push_back( maybeMoveBuild< Expression >(expr_node) );
367        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
368} // build_unary_val
369
370Expression * build_unary_ptr( OperKinds op, ExpressionNode * expr_node ) {
371        std::list< Expression * > args;
372        args.push_back(  maybeMoveBuild< Expression >(expr_node) ); // xxx
373        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
374} // build_unary_ptr
375
376Expression * build_binary_val( OperKinds op, ExpressionNode * expr_node1, ExpressionNode * expr_node2 ) {
377        std::list< Expression * > args;
378        args.push_back( maybeMoveBuild< Expression >(expr_node1) );
379        args.push_back( maybeMoveBuild< Expression >(expr_node2) );
380        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
381} // build_binary_val
382
383Expression * build_binary_ptr( OperKinds op, ExpressionNode * expr_node1, ExpressionNode * expr_node2 ) {
384        std::list< Expression * > args;
385        args.push_back( maybeMoveBuild< Expression >(expr_node1) );
386        args.push_back( maybeMoveBuild< Expression >(expr_node2) );
387        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
388} // build_binary_ptr
389
390Expression * build_cond( ExpressionNode * expr_node1, ExpressionNode * expr_node2, ExpressionNode * expr_node3 ) {
391        return new ConditionalExpr( notZeroExpr( maybeMoveBuild< Expression >(expr_node1) ), maybeMoveBuild< Expression >(expr_node2), maybeMoveBuild< Expression >(expr_node3) );
392} // build_cond
393
394Expression * build_comma( ExpressionNode * expr_node1, ExpressionNode * expr_node2 ) {
395        return new CommaExpr( maybeMoveBuild< Expression >(expr_node1), maybeMoveBuild< Expression >(expr_node2) );
396} // build_comma
397
398Expression * build_attrexpr( NameExpr * var, ExpressionNode * expr_node ) {
399        return new AttrExpr( var, maybeMoveBuild< Expression >(expr_node) );
400} // build_attrexpr
401
402Expression * build_attrtype( NameExpr * var, DeclarationNode * decl_node ) {
403        return new AttrExpr( var, maybeMoveBuildType( decl_node ) );
404} // build_attrtype
405
406Expression * build_tuple( ExpressionNode * expr_node ) {
407        std::list< Expression * > exprs;
408        buildMoveList( expr_node, exprs );
409        return new UntypedTupleExpr( exprs );;
410} // build_tuple
411
412Expression * build_func( ExpressionNode * function, ExpressionNode * expr_node ) {
413        std::list< Expression * > args;
414        buildMoveList( expr_node, args );
415        return new UntypedExpr( maybeMoveBuild< Expression >(function), args, nullptr );
416} // build_func
417
418Expression * build_range( ExpressionNode * low, ExpressionNode * high ) {
419        return new RangeExpr( maybeMoveBuild< Expression >( low ), maybeMoveBuild< Expression >( high ) );
420} // build_range
421
422Expression * build_asmexpr( ExpressionNode * inout, ConstantExpr * constraint, ExpressionNode * operand ) {
423        return new AsmExpr( maybeMoveBuild< Expression >( inout ), constraint, maybeMoveBuild< Expression >(operand) );
424} // build_asmexpr
425
426Expression * build_valexpr( StatementNode * s ) {
427        return new StmtExpr( dynamic_cast< CompoundStmt * >(maybeMoveBuild< Statement >(s) ) );
428} // build_valexpr
429
430Expression * build_typevalue( DeclarationNode * decl ) {
431        return new TypeExpr( maybeMoveBuildType( decl ) );
432} // build_typevalue
433
434Expression * build_compoundLiteral( DeclarationNode * decl_node, InitializerNode * kids ) {
435        Declaration * newDecl = maybeBuild< Declaration >(decl_node); // compound literal type
436        if ( DeclarationWithType * newDeclWithType = dynamic_cast< DeclarationWithType * >( newDecl ) ) { // non-sue compound-literal type
437                return new CompoundLiteralExpr( newDeclWithType->get_type(), maybeMoveBuild< Initializer >(kids) );
438        // these types do not have associated type information
439        } else if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( newDecl )  ) {
440                if ( newDeclStructDecl->has_body() ) {
441                        return new CompoundLiteralExpr( new StructInstType( Type::Qualifiers(), newDeclStructDecl ), maybeMoveBuild< Initializer >(kids) );
442                } else {
443                        return new CompoundLiteralExpr( new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
444                } // if
445        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( newDecl )  ) {
446                if ( newDeclUnionDecl->has_body() ) {
447                        return new CompoundLiteralExpr( new UnionInstType( Type::Qualifiers(), newDeclUnionDecl ), maybeMoveBuild< Initializer >(kids) );
448                } else {
449                        return new CompoundLiteralExpr( new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
450                } // if
451        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( newDecl )  ) {
452                if ( newDeclEnumDecl->has_body() ) {
453                        return new CompoundLiteralExpr( new EnumInstType( Type::Qualifiers(), newDeclEnumDecl ), maybeMoveBuild< Initializer >(kids) );
454                } else {
455                        return new CompoundLiteralExpr( new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
456                } // if
457        } else {
458                assert( false );
459        } // if
460} // build_compoundLiteral
461
462// Local Variables: //
463// tab-width: 4 //
464// mode: c++ //
465// compile-command: "make install" //
466// End: //
Note: See TracBrowser for help on using the repository browser.