source: src/Validate/GenericParameter.cpp @ 11df881

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since 11df881 was 11df881, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Updated documentation on pre-resolver passes, moving code to headers instead of uses. Note that some comments were just copied over, I don't know if they are accurate.

  • Property mode set to 100644
File size: 9.7 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.hpp -- 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 : Fri Apr 22 16:43:00 2022
13// Update Count     : 1
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::WithGuards {
122        const CodeLocation * locationPtr = nullptr;
123
124        void previsit( const ast::ParseNode * node ) {
125                GuardValue( locationPtr ) = &node->location;
126        }
127
128        const ast::StructInstType * previsit( const ast::StructInstType * type ) {
129                assert( locationPtr );
130                return validateGeneric( *locationPtr, type );
131        }
132
133        const ast::UnionInstType * previsit( const ast::UnionInstType * type ) {
134                assert( locationPtr );
135                return validateGeneric( *locationPtr, type );
136        }
137};
138
139// --------------------------------------------------------------------------
140
141struct TranslateDimensionCore :
142                public WithNoIdSymbolTable, public ast::WithGuards {
143
144        // SUIT: Struct- or Union- InstType
145        // Situational awareness:
146        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
147        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
148        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
149        bool nextVisitedNodeIsChildOfSUIT = false;
150        bool visitingChildOfSUIT = false;
151        void changeState_ChildOfSUIT( bool newValue ) {
152                GuardValue( visitingChildOfSUIT ) = nextVisitedNodeIsChildOfSUIT;
153                GuardValue( nextVisitedNodeIsChildOfSUIT ) = newValue;
154        }
155
156        void previsit( const ast::StructInstType * ) {
157                changeState_ChildOfSUIT( true );
158        }
159        void previsit( const ast::UnionInstType * ) {
160                changeState_ChildOfSUIT( true );
161        }
162        void previsit( const ast::Node * ) {
163                changeState_ChildOfSUIT( false );
164        }
165
166        const ast::TypeDecl * postvisit( const ast::TypeDecl * decl );
167        const ast::Expr * postvisit( const ast::DimensionExpr * expr );
168        const ast::Expr * postvisit( const ast::Expr * expr );
169        const ast::Expr * postvisit( const ast::TypeExpr * expr );
170};
171
172const ast::TypeDecl * TranslateDimensionCore::postvisit(
173                const ast::TypeDecl * decl ) {
174        if ( decl->kind == ast::TypeDecl::Dimension ) {
175                auto mutDecl = ast::mutate( decl );
176                mutDecl->kind = ast::TypeDecl::Dtype;
177                if ( !isReservedTysysIdOnlyName( mutDecl->name ) ) {
178                        mutDecl->sized = true;
179                }
180                return mutDecl;
181        }
182        return decl;
183}
184
185// Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
186// Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
187// Intertwined reality:                    array( float, N     )  -> array( float,              N        )
188//                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
189// Intertwined case 1 is not just an optimization.
190// Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
191//   forall([N]) void f( array(float, N) & );
192//   array(float, 7) a;
193//   f(a);
194const ast::Expr * TranslateDimensionCore::postvisit(
195                const ast::DimensionExpr * expr ) {
196        // Expression `expr` is an occurrence of N in LHS of above examples.
197        // Look up the name that `expr` references.
198        // If we are in a struct body, then this reference can be to an entry of
199        // the stuct's forall list.
200        // Whether or not we are in a struct body, this reference can be to an
201        // entry of a containing function's forall list.
202        // If we are in a struct body, then the stuct's forall declarations are
203        // innermost (functions don't occur in structs).
204        // Thus, a potential struct's declaration is highest priority.
205        // A struct's forall declarations are already renamed with _generic_ suffix.
206        // Try that name variant first.
207
208        std::string useName = "__" + expr->name + "_generic_";
209        ast::TypeDecl * namedParamDecl = const_cast<ast::TypeDecl *>(
210                strict_dynamic_cast<const ast::TypeDecl *, nullptr >(
211                        symtab.lookupType( useName ) ) );
212
213        if ( !namedParamDecl ) {
214                useName = expr->name;
215                namedParamDecl = const_cast<ast::TypeDecl *>( strict_dynamic_cast<const ast::TypeDecl *, nullptr >( symtab.lookupType( useName ) ) );
216        }
217
218        // Expect to find it always.
219        // A misspelled name would have been parsed as an identifier.
220        assertf( namedParamDecl, "Type-system-managed value name not found in symbol table" );
221
222        auto * refToDecl = new ast::TypeInstType( useName, namedParamDecl );
223
224        if ( visitingChildOfSUIT ) {
225                // As in postvisit( Expr * ), topmost expression needs a TypeExpr
226                // wrapper. But avoid ArrayType-Sizeof.
227                return new ast::TypeExpr( expr->location, refToDecl );
228        } else {
229                // the N occurrence is being used directly as a runtime value,
230                // if we are in a type instantiation, then the N is within a bigger value computation
231                return new ast::SizeofExpr( expr->location, refToDecl );
232        }
233}
234
235const ast::Expr * TranslateDimensionCore::postvisit(
236                const ast::Expr * expr ) {
237        // This expression is used as an argument to instantiate a type.
238        if ( visitingChildOfSUIT ) {
239                // DimensionExpr and TypeExpr should not reach here.
240                return new ast::TypeExpr( expr->location,
241                        new ast::ArrayType(
242                                new ast::BasicType( ast::BasicType::Char ),
243                                expr,
244                                ast::VariableLen,
245                                ast::DynamicDim
246                        )
247                );
248        }
249        return expr;
250}
251
252const ast::Expr * TranslateDimensionCore::postvisit(
253                const ast::TypeExpr * expr ) {
254        // Does nothing, except prevents matching ast::Expr (above).
255        return expr;
256}
257
258} // namespace
259
260void fillGenericParameters( ast::TranslationUnit & translationUnit ) {
261        ast::Pass<ValidateGenericParamsCore>::run( translationUnit );
262}
263
264void translateDimensionParameters( ast::TranslationUnit & translationUnit ) {
265        ast::Pass<TranslateDimensionCore>::run( translationUnit );
266}
267
268} // namespace Validate
269
270// Local Variables: //
271// tab-width: 4 //
272// mode: c++ //
273// compile-command: "make install" //
274// End: //
Note: See TracBrowser for help on using the repository browser.