source: src/Validate/GenericParameter.cpp @ 251ce80

ast-experimental
Last change on this file since 251ce80 was bccd70a, checked in by Andrew Beach <ajbeach@…>, 12 months ago

Removed internal code from TypeSubstitution? header. It caused a chain of include problems, which have been corrected.

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