source: src/SymTab/Demangle.cc @ d1e0979

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since d1e0979 was d1e0979, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Add a basic demangler that works for basic types, pointers, tuples, and functions

  • Property mode set to 100644
File size: 14.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// Demangler.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Thu Jul 19 12:52:41 2018
11// Last Modified By : Rob Schluntz
12// Last Modified On : Thu Jul 19 12:54:35 2018
13// Update Count     : 2
14//
15
16#include <algorithm>
17#include <sstream>
18
19#include "CodeGen/GenType.h"
20#include "Common/PassVisitor.h"
21#include "Mangler.h"
22#include "SynTree/Type.h"
23#include "SynTree/Declaration.h"
24
25// #define DEBUG
26#ifdef DEBUG
27#define PRINT(x) x
28#else
29#define PRINT(x) {}
30#endif
31
32namespace {
33        struct GenType : public WithVisitorRef<GenType>, public WithShortCircuiting {
34                std::string typeString;
35                GenType( const std::string &typeString );
36
37                void previsit( BaseSyntaxNode * );
38                void postvisit( BaseSyntaxNode * );
39
40                void postvisit( FunctionType * funcType );
41                void postvisit( VoidType * voidType );
42                void postvisit( BasicType * basicType );
43                void postvisit( PointerType * pointerType );
44                void postvisit( ArrayType * arrayType );
45                void postvisit( ReferenceType * refType );
46                void postvisit( StructInstType * structInst );
47                void postvisit( UnionInstType * unionInst );
48                void postvisit( EnumInstType * enumInst );
49                void postvisit( TypeInstType * typeInst );
50                void postvisit( TupleType  * tupleType );
51                void postvisit( VarArgsType * varArgsType );
52                void postvisit( ZeroType * zeroType );
53                void postvisit( OneType * oneType );
54                void postvisit( GlobalScopeType * globalType );
55                void postvisit( QualifiedType * qualType );
56
57          private:
58                void handleQualifiers( Type *type );
59                std::string handleGeneric( ReferenceToType * refType );
60                void genArray( const Type::Qualifiers &qualifiers, Type *base, Expression *dimension, bool isVarLen, bool isStatic );
61        };
62
63  std::string genDemangleType( Type * type, const std::string & baseString ) {
64                PassVisitor<GenType> gt( baseString );
65                assert( type );
66                type->accept( gt );
67                return gt.pass.typeString;
68  }
69
70        GenType::GenType( const std::string &typeString ) : typeString( typeString ) {}
71
72        // *** BaseSyntaxNode
73        void GenType::previsit( BaseSyntaxNode * ) {
74                // turn off automatic recursion for all nodes, to allow each visitor to
75                // precisely control the order in which its children are visited.
76                visit_children = false;
77        }
78
79        void GenType::postvisit( BaseSyntaxNode * node ) {
80                std::stringstream ss;
81                node->print( ss );
82                assertf( false, "Unhandled node reached in GenType: %s", ss.str().c_str() );
83        }
84
85        void GenType::postvisit( VoidType * voidType ) {
86                typeString = "void " + typeString;
87                handleQualifiers( voidType );
88        }
89
90        void GenType::postvisit( BasicType * basicType ) {
91                BasicType::Kind kind = basicType->kind;
92                assert( 0 <= kind && kind < BasicType::NUMBER_OF_BASIC_TYPES );
93                typeString = std::string( BasicType::typeNames[kind] ) + " " + typeString;
94                handleQualifiers( basicType );
95        }
96
97        void GenType::genArray( const Type::Qualifiers & qualifiers, Type * base, Expression *dimension, bool isVarLen, bool ) {
98                std::ostringstream os;
99                if ( typeString != "" ) {
100                        if ( typeString[ 0 ] == '*' ) {
101                                os << "(" << typeString << ")";
102                        } else {
103                                os << typeString;
104                        } // if
105                } // if
106                os << "[";
107
108                if ( qualifiers.is_const ) {
109                        os << "const ";
110                } // if
111                if ( qualifiers.is_volatile ) {
112                        os << "volatile ";
113                } // if
114                if ( qualifiers.is_restrict ) {
115                        os << "__restrict ";
116                } // if
117                if ( qualifiers.is_atomic ) {
118                        os << "_Atomic ";
119                } // if
120                if ( dimension != 0 ) {
121                        // TODO: ???
122                        // PassVisitor<CodeGenerator> cg( os, pretty, genC, lineMarks );
123                        // dimension->accept( cg );
124                } else if ( isVarLen ) {
125                        // no dimension expression on a VLA means it came in with the * token
126                        os << "*";
127                } // if
128                os << "]";
129
130                typeString = os.str();
131
132                base->accept( *visitor );
133        }
134
135        void GenType::postvisit( PointerType * pointerType ) {
136                assert( pointerType->base != 0);
137                if ( pointerType->get_isStatic() || pointerType->get_isVarLen() || pointerType->dimension ) {
138                        assert(false);
139                        genArray( pointerType->get_qualifiers(), pointerType->base, pointerType->dimension, pointerType->get_isVarLen(), pointerType->get_isStatic() );
140                } else {
141                        handleQualifiers( pointerType );
142                        if ( typeString[ 0 ] == '?' ) {
143                                typeString = "* " + typeString;
144                        } else {
145                                typeString = "*" + typeString;
146                        } // if
147                        pointerType->base->accept( *visitor );
148                } // if
149        }
150
151        void GenType::postvisit( ArrayType * arrayType ) {
152                genArray( arrayType->get_qualifiers(), arrayType->base, arrayType->dimension, arrayType->get_isVarLen(), arrayType->get_isStatic() );
153        }
154
155        void GenType::postvisit( ReferenceType * refType ) {
156                assert( false );
157                assert( refType->base != 0);
158                handleQualifiers( refType );
159                typeString = "&" + typeString;
160                refType->base->accept( *visitor );
161        }
162
163        void GenType::postvisit( FunctionType * funcType ) {
164                std::ostringstream os;
165
166                if ( typeString != "" ) {
167                        if ( typeString[0] == '*' ) {
168                                os << "(" << typeString << ")";
169                        } else {
170                                os << typeString;
171                        } // if
172                } // if
173
174                /************* parameters ***************/
175                const std::list<DeclarationWithType *> &pars = funcType->parameters;
176
177                if ( pars.empty() ) {
178                        if ( funcType->get_isVarArgs() ) {
179                                os << "()";
180                        } else {
181                                os << "(void)";
182                        } // if
183                } else {
184                        os << "(" ;
185
186                        unsigned int i = 0;
187                        for (DeclarationWithType * p : pars) {
188                                os << genDemangleType( p->get_type(), "" );
189                                if (++i != pars.size()) os << ", ";
190                        }
191
192                        if ( funcType->get_isVarArgs() ) {
193                                os << ", ...";
194                        } // if
195                        os << ")";
196                } // if
197
198                typeString = os.str();
199
200                if ( funcType->returnVals.size() == 0 ) {
201                        typeString += ": void";
202                } else {
203                        typeString += ": " + genDemangleType(funcType->returnVals.front()->get_type(), "");
204                } // if
205
206                // add forall
207                if( ! funcType->forall.empty() ) {
208                        std::ostringstream os;
209                        os << "forall(";
210                        unsigned int i = 0;
211                        for ( auto td : funcType->forall ) {
212                                os << td->typeString() << " " << td->name;
213                                if (! td->assertions.empty()) {
214                                        os << " | { ";
215                                        unsigned int j = 0;
216                                        for (DeclarationWithType * assert : td->assertions) {
217                                                os << genDemangleType(assert->get_type(), assert->name);
218                                                if (++j != td->assertions.size()) os << ", ";
219                                        }
220                                        os << "}";
221                                }
222                                if (++i != funcType->forall.size()) os << ", ";
223                        }
224                        os << ")";
225                        typeString = typeString + " -> " + os.str();
226                }
227        }
228
229        std::string GenType::handleGeneric( ReferenceToType * refType ) {
230                if ( ! refType->parameters.empty() ) {
231                        std::ostringstream os;
232                        // TODO: ???
233                        // PassVisitor<CodeGenerator> cg( os, pretty, genC, lineMarks );
234                        os << "(";
235                        // cg.pass.genCommaList( refType->parameters.begin(), refType->parameters.end() );
236                        os << ") ";
237                        return os.str();
238                }
239                return "";
240        }
241
242        void GenType::postvisit( StructInstType * structInst )  {
243                typeString = "struct " + structInst->name + handleGeneric( structInst ) + " " + typeString;
244                handleQualifiers( structInst );
245        }
246
247        void GenType::postvisit( UnionInstType * unionInst ) {
248                typeString = "union " + unionInst->name + handleGeneric( unionInst ) + " " + typeString;
249                handleQualifiers( unionInst );
250        }
251
252        void GenType::postvisit( EnumInstType * enumInst ) {
253                typeString = "enum " + enumInst->name + " " + typeString;
254                handleQualifiers( enumInst );
255        }
256
257        void GenType::postvisit( TypeInstType * typeInst ) {
258                typeString = typeInst->name + " " + typeString;
259                handleQualifiers( typeInst );
260        }
261
262        void GenType::postvisit( TupleType * tupleType ) {
263                unsigned int i = 0;
264                std::ostringstream os;
265                os << "[";
266                for ( Type * t : *tupleType ) {
267                        i++;
268                        os << genDemangleType( t, "" ) << (i == tupleType->size() ? "" : ", ");
269                }
270                os << "] ";
271                typeString = os.str() + typeString;
272        }
273
274        void GenType::postvisit( VarArgsType * varArgsType ) {
275                typeString = "__builtin_va_list " + typeString;
276                handleQualifiers( varArgsType );
277        }
278
279        void GenType::postvisit( ZeroType * zeroType ) {
280                // ideally these wouldn't hit codegen at all, but should be safe to make them ints
281                typeString = "zero_t " + typeString;
282                handleQualifiers( zeroType );
283        }
284
285        void GenType::postvisit( OneType * oneType ) {
286                // ideally these wouldn't hit codegen at all, but should be safe to make them ints
287                typeString = "one_t " + typeString;
288                handleQualifiers( oneType );
289        }
290
291        void GenType::postvisit( GlobalScopeType * globalType ) {
292                handleQualifiers( globalType );
293        }
294
295        void GenType::postvisit( QualifiedType * qualType ) {
296                std::ostringstream os;
297                os << genDemangleType( qualType->parent, "" ) << "." << genDemangleType( qualType->child, "" ) << typeString;
298                typeString = os.str();
299                handleQualifiers( qualType );
300        }
301
302        void GenType::handleQualifiers( Type * type ) {
303                if ( type->get_const() ) {
304                        typeString = "const " + typeString;
305                } // if
306                if ( type->get_volatile() ) {
307                        typeString = "volatile " + typeString;
308                } // if
309                if ( type->get_restrict() ) {
310                        typeString = "__restrict " + typeString;
311                } // if
312                if ( type->get_atomic() ) {
313                        typeString = "_Atomic " + typeString;
314                } // if
315                if ( type->get_lvalue() ) {
316                        // when not generating C code, print lvalue for debugging.
317                        typeString = "lvalue " + typeString;
318                }
319        }
320}
321
322
323namespace SymTab {
324        namespace Mangler {
325                namespace {
326                        // strips __NAME__cfa__TYPE_N, where N is [0-9]+: returns str is a match is found, returns empty string otherwise
327                        bool stripMangleName(const std::string & mangleName, std::string & name, std::string & type) {
328                                PRINT( std::cerr << "====== " << mangleName.size() << " " << mangleName << std::endl; )
329                                if (mangleName.size() < 4+nameSeparator.size()) return false;
330                                if (mangleName[0] != '_' || mangleName[1] != '_' || ! isdigit(mangleName.back())) return false;
331
332                                // find bounds for name
333                                size_t nameStart = 2;
334                                size_t nameEnd = mangleName.rfind(nameSeparator);
335                                PRINT( std::cerr << nameStart << " " << nameEnd << std::endl; )
336                                if (nameEnd == std::string::npos) return false;
337
338                                // find bounds for type
339                                size_t typeStart = nameEnd+nameSeparator.size();
340                                size_t typeEnd = mangleName.size()-1;
341                                PRINT( std::cerr << typeStart << " " << typeEnd << std::endl; )
342                                PRINT( std::cerr << "[");
343                                while (isdigit(mangleName[typeEnd])) {
344                                        PRINT(std::cerr << ".");
345                                        typeEnd--;
346                                }
347                                PRINT( std::cerr << "]" << std::endl );
348                                if (mangleName[typeEnd] != '_') return false;
349                                PRINT( std::cerr << typeEnd << std::endl; )
350
351                                // trim and return
352                                name = mangleName.substr(nameStart, nameEnd-nameStart);
353                                type = mangleName.substr(typeStart, typeEnd-typeStart);
354                                return true;
355                        }
356
357                        /// determines if `pref` is a prefix of `str`
358                        static inline bool isPrefix( const std::string & str, const std::string & pref, unsigned int idx ) {
359                                if ( pref.size() > str.size()-idx ) return false;
360                                auto its = std::mismatch( pref.begin(), pref.end(), std::next(str.begin(), idx) );
361                                return its.first == pref.end();
362                        }
363
364                        Type * parseType(const std::string & typeString, unsigned int & idx) {
365                                if (idx >= typeString.size()) return nullptr;
366
367                                // qualifiers
368                                Type::Qualifiers tq;
369                                while (true) {
370                                        auto qual = std::find_if(qualifierLetter.begin(), qualifierLetter.end(), [&idx, &typeString](decltype(qualifierLetter)::value_type val) {
371                                                if (isPrefix(typeString, val.second, idx)) {
372                                                        PRINT( std::cerr << "found qualifier: " << val.second << std::endl; )
373                                                        idx += std::string(val.second).size();
374                                                        return true;
375                                                }
376                                                return false;
377                                        });
378                                        if (qual == qualifierLetter.end()) break;
379                                        tq |= qual->first;
380                                }
381
382                                // basic types
383                                const char ** letter = std::find_if(&btLetter[0], &btLetter[numBtLetter], [&idx, &typeString](const std::string & letter) {
384                                        if (isPrefix(typeString, letter, idx)) {
385                                                idx += letter.size();
386                                                return true;
387                                        }
388                                        return false;
389                                });
390                                if (letter != &btLetter[numBtLetter]) {
391                                        PRINT( std::cerr << "basic type: " << (letter-btLetter) << std::endl; )
392                                        BasicType::Kind k = (BasicType::Kind)(letter-btLetter);
393                                        return new BasicType( tq, k );
394                                } // BasicType?
395
396                                // everything else
397                                switch(typeString[idx++]) {
398                                        case 'F': {
399                                                PRINT( std::cerr << "function..." << std::endl; )
400                                                if (idx >= typeString.size()) return nullptr;
401                                                FunctionType * ftype = new FunctionType( tq, false );
402                                                Type * retVal = parseType(typeString, idx);
403                                                if (! retVal) return nullptr;
404                                                PRINT( std::cerr << "with return type: " << retVal << std::endl; )
405                                                ftype->returnVals.push_back(ObjectDecl::newObject("", retVal, nullptr));
406                                                if (idx >= typeString.size() || typeString[idx++] != '_') return nullptr;
407                                                while (idx < typeString.size()) {
408                                                        PRINT( std::cerr << "got ch: " << typeString[idx] << std::endl; )
409                                                        if (typeString[idx] == '_') break;
410                                                        Type * param = parseType(typeString, idx);
411                                                        if (! param) return nullptr;
412                                                        PRINT( std::cerr << "with parameter : " << param << std::endl; )
413                                                        ftype->parameters.push_back(ObjectDecl::newObject("", param, nullptr));
414                                                }
415                                                if (idx >= typeString.size() || typeString[idx] != '_') return nullptr;
416                                                ++idx;
417                                                return ftype;
418                                        }
419                                        case 'v':
420                                                return new VoidType( tq );
421                                        case 'T': {
422                                                PRINT( std::cerr << "tuple..." << std::endl; )
423                                                std::list< Type * > types;
424                                                while (idx < typeString.size()) {
425                                                        PRINT( std::cerr << "got ch: " << typeString[idx] << std::endl; )
426                                                        if (typeString[idx] == '_') break;
427                                                        Type * t = parseType(typeString, idx);
428                                                        if (! t) return nullptr;
429                                                        PRINT( std::cerr << "with type : " << t << std::endl; )
430                                                        types.push_back(t);
431                                                }
432                                                if (idx >= typeString.size() || typeString[idx] != '_') return nullptr;
433                                                ++idx;
434                                                return new TupleType( tq, types );
435                                        }
436                                        case 'P': {
437                                                PRINT( std::cerr << "pointer..." << std::endl; )
438                                                Type * t = parseType(typeString, idx);
439                                                if (! t) return nullptr;
440                                                return new PointerType( tq, t );
441                                        }
442
443                                        default: assertf(false, "Unhandled type letter: %c at index: %u", typeString[idx], idx);
444                                }
445                                return nullptr;
446                        }
447
448                        Type * parseType(const std::string & typeString) {
449                                unsigned int idx = 0;
450                                return parseType(typeString, idx);
451                        }
452                } // namespace
453        } // namespace Mangler
454} // namespace SymTab
455
456extern "C" {
457        std::string cforall_demangle(const std::string & mangleName) {
458                std::string name, type;
459                if (! SymTab::Mangler::stripMangleName(mangleName, name, type)) return mangleName;
460                PRINT( std::cerr << name << " " << type << std::endl; )
461                Type * t = SymTab::Mangler::parseType(type);
462                if (! t) return mangleName;
463                return genDemangleType(t, name);
464        } // extern "C"
465}
466
467// Local Variables: //
468// tab-width: 4 //
469// mode: c++ //
470// compile-command: "make install" //
471// End: //
Note: See TracBrowser for help on using the repository browser.