source: src/Validate/GenericParameter.cpp @ 1d66a91

Last change on this file since 1d66a91 was f02f546, checked in by Michael Brooks <mlbrooks@…>, 17 months ago

Implement new rules for array dimension expression matching.

Core changes:
src/ResolvExpr/Unify.cc: add sense of "these two expressions unify"
src/InitTweak/GenInit.cc: make hoisting happen more often
tests/array-container/*: reconfigure the array-dimension test to use non-"classic" expectation rules

Misc contributors and noise:
libcfa/src/parseargs.cfa: ,ake a parameter, that's used as a length expression, constant (example of an array user following new rules)
src/ResolvExpr/ResolveTypeof.h: make fixArrayType public
src/Validate/GenericParameter.cpp: do the array-type desugaring in both AST corners that forall-variables can be found (not just in one of them)
tests/.expect/typedefRedef-ERR1.txt: old one was "expecting" a bug, that new array rules handle correctly

  • Property mode set to 100644
File size: 11.4 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
121bool isSizedPolymorphic( const ast::AggregateDecl * decl ) {
122        for ( const auto & param : decl->params ) {
123                if ( param->sized ) return true;
124        }
125        return false;
126}
127
128struct ValidateGenericParamsCore :
129                public ast::WithCodeLocation, public ast::WithGuards {
130        // Generic parameter filling and checks:
131        const ast::StructInstType * previsit( const ast::StructInstType * type ) {
132                assert( location );
133                return validateGeneric( *location, type );
134        }
135
136        const ast::UnionInstType * previsit( const ast::UnionInstType * type ) {
137                assert( location );
138                return validateGeneric( *location, type );
139        }
140
141        // Check parameter and bitfield combinations:
142        bool insideSized = false;
143        void previsit( const ast::StructDecl * decl ) {
144                if ( isSizedPolymorphic( decl ) && !insideSized ) {
145                        GuardValue( insideSized ) = true;
146                }
147        }
148
149        void previsit( const ast::UnionDecl * decl ) {
150                if ( isSizedPolymorphic( decl ) && !insideSized ) {
151                        GuardValue( insideSized ) = true;
152                }
153        }
154
155        void previsit( const ast::ObjectDecl * decl ) {
156                if ( insideSized && decl->bitfieldWidth ) {
157                        SemanticError( decl->location, decl,
158                                "Cannot have bitfields inside a sized polymorphic structure." );
159                }
160        }
161};
162
163// --------------------------------------------------------------------------
164
165struct TranslateDimensionCore :
166                public WithNoIdSymbolTable, public ast::WithGuards,
167                public ast::WithVisitorRef<TranslateDimensionCore> {
168
169        // SUIT: Struct- or Union- InstType
170        // Situational awareness:
171        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
172        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
173        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
174        bool nextVisitedNodeIsChildOfSUIT = false;
175        bool visitingChildOfSUIT = false;
176        void changeState_ChildOfSUIT( bool newValue ) {
177                GuardValue( visitingChildOfSUIT ) = nextVisitedNodeIsChildOfSUIT;
178                GuardValue( nextVisitedNodeIsChildOfSUIT ) = newValue;
179        }
180
181        void previsit( const ast::StructInstType * ) {
182                changeState_ChildOfSUIT( true );
183        }
184        void previsit( const ast::UnionInstType * ) {
185                changeState_ChildOfSUIT( true );
186        }
187        void previsit( const ast::Node * ) {
188                changeState_ChildOfSUIT( false );
189        }
190
191        const ast::TypeDecl * postvisit( const ast::TypeDecl * decl );
192        const ast::Type * postvisit( const ast::FunctionType * type );
193        const ast::Type * postvisit( const ast::TypeInstType * type );
194
195        const ast::Expr * postvisit( const ast::DimensionExpr * expr );
196        const ast::Expr * postvisit( const ast::Expr * expr );
197        const ast::Expr * postvisit( const ast::TypeExpr * expr );
198};
199
200// Declaration of type variable: forall( [N] )  ->  forall( N & | sized( N ) )
201const ast::TypeDecl * TranslateDimensionCore::postvisit(
202                const ast::TypeDecl * decl ) {
203        if ( decl->kind == ast::TypeDecl::Dimension ) {
204                auto mutDecl = ast::mutate( decl );
205                mutDecl->kind = ast::TypeDecl::Dtype;
206                if ( !isReservedTysysIdOnlyName( mutDecl->name ) ) {
207                        mutDecl->sized = true;
208                }
209                return mutDecl;
210        }
211        return decl;
212}
213
214// Makes postvisit( TypeInstType ) get called on the entries of the function declaration's type's forall list.
215// Pass.impl.hpp's visit( FunctionType ) does not consider the forall entries to be child nodes.
216// Workaround is: during the current TranslateDimension pass, manually visit down there.
217const ast::Type * TranslateDimensionCore::postvisit(
218                const ast::FunctionType * type ) {
219        visitor->maybe_accept( type, &ast::FunctionType::forall );
220        return type;
221}
222
223// Use of type variable, assuming `forall( [N] )` in scope:  void (*)( foo( /*dimension*/ N ) & )  ->  void (*)( foo( /*dtype*/ N ) & )
224const ast::Type * TranslateDimensionCore::postvisit(
225                const ast::TypeInstType * type ) {
226        if ( type->kind == ast::TypeDecl::Dimension ) {
227                auto mutType = ast::mutate( type );
228                mutType->kind = ast::TypeDecl::Dtype;
229                return mutType;
230        }
231        return type;
232}
233
234// Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
235// Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
236// Intertwined reality:                    array( float, N     )  -> array( float,              N        )
237//                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
238// Intertwined case 1 is not just an optimization.
239// Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
240//   forall([N]) void f( array(float, N) & );
241//   array(float, 7) a;
242//   f(a);
243const ast::Expr * TranslateDimensionCore::postvisit(
244                const ast::DimensionExpr * expr ) {
245        // Expression `expr` is an occurrence of N in LHS of above examples.
246        // Look up the name that `expr` references.
247        // If we are in a struct body, then this reference can be to an entry of
248        // the stuct's forall list.
249        // Whether or not we are in a struct body, this reference can be to an
250        // entry of a containing function's forall list.
251        // If we are in a struct body, then the stuct's forall declarations are
252        // innermost (functions don't occur in structs).
253        // Thus, a potential struct's declaration is highest priority.
254        // A struct's forall declarations are already renamed with _generic_ suffix.
255        // Try that name variant first.
256
257        std::string useName = "__" + expr->name + "_generic_";
258        ast::TypeDecl * namedParamDecl = const_cast<ast::TypeDecl *>(
259                strict_dynamic_cast<const ast::TypeDecl *, nullptr >(
260                        symtab.lookupType( useName ) ) );
261
262        if ( !namedParamDecl ) {
263                useName = expr->name;
264                namedParamDecl = const_cast<ast::TypeDecl *>( strict_dynamic_cast<const ast::TypeDecl *, nullptr >( symtab.lookupType( useName ) ) );
265        }
266
267        // Expect to find it always.
268        // A misspelled name would have been parsed as an identifier.
269        assertf( namedParamDecl, "Type-system-managed value name not found in symbol table" );
270
271        auto * refToDecl = new ast::TypeInstType( useName, namedParamDecl );
272
273        if ( visitingChildOfSUIT ) {
274                // As in postvisit( Expr * ), topmost expression needs a TypeExpr
275                // wrapper. But avoid ArrayType-Sizeof.
276                return new ast::TypeExpr( expr->location, refToDecl );
277        } else {
278                // the N occurrence is being used directly as a runtime value,
279                // if we are in a type instantiation, then the N is within a bigger value computation
280                return new ast::SizeofExpr( expr->location, refToDecl );
281        }
282}
283
284const ast::Expr * TranslateDimensionCore::postvisit(
285                const ast::Expr * expr ) {
286        // This expression is used as an argument to instantiate a type.
287        if ( visitingChildOfSUIT ) {
288                // DimensionExpr and TypeExpr should not reach here.
289                return new ast::TypeExpr( expr->location,
290                        new ast::ArrayType(
291                                new ast::BasicType( ast::BasicType::Char ),
292                                expr,
293                                ast::VariableLen,
294                                ast::DynamicDim
295                        )
296                );
297        }
298        return expr;
299}
300
301const ast::Expr * TranslateDimensionCore::postvisit(
302                const ast::TypeExpr * expr ) {
303        // Does nothing, except prevents matching ast::Expr (above).
304        return expr;
305}
306
307} // namespace
308
309void fillGenericParameters( ast::TranslationUnit & translationUnit ) {
310        ast::Pass<ValidateGenericParamsCore>::run( translationUnit );
311}
312
313void translateDimensionParameters( ast::TranslationUnit & translationUnit ) {
314        ast::Pass<TranslateDimensionCore>::run( translationUnit );
315}
316
317} // namespace Validate
318
319// Local Variables: //
320// tab-width: 4 //
321// mode: c++ //
322// compile-command: "make install" //
323// End: //
Note: See TracBrowser for help on using the repository browser.