source: src/Validate/GenericParameter.cpp @ 0bd46fd

ADTast-experimentalpthread-emulation
Last change on this file since 0bd46fd was e9e9f56, checked in by Andrew Beach <ajbeach@…>, 20 months ago

Used the WithCodeLocation? helper in more passes. This cleans up some code and should improve efficiency.

  • Property mode set to 100644
File size: 9.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2018 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// GenericParameter.cpp -- Generic parameter related passes.
8//
9// Author           : Andrew Beach
10// Created On       : Fri Mar 21 10:02:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Sep 20 16:28:00 2022
13// Update Count     : 2
14//
15
16#include "GenericParameter.hpp"
17
18#include "AST/Decl.hpp"
19#include "AST/Expr.hpp"
20#include "AST/ParseNode.hpp"
21#include "AST/Pass.hpp"
22#include "AST/TranslationUnit.hpp"
23#include "AST/Type.hpp"
24#include "Validate/NoIdSymbolTable.hpp"
25
26namespace Validate {
27
28namespace {
29
30// Test for special name on a generic parameter.  Special treatment for the
31// special name is a bootstrapping hack.  In most cases, the worlds of T's
32// and of N's don't overlap (normal treamtemt).  The foundations in
33// array.hfa use tagging for both types and dimensions.  Tagging treats
34// its subject parameter even more opaquely than T&, which assumes it is
35// possible to have a pointer/reference to such an object.  Tagging only
36// seeks to identify the type-system resident at compile time.  Both N's
37// and T's can make tags.  The tag definition uses the special name, which
38// is treated as "an N or a T."  This feature is not inteded to be used
39// outside of the definition and immediate uses of a tag.
40inline bool isReservedTysysIdOnlyName( const std::string & name ) {
41        // The name might be wrapped in __..._generic so check for that as well.
42        int foundAt = name.find("__CFA_tysys_id_only");
43        if (foundAt == 0) return true;
44        if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
45        return false;
46}
47
48template< typename InstType >
49const InstType * validateGeneric(
50                const CodeLocation & location, const InstType * type ) {
51        const typename InstType::base_type * base = type->base.get();
52        if ( nullptr == base ) {
53                return type;
54        }
55
56        const std::vector<ast::ptr<ast::TypeDecl>> & params = base->params;
57        if ( params.empty() ) {
58                return type;
59        }
60
61        // I think I can move this check up, or it should check the result of
62        // the substuition.
63
64        auto mutType = ast::mutate( type );
65        std::vector<ast::ptr<ast::Expr>> & args = mutType->params;
66
67        // Quick check before we get into the real work.
68        if ( params.size() < args.size() ) {
69                SemanticError( location, type, "Too many type arguments in generic type " );
70        }
71
72        // Insert defaults arguments when a type argument is missing (currently
73        // only supports missing arguments at the end of the list).
74        // A substitution is used to ensure that defaults are replaced correctly:
75        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
76        //   vector(int) v;
77        // After insertion of default values becomes:
78        //   vector(int, heap_allocator(T))
79        // The substitution is built with T=int so the result is:
80        //   vector(int, heap_allocator(int))
81
82        ast::TypeSubstitution sub;
83        // Build the substution:
84        auto paramIter = params.begin();
85        auto argIter = args.begin();
86        for ( ; paramIter != params.end() ; ++paramIter, ++argIter ) {
87                if ( argIter != args.end() ) {
88                        if ( auto expr = argIter->as<ast::TypeExpr>() ) {
89                                sub.add( paramIter->get(), ast::deepCopy( expr->type ) );
90                        }
91                } else if ( const ast::Type * defaultType = (*paramIter)->init ) {
92                        args.push_back( new ast::TypeExpr(
93                                location, ast::deepCopy( defaultType ) ) );
94                        sub.add( paramIter->get(), ast::deepCopy( defaultType ) );
95                        argIter = std::prev( args.end() );
96                } else {
97                        SemanticError( location, type, "Too few type arguments in generic type " );
98                }
99                assert( argIter != args.end() );
100                bool typeParamDeclared = (*paramIter)->kind != ast::TypeDecl::Dimension;
101                bool typeArgGiven;
102                if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
103                        // Always match when declaration is reserved name, means "either".
104                        typeArgGiven = typeParamDeclared;
105                } else {
106                        typeArgGiven = argIter->as<ast::TypeExpr>();
107                }
108                if ( !typeParamDeclared && typeArgGiven ) {
109                        SemanticError( location, type, "Type argument given for value parameter: " );
110                }
111                if ( typeParamDeclared && !typeArgGiven ) {
112                        SemanticError( location, type, "Expression argument given for type parameter: " );
113                }
114        }
115
116        // Actually do the application:
117        auto result = sub.apply( mutType );
118        return result.node.release();
119}
120
121struct ValidateGenericParamsCore : public ast::WithCodeLocation {
122        const ast::StructInstType * previsit( const ast::StructInstType * type ) {
123                assert( location );
124                return validateGeneric( *location, type );
125        }
126
127        const ast::UnionInstType * previsit( const ast::UnionInstType * type ) {
128                assert( location );
129                return validateGeneric( *location, type );
130        }
131};
132
133// --------------------------------------------------------------------------
134
135struct TranslateDimensionCore :
136                public WithNoIdSymbolTable, public ast::WithGuards {
137
138        // SUIT: Struct- or Union- InstType
139        // Situational awareness:
140        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
141        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
142        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
143        bool nextVisitedNodeIsChildOfSUIT = false;
144        bool visitingChildOfSUIT = false;
145        void changeState_ChildOfSUIT( bool newValue ) {
146                GuardValue( visitingChildOfSUIT ) = nextVisitedNodeIsChildOfSUIT;
147                GuardValue( nextVisitedNodeIsChildOfSUIT ) = newValue;
148        }
149
150        void previsit( const ast::StructInstType * ) {
151                changeState_ChildOfSUIT( true );
152        }
153        void previsit( const ast::UnionInstType * ) {
154                changeState_ChildOfSUIT( true );
155        }
156        void previsit( const ast::Node * ) {
157                changeState_ChildOfSUIT( false );
158        }
159
160        const ast::TypeDecl * postvisit( const ast::TypeDecl * decl );
161        const ast::Expr * postvisit( const ast::DimensionExpr * expr );
162        const ast::Expr * postvisit( const ast::Expr * expr );
163        const ast::Expr * postvisit( const ast::TypeExpr * expr );
164};
165
166const ast::TypeDecl * TranslateDimensionCore::postvisit(
167                const ast::TypeDecl * decl ) {
168        if ( decl->kind == ast::TypeDecl::Dimension ) {
169                auto mutDecl = ast::mutate( decl );
170                mutDecl->kind = ast::TypeDecl::Dtype;
171                if ( !isReservedTysysIdOnlyName( mutDecl->name ) ) {
172                        mutDecl->sized = true;
173                }
174                return mutDecl;
175        }
176        return decl;
177}
178
179// Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
180// Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
181// Intertwined reality:                    array( float, N     )  -> array( float,              N        )
182//                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
183// Intertwined case 1 is not just an optimization.
184// Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
185//   forall([N]) void f( array(float, N) & );
186//   array(float, 7) a;
187//   f(a);
188const ast::Expr * TranslateDimensionCore::postvisit(
189                const ast::DimensionExpr * expr ) {
190        // Expression `expr` is an occurrence of N in LHS of above examples.
191        // Look up the name that `expr` references.
192        // If we are in a struct body, then this reference can be to an entry of
193        // the stuct's forall list.
194        // Whether or not we are in a struct body, this reference can be to an
195        // entry of a containing function's forall list.
196        // If we are in a struct body, then the stuct's forall declarations are
197        // innermost (functions don't occur in structs).
198        // Thus, a potential struct's declaration is highest priority.
199        // A struct's forall declarations are already renamed with _generic_ suffix.
200        // Try that name variant first.
201
202        std::string useName = "__" + expr->name + "_generic_";
203        ast::TypeDecl * namedParamDecl = const_cast<ast::TypeDecl *>(
204                strict_dynamic_cast<const ast::TypeDecl *, nullptr >(
205                        symtab.lookupType( useName ) ) );
206
207        if ( !namedParamDecl ) {
208                useName = expr->name;
209                namedParamDecl = const_cast<ast::TypeDecl *>( strict_dynamic_cast<const ast::TypeDecl *, nullptr >( symtab.lookupType( useName ) ) );
210        }
211
212        // Expect to find it always.
213        // A misspelled name would have been parsed as an identifier.
214        assertf( namedParamDecl, "Type-system-managed value name not found in symbol table" );
215
216        auto * refToDecl = new ast::TypeInstType( useName, namedParamDecl );
217
218        if ( visitingChildOfSUIT ) {
219                // As in postvisit( Expr * ), topmost expression needs a TypeExpr
220                // wrapper. But avoid ArrayType-Sizeof.
221                return new ast::TypeExpr( expr->location, refToDecl );
222        } else {
223                // the N occurrence is being used directly as a runtime value,
224                // if we are in a type instantiation, then the N is within a bigger value computation
225                return new ast::SizeofExpr( expr->location, refToDecl );
226        }
227}
228
229const ast::Expr * TranslateDimensionCore::postvisit(
230                const ast::Expr * expr ) {
231        // This expression is used as an argument to instantiate a type.
232        if ( visitingChildOfSUIT ) {
233                // DimensionExpr and TypeExpr should not reach here.
234                return new ast::TypeExpr( expr->location,
235                        new ast::ArrayType(
236                                new ast::BasicType( ast::BasicType::Char ),
237                                expr,
238                                ast::VariableLen,
239                                ast::DynamicDim
240                        )
241                );
242        }
243        return expr;
244}
245
246const ast::Expr * TranslateDimensionCore::postvisit(
247                const ast::TypeExpr * expr ) {
248        // Does nothing, except prevents matching ast::Expr (above).
249        return expr;
250}
251
252} // namespace
253
254void fillGenericParameters( ast::TranslationUnit & translationUnit ) {
255        ast::Pass<ValidateGenericParamsCore>::run( translationUnit );
256}
257
258void translateDimensionParameters( ast::TranslationUnit & translationUnit ) {
259        ast::Pass<TranslateDimensionCore>::run( translationUnit );
260}
261
262} // namespace Validate
263
264// Local Variables: //
265// tab-width: 4 //
266// mode: c++ //
267// compile-command: "make install" //
268// End: //
Note: See TracBrowser for help on using the repository browser.