Changeset 6943a987


Ignore:
Timestamp:
Aug 29, 2016, 10:33:05 AM (8 years ago)
Author:
Aaron Moss <a3moss@…>
Branches:
ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, ctor, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc
Children:
5e644d3e
Parents:
79841be (diff), 413ad05 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

Files:
6 added
6 deleted
83 edited

Legend:

Unmodified
Added
Removed
  • .gitignore

    r79841be r6943a987  
    3434# generated by bison and lex from cfa.yy and lex.ll, respectively
    3535src/Parser/parser.output
     36
     37# generated by xfig for user manual
     38doc/user/Cdecl.tex
     39doc/user/pointer1.tex
     40doc/user/pointer2.tex
  • doc/LaTeXmacros/common.tex

    r79841be r6943a987  
    1111%% Created On       : Sat Apr  9 10:06:17 2016
    1212%% Last Modified By : Peter A. Buhr
    13 %% Last Modified On : Tue Aug  2 17:02:02 2016
    14 %% Update Count     : 228
     13%% Last Modified On : Sun Aug 14 08:27:29 2016
     14%% Update Count     : 231
    1515%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    1616
     
    154154}%
    155155\newcommand{\etal}{%
    156         \@ifnextchar{.}{\abbrevFont{et al}}%
     156        \@ifnextchar{.}{\abbrevFont{et~al}}%
    157157                {\abbrevFont{et al}.\xspace}%
    158158}%
     
    255255literate={-}{\raisebox{-0.15ex}{\texttt{-}}}1 {^}{\raisebox{0.6ex}{$\scriptscriptstyle\land\,$}}1
    256256        {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 {_}{\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}1 {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
    257         {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {...}{$\dots$}2,
     257        {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2,
    258258}%
    259259
  • doc/aaron_comp_II/comp_II.tex

    r79841be r6943a987  
    9191\CFA\footnote{Pronounced ``C-for-all'', and written \CFA or \CFL.} is an evolutionary modernization of the C programming language currently being designed and built at the University of Waterloo by a team led by Peter Buhr.
    9292\CFA both fixes existing design problems and adds multiple new features to C, including name overloading, user-defined operators, parametric-polymorphic routines, and type constructors and destructors, among others.
    93 The new features make \CFA significantly more powerful and expressive than C, but impose a significant compile-time cost, particularly in the expression resolver, which must evaluate the typing rules of a much more complex type-system.
     93The new features make \CFA more powerful and expressive than C, but impose a compile-time cost, particularly in the expression resolver, which must evaluate the typing rules of a significantly more complex type-system.
    9494
    9595The primary goal of this research project is to develop a sufficiently performant expression resolution algorithm, experimentally validate its performance, and integrate it into CFA, the \CFA reference compiler.
     
    104104
    105105It is important to note that \CFA is not an object-oriented language.
    106 \CFA does have a system of (possibly implicit) type conversions derived from C's type conversions; while these conversions may be thought of as something like an inheritance hierarchy the underlying semantics are significantly different and such an analogy is loose at best.
     106\CFA does have a system of (possibly implicit) type conversions derived from C's type conversions; while these conversions may be thought of as something like an inheritance hierarchy, the underlying semantics are significantly different and such an analogy is loose at best.
    107107Particularly, \CFA has no concept of ``subclass'', and thus no need to integrate an inheritance-based form of polymorphism with its parametric and overloading-based polymorphism.
    108108The graph structure of the \CFA type conversions is also markedly different than an inheritance graph; it has neither a top nor a bottom type, and does not satisfy the lattice properties typical of inheritance graphs.
     
    120120\end{lstlisting}
    121121The ©identity© function above can be applied to any complete object type (or ``©otype©'').
    122 The type variable ©T© is transformed into a set of additional implicit parameters to ©identity© which encode sufficient information about ©T© to create and return a variable of that type.
     122The type variable ©T© is transformed into a set of additional implicit parameters to ©identity©, which encode sufficient information about ©T© to create and return a variable of that type.
    123123The current \CFA implementation passes the size and alignment of the type represented by an ©otype© parameter, as well as an assignment operator, constructor, copy constructor and destructor.
    124124Here, the runtime cost of polymorphism is spread over each polymorphic call, due to passing more arguments to polymorphic functions; preliminary experiments have shown this overhead to be similar to \CC virtual function calls.
    125125Determining if packaging all polymorphic arguments to a function into a virtual function table would reduce the runtime overhead of polymorphic calls is an open research question.
    126126
    127 Since bare polymorphic types do not provide a great range of available operations, \CFA also provides a \emph{type assertion} mechanism to provide further information about a type:
     127Since bare polymorphic types do not provide a great range of available operations, \CFA provides a \emph{type assertion} mechanism to provide further information about a type:
    128128\begin{lstlisting}
    129129forall(otype T ®| { T twice(T); }®)
     
    137137\end{lstlisting}
    138138These type assertions may be either variable or function declarations that depend on a polymorphic type variable.
    139 ©four_times© can only be called with an argument for which there exists a function named ©twice© that can take that argument and return another value of the same type; a pointer to the appropriate ©twice© function is passed as an additional implicit parameter to the call to ©four_times©.
     139©four_times© can only be called with an argument for which there exists a function named ©twice© that can take that argument and return another value of the same type; a pointer to the appropriate ©twice© function is passed as an additional implicit parameter to the call of ©four_times©.
    140140
    141141Monomorphic specializations of polymorphic functions can themselves be used to satisfy type assertions.
     
    148148The compiler accomplishes this by creating a wrapper function calling ©twice // (2)© with ©S© bound to ©double©, then providing this wrapper function to ©four_times©\footnote{©twice // (2)© could also have had a type parameter named ©T©; \CFA specifies renaming of the type parameters, which would avoid the name conflict with the type variable ©T© of ©four_times©.}.
    149149
    150 Finding appropriate functions to satisfy type assertions is essentially a recursive case of expression resolution, as it takes a name (that of the type assertion) and attempts to match it to a suitable declaration in the current scope.
     150Finding appropriate functions to satisfy type assertions is essentially a recursive case of expression resolution, as it takes a name (that of the type assertion) and attempts to match it to a suitable declaration \emph{in the current scope}.
    151151If a polymorphic function can be used to satisfy one of its own type assertions, this recursion may not terminate, as it is possible that function is examined as a candidate for its own type assertion unboundedly repeatedly.
    152152To avoid infinite loops, the current CFA compiler imposes a fixed limit on the possible depth of recursion, similar to that employed by most \CC compilers for template expansion; this restriction means that there are some semantically well-typed expressions that cannot be resolved by CFA.
     
    170170forall(otype M | has_magnitude(M))
    171171M max_magnitude( M a, M b ) {
    172     M aa = abs(a), ab = abs(b);
    173     return aa < ab ? b : a;
     172    return abs(a) < abs(b) ? b : a;
    174173}
    175174\end{lstlisting}
    176175
    177176Semantically, traits are simply a named lists of type assertions, but they may be used for many of the same purposes that interfaces in Java or abstract base classes in \CC are used for.
    178 Unlike Java interfaces or \CC base classes, \CFA types do not explicitly state any inheritance relationship to traits they satisfy; this can be considered a form of structural inheritance, similar to interface implementation in Go, as opposed to the nominal inheritance model of Java and \CC.
     177Unlike Java interfaces or \CC base classes, \CFA types do not explicitly state any inheritance relationship to traits they satisfy; this can be considered a form of structural inheritance, similar to implementation of an interface in Go, as opposed to the nominal inheritance model of Java and \CC.
    179178Nominal inheritance can be simulated with traits using marker variables or functions:
    180179\begin{lstlisting}
     
    190189\end{lstlisting}
    191190
    192 Traits, however, are significantly more powerful than nominal-inheritance interfaces; firstly, due to the scoping rules of the declarations which satisfy a trait's type assertions, a type may not satisfy a trait everywhere that the type is declared, as with ©char© and the ©nominal© trait above.
    193 Secondly, traits may be used to declare a relationship between multiple types, a property which may be difficult or impossible to represent in nominal-inheritance type systems:
     191Traits, however, are significantly more powerful than nominal-inheritance interfaces; firstly, due to the scoping rules of the declarations that satisfy a trait's type assertions, a type may not satisfy a trait everywhere that the type is declared, as with ©char© and the ©nominal© trait above.
     192Secondly, traits may be used to declare a relationship among multiple types, a property that may be difficult or impossible to represent in nominal-inheritance type systems:
    194193\begin{lstlisting}
    195194trait pointer_like(®otype Ptr, otype El®) {
     
    202201};
    203202
    204 typedef list* list_iterator;
     203typedef list *list_iterator;
    205204
    206205lvalue int *?( list_iterator it ) {
     
    209208\end{lstlisting}
    210209
    211 In the example above, ©(list_iterator, int)© satisfies ©pointer_like© by the given function, and ©(list_iterator, list)© also satisfies ©pointer_like© by the built-in pointer dereference operator.
     210In the example above, ©(list_iterator, int)© satisfies ©pointer_like© by the user-defined dereference function, and ©(list_iterator, list)© also satisfies ©pointer_like© by the built-in dereference operator for pointers.
     211Given a declaration ©list_iterator it©, ©*it© can be either an ©int© or a ©list©, with the meaning disambiguated by context (\eg ©int x = *it;© interprets ©*it© as an ©int©, while ©(*it).value = 42;© interprets ©*it© as a ©list©).
    212212While a nominal-inheritance system with associated types could model one of those two relationships by making ©El© an associated type of ©Ptr© in the ©pointer_like© implementation, few such systems could model both relationships simultaneously.
    213213
    214 The flexibility of \CFA's implicit trait satisfaction mechanism provides programmers with a great deal of power, but also blocks some optimization approaches for expression resolution.
    215 The ability of types to begin to or cease to satisfy traits when declarations go into or out of scope makes caching of trait satisfaction judgements difficult, and the ability of traits to take multiple type parameters could lead to a combinatorial explosion of work in any attempt to pre-compute trait satisfaction relationships.
     214The flexibility of \CFA's implicit trait-satisfaction mechanism provides programmers with a great deal of power, but also blocks some optimization approaches for expression resolution.
     215The ability of types to begin to or cease to satisfy traits when declarations go into or out of scope makes caching of trait satisfaction judgements difficult, and the ability of traits to take multiple type parameters can lead to a combinatorial explosion of work in any attempt to pre-compute trait satisfaction relationships.
    216216On the other hand, the addition of a nominal inheritance mechanism to \CFA's type system or replacement of \CFA's trait satisfaction system with a more object-oriented inheritance model and investigation of possible expression resolution optimizations for such a system may be an interesting avenue of further research.
    217217
    218218\subsection{Name Overloading}
    219219In C, no more than one variable or function in the same scope may share the same name\footnote{Technically, C has multiple separated namespaces, one holding ©struct©, ©union©, and ©enum© tags, one holding labels, one holding typedef names, variable, function, and enumerator identifiers, and one for each ©struct© or ©union© type holding the field names.}, and variable or function declarations in inner scopes with the same name as a declaration in an outer scope hide the outer declaration.
    220 This makes finding the proper declaration to match to a variable expression or function application a simple matter of symbol table lookup, which can be easily and efficiently implemented.
     220This restriction makes finding the proper declaration to match to a variable expression or function application a simple matter of symbol-table lookup, which can be easily and efficiently implemented.
    221221\CFA, on the other hand, allows overloading of variable and function names, so long as the overloaded declarations do not have the same type, avoiding the multiplication of variable and function names for different types common in the C standard library, as in the following example:
    222222\begin{lstlisting}
     
    229229double max = DBL_MAX;  // (4)
    230230
    231 max(7, -max);   // uses (1) and (3), by matching int type of 7
    232 max(max, 3.14); // uses (2) and (4), by matching double type of 3.14
     231max(7, -max);   // uses (1) and (3), by matching int type of the constant 7
     232max(max, 3.14); // uses (2) and (4), by matching double type of the constant 3.14
    233233
    234234max(max, -max);  // ERROR: ambiguous
    235 int m = max(max, -max); // uses (1) and (3) twice, by return type
     235int m = max(max, -max); // uses (1) once and (3) twice, by matching return type
    236236\end{lstlisting}
    237237
     
    239239
    240240\subsection{Implicit Conversions}
    241 In addition to the multiple interpretations of an expression produced by name overloading, \CFA also supports all of the implicit conversions present in C, producing further candidate interpretations for expressions.
    242 C does not have a traditionally-defined inheritance hierarchy of types, but the C standard's rules for the ``usual arithmetic conversions'' define which of the built-in types are implicitly convertable to which other types, and the relative cost of any pair of such conversions from a single source type.
    243 \CFA adds to the usual arithmetic conversions rules for determining the cost of binding a polymorphic type variable in a function call; such bindings are cheaper than any \emph{unsafe} (narrowing) conversion, \eg ©int© to ©char©, but more expensive than any \emph{safe} (widening) conversion, \eg ©int© to ©double©.
    244 
    245 The expression resolution problem, then, is to find the unique minimal-cost interpretation of each expression in the program, where all identifiers must be matched to a declaration and implicit conversions or polymorphic bindings of the result of an expression may increase the cost of the expression.
     241In addition to the multiple interpretations of an expression produced by name overloading, \CFA must support all of the implicit conversions present in C for backward compatibility, producing further candidate interpretations for expressions.
     242C does not have a inheritance hierarchy of types, but the C standard's rules for the ``usual arithmetic conversions'' define which of the built-in types are implicitly convertable to which other types, and the relative cost of any pair of such conversions from a single source type.
     243\CFA adds to the usual arithmetic conversions rules defining the cost of binding a polymorphic type variable in a function call; such bindings are cheaper than any \emph{unsafe} (narrowing) conversion, \eg ©int© to ©char©, but more expensive than any \emph{safe} (widening) conversion, \eg ©int© to ©double©.
     244
     245The expression resolution problem, then, is to find the unique minimal-cost interpretation of each expression in the program, where all identifiers must be matched to a declaration, and implicit conversions or polymorphic bindings of the result of an expression may increase the cost of the expression.
    246246Note that which subexpression interpretation is minimal-cost may require contextual information to disambiguate.
    247 For instance, in the example in the previous subsection, ©max(max, -max)© cannot be unambiguously resolved, but ©int m = max(max, -max);© has a single minimal-cost resolution.
    248 ©int m = (int)max((double)max, -(double)max)© is also be a valid interpretation, but is not minimal-cost due to the unsafe cast from the ©double© result of ©max© to ©int© (the two ©double© casts function as type ascriptions selecting ©double max© rather than casts from ©int max© to ©double©, and as such are zero-cost).
     247For instance, in the example in the previous subsection, ©max(max, -max)© cannot be unambiguously resolved, but ©int m = max(max, -max)© has a single minimal-cost resolution.
     248While the interpretation ©int m = (int)max((double)max, -(double)max)© is also a valid interpretation, it is not minimal-cost due to the unsafe cast from the ©double© result of ©max© to ©int© (the two ©double© casts function as type ascriptions selecting ©double max© rather than casts from ©int max© to ©double©, and as such are zero-cost).
    249249
    250250\subsubsection{User-generated Implicit Conversions}
     
    252252Such a conversion system should be simple for programmers to utilize, and fit naturally with the existing design of implicit conversions in C; ideally it would also be sufficiently powerful to encode C's usual arithmetic conversions itself, so that \CFA only has one set of rules for conversions.
    253253
    254 Ditchfield~\cite{Ditchfield:conversions} has laid out a framework for using polymorphic-conversion-constructor functions to create a directed acyclic graph (DAG) of conversions.
     254Ditchfield~\cite{Ditchfield:conversions} laid out a framework for using polymorphic-conversion-constructor functions to create a directed acyclic graph (DAG) of conversions.
    255255A monomorphic variant of these functions can be used to mark a conversion arc in the DAG as only usable as the final step in a conversion.
    256 With these two types of conversion arcs, separate DAGs can be created for the safe and the unsafe conversions, and conversion cost can be represented as path length through the DAG.
     256With these two types of conversion arcs, separate DAGs can be created for the safe and the unsafe conversions, and conversion cost can be represented the length of the shortest path through the DAG from one type to another.
    257257\begin{figure}[h]
    258258\centering
    259259\includegraphics{conversion_dag}
    260 \caption{A portion of the implicit conversion DAG for built-in types.}
     260\caption{A portion of the implicit conversion DAG for built-in types.}\label{fig:conv_dag}
    261261\end{figure}
    262 As can be seen in the example DAG above, there are either safe or unsafe paths between each of the arithmetic types listed; the ``final'' arcs are important both to avoid creating cycles in the signed-unsigned conversions, and to disambiguate potential diamond conversions (\eg, if the ©int© to ©unsigned int© conversion was not marked final there would be two length-two paths from ©int© to ©unsigned long©, and it would be impossible to choose which one; however, since the ©unsigned int© to ©unsigned long© arc can not be traversed after the final ©int© to ©unsigned int© arc, there is a single unambiguous conversion path from ©int© to ©unsigned long©).
     262As can be seen in Figure~\ref{fig:conv_dag}, there are either safe or unsafe paths between each of the arithmetic types listed; the ``final'' arcs are important both to avoid creating cycles in the signed-unsigned conversions, and to disambiguate potential diamond conversions (\eg, if the ©int© to ©unsigned int© conversion was not marked final there would be two length-two paths from ©int© to ©unsigned long©, making it impossible to choose which one; however, since the ©unsigned int© to ©unsigned long© arc can not be traversed after the final ©int© to ©unsigned int© arc, there is a single unambiguous conversion path from ©int© to ©unsigned long©).
    263263
    264264Open research questions on this topic include:
    265265\begin{itemize}
    266266\item Can a conversion graph be generated that represents each allowable conversion in C with a unique minimal-length path such that the path lengths accurately represent the relative costs of the conversions?
    267 \item Can such a graph representation can be usefully augmented to include user-defined types as well as built-in types?
    268 \item Can the graph can be efficiently represented and used in the expression resolver?
     267\item Can such a graph representation be usefully augmented to include user-defined types as well as built-in types?
     268\item Can the graph be efficiently represented and used in the expression resolver?
    269269\end{itemize}
    270270
    271271\subsection{Constructors and Destructors}
    272272Rob Shluntz, a current member of the \CFA research team, has added constructors and destructors to \CFA.
    273 Each type has an overridable default-generated zero-argument constructor, copy constructor, assignment operator, and destructor; for ©struct© types these functions each call their equivalents on each field of the ©struct©.
    274 This affects expression resolution because an ©otype© type variable ©T© implicitly adds four type assertions, one for each of these four functions, so assertion resolution is pervasive in \CFA polymorphic functions, even those without any explicit type assertions.
     273Each type has an overridable default-generated zero-argument constructor, copy constructor, assignment operator, and destructor.
     274For ©struct© types these functions each call their equivalents on each field of the ©struct©.
     275This feature affects expression resolution because an ©otype© type variable ©T© implicitly adds four type assertions, one for each of these four functions, so assertion resolution is pervasive in \CFA polymorphic functions, even those without any explicit type assertions.
    275276The following example shows the implicitly-generated code in green:
    276277\begin{lstlisting}
     
    280281};
    281282
    282 ¢void ?{}(kv *this) {
    283     ?{}(&this->key);
    284     ?{}(&this->value);
    285 }
    286 void ?{}(kv *this, kv that) {
    287     ?{}(&this->key, that.key);
    288     ?{}(&this->value, that.value);
    289 }
    290 kv ?=?(kv *this, kv that) {
    291     ?=?(&this->key, that.key);
    292     ?=?(&this->value, that.value);
     283¢void ?{}(kv *this) {  // default constructor
     284    ?{}(&(this->key));  // call recursively on members
     285    ?{}(&(this->value));
     286}
     287void ?{}(kv *this, kv that) {  // copy constructor
     288    ?{}(&(this->key), that.key);
     289    ?{}(&(this->value), that.value);
     290}
     291kv ?=?(kv *this, kv that) {  // assignment operator
     292    ?=?(&(this->key), that.key);
     293    ?=?(&(this->value), that.value);
    293294    return *this;
    294295}
    295 void ^?{}(kv *this) {
    296     ^?{}(&this->key);
    297     ^?{}(&this->value);
     296void ^?{}(kv *this) {  // destructor
     297    ^?{}(&(this->key));
     298    ^?{}(&(this->value));
    298299
    299300
     
    335336\begin{itemize}
    336337\item Since there is an implicit conversion from ©void*© to any pointer type, the highlighted expression can be interpreted as either a ©void*©, matching ©f // (1)©, or a ©box(S)*© for some type ©S©, matching ©f // (2)©.
    337 \item To determine the cost of the ©box(S)© interpretation, a type must be found for ©S© which satisfies the ©otype© implicit type assertions (assignment operator, default and copy constructors, and destructor); one option is ©box(S2)© for some type ©S2©.
     338\item To determine the cost of the ©box(S)© interpretation, a type must be found for ©S© that satisfies the ©otype© implicit type assertions (assignment operator, default and copy constructors, and destructor); one option is ©box(S2)© for some type ©S2©.
    338339\item The assignment operator, default and copy constructors, and destructor of ©box(T)© are also polymorphic functions, each of which require the type parameter ©T© to have an assignment operator, default and copy constructors, and destructor. When choosing an interpretation for ©S2©, one option is ©box(S3)©, for some type ©S3©.
    339340\item The previous step repeats until stopped, with four times as much work performed at each step.
    340341\end{itemize}
    341 This problem can occur in any resolution context where a polymorphic function that can satisfy its own type assertions is required for a possible interpretation of an expression with no constraints on its type, and is thus not limited to combinations of generic types with ©void*© conversions, though constructors for generic types often satisfy their own assertions and a polymorphic conversion such as the ©void*© conversion to a polymorphic variable can create an expression with no constraints on its type.
     342This problem can occur in any resolution context where a polymorphic function can satisfy its own type assertions is required for a possible interpretation of an expression with no constraints on its type, and is thus not limited to combinations of generic types with ©void*© conversions.
     343However, constructors for generic types often satisfy their own assertions and a polymorphic conversion such as the ©void*© conversion to a polymorphic variable is a common way to create an expression with no constraints on its type.
    342344As discussed above, the \CFA expression resolver must handle this possible infinite recursion somehow, and it occurs fairly naturally in code like the above that uses generic types.
    343345
     
    345347\CFA adds \emph{tuple types} to C, a syntactic facility for referring to lists of values anonymously or with a single identifier.
    346348An identifier may name a tuple, and a function may return one.
    347 Particularly relevantly for resolution, a tuple may be implicitly \emph{destructured} into a list of values, as in the call to ©swap© below:
    348 \begin{lstlisting}
    349 [char, char] x = [ '!', '?' ];
    350 int x = 42;
    351 
    352 forall(otype T) [T, T] swap( T a, T b ) { return [b, a]; }
     349Particularly relevantly for resolution, a tuple may be implicitly \emph{destructured} into a list of values, as in the call to ©swap©:
     350\begin{lstlisting}
     351[char, char] x = [ '!', '?' ];  // (1)
     352int x = 42;  // (2)
     353
     354forall(otype T) [T, T] swap( T a, T b ) { return [b, a]; }  // (3)
    353355
    354356x = swap( x ); // destructure [char, char] x into two elements of parameter list
    355357// cannot use int x for parameter, not enough arguments to swap
    356 \end{lstlisting}
    357 Tuple destructuring means that the mapping from the position of a subexpression in the argument list to the position of a paramter in the function declaration is not straightforward, as some arguments may be expandable to different numbers of parameters, like ©x© above.
     358
     359void swap( int, char, char ); // (4)
     360
     361swap( x, x ); // resolved as (4) on (2) and (1)
     362// (3) on (2) and (2) is close, but the polymorphic binding makes it not minimal-cost
     363\end{lstlisting}
     364Tuple destructuring means that the mapping from the position of a subexpression in the argument list to the position of a paramter in the function declaration is not straightforward, as some arguments may be expandable to different numbers of parameters, like ©x© above.
     365In the second example, the second ©x© argument can be resolved starting at the second or third parameter of ©swap©, depending which interpretation of ©x© was chosen for the first argument.
    358366
    359367\subsection{Reference Types}
    360368I have been designing \emph{reference types} for \CFA, in collaboration with the rest of the \CFA research team.
    361369Given some type ©T©, a ©T&© (``reference to ©T©'') is essentially an automatically dereferenced pointer; with these semantics most of the C standard's discussions of lvalues can be expressed in terms of references instead, with the benefit of being able to express the difference between the reference and non-reference version of a type in user code.
    362 References preserve C's existing qualifier-dropping lvalue-to-rvalue conversion (\eg a ©const volatile int&© can be implicitly converted to a bare ©int©); the reference proposal also adds a rvalue-to-lvalue conversion to \CFA, implemented by storing the value in a new compiler-generated temporary and passing a reference to the temporary.
    363 These two conversions can chain, producing a qualifier-dropping conversion for references, for instance converting a reference to a ©const int© into a reference to a non-©const int© by copying the originally refered to value into a fresh temporary and taking a reference to this temporary, as below:
     370References preserve C's existing qualifier-dropping lvalue-to-rvalue conversion (\eg a ©const volatile int&© can be implicitly converted to a bare ©int©).
     371The reference proposal also adds a rvalue-to-lvalue conversion to \CFA, implemented by storing the value in a new compiler-generated temporary and passing a reference to the temporary.
     372These two conversions can chain, producing a qualifier-dropping conversion for references, for instance converting a reference to a ©const int© into a reference to a non-©const int© by copying the originally refered to value into a fresh temporary and taking a reference to this temporary, as in:
    364373\begin{lstlisting}
    365374const int magic = 42;
     
    369378print_inc( magic ); // legal; implicitly generated code in green below:
    370379
    371 ¢int tmp = magic;¢ // copies to safely strip const-qualifier
     380¢int tmp = magic;¢ // to safely strip const-qualifier
    372381¢print_inc( tmp );¢ // tmp is incremented, magic is unchanged
    373382\end{lstlisting}
    374 These reference conversions may also chain with the other implicit type conversions.
    375 The main implication of this for expression resolution is the multiplication of available implicit conversions, though in a restricted context that may be able to be treated efficiently as a special case.
     383These reference conversions may also chain with the other implicit type-conversions.
     384The main implication of the reference conversions for expression resolution is the multiplication of available implicit conversions, though given the restricted context reference conversions may be able to be treated efficiently as a special case of implicit conversions.
    376385
    377386\subsection{Special Literal Types}
    378387Another proposal currently under consideration for the \CFA type-system is assigning special types to the literal values ©0© and ©1©.
    379 Implicit conversions from these types allow ©0© and ©1© to be considered as values of many different types, depending on context, allowing expression desugarings like ©if ( x ) {}© $\Rightarrow$ ©if ( x != 0 ) {}© to be implemented efficiently and precicely.
     388Implicit conversions from these types allow ©0© and ©1© to be considered as values of many different types, depending on context, allowing expression desugarings like ©if ( x ) {}© $\Rightarrow$ ©if ( x != 0 ) {}© to be implemented efficiently and precisely.
    380389This approach is a generalization of C's existing behaviour of treating ©0© as either an integer zero or a null pointer constant, and treating either of those values as boolean false.
    381390The main implication for expression resolution is that the frequently encountered expressions ©0© and ©1© may have a large number of valid interpretations.
     
    386395int somefn(char) = delete;
    387396\end{lstlisting}
    388 This feature is typically used in \CCeleven to make a type non-copyable by deleting its copy constructor and assignment operator, or forbidding some interpretations of a polymorphic function by specifically deleting the forbidden overloads.
    389 To add a similar feature to \CFA would involve including the deleted function declarations in expression resolution along with the normal declarations, but producing a compiler error if the deleted function was the best resolution.
     397This feature is typically used in \CCeleven to make a type non-copyable by deleting its copy constructor and assignment operator\footnote{In previous versions of \CC a type could be made non-copyable by declaring a private copy constructor and assignment operator, but not defining either. This idiom is well-known, but depends on some rather subtle and \CC-specific rules about private members and implicitly-generated functions; the deleted-function form is both clearer and less verbose.}, or forbidding some interpretations of a polymorphic function by specifically deleting the forbidden overloads\footnote{Specific polymorphic function overloads can also be forbidden in previous \CC versions through use of template metaprogramming techniques, though this advanced usage is beyond the skills of many programmers. A similar effect can be produced on an ad-hoc basis at the appropriate call sites through use of casts to determine the function type. In both cases, the deleted-function form is clearer and more concise.}.
     398To add a similar feature to \CFA involves including the deleted function declarations in expression resolution along with the normal declarations, but producing a compiler error if the deleted function is the best resolution.
    390399How conflicts should be handled between resolution of an expression to both a deleted and a non-deleted function is a small but open research question.
    391400
     
    404413%TODO: look up and lit review
    405414The second area of investigation is minimizing dependencies between argument-parameter matches; the current CFA compiler attempts to match entire argument combinations against functions at once, potentially attempting to match the same argument against the same parameter multiple times.
    406 Whether the feature set of \CFA admits an expression resolution algorithm where arguments can be matched to parameters independently of other arguments in the same function application is an area of open research; polymorphic type paramters produce enough of a cross-argument dependency that the problem is not trivial.
     415Whether the feature set of \CFA admits an expression resolution algorithm where arguments can be matched to parameters independently of other arguments in the same function application is an area of open research; polymorphic type paramters produce enough cross-argument dependencies that the problem is not trivial.
    407416If cross-argument resolution dependencies cannot be completely eliminated, effective caching strategies to reduce duplicated work between equivalent argument-parameter matches in different combinations may mitigate the asymptotic defecits of the whole-combination matching approach.
    408417The final area of investigation is heuristics and algorithmic approaches to reduce the number of argument interpretations considered in the common case; if argument-parameter matches cannot be made independent, even small reductions in $i$ should yield significant reductions in the $i^{p+1}$ resolver runtime factor.
     
    412421
    413422\subsection{Argument-Parameter Matching}
    414 The first axis for consideration is argument-parameter matching direction --- whether the type matching for a candidate function to a set of candidate arguments is directed by the argument types or the parameter types.
     423The first axis for consideration is the argument-parameter matching direction --- whether the type matching for a candidate function to a set of candidate arguments is directed by the argument types or the parameter types.
    415424For programming languages without implicit conversions, argument-parameter matching is essentially the entirety of the expression resolution problem, and is generally referred to as ``overload resolution'' in the literature.
    416 All expression resolution algorithms form a DAG of interpretations, some explicitly, some implicitly; in this DAG, arcs point from function-call interpretations to argument interpretations, as below:
     425All expression-resolution algorithms form a DAG of interpretations, some explicitly, some implicitly; in this DAG, arcs point from function-call interpretations to argument interpretations, as in Figure~\ref{fig:res_dag}:
    417426\begin{figure}[h]
    418427\centering
     
    433442\end{figure}
    434443
    435 Note that some interpretations may be part of more than one super-interpretation, as with $p_i$ in the bottom row, while some valid subexpression interpretations, like $f_d$ in the middle row, are not used in any interpretation of their containing expression.
     444Note that some interpretations may be part of more than one super-interpretation, as with the second $p_i$ in the bottom row, while some valid subexpression interpretations, like $f_d$ in the middle row, are not used in any interpretation of their superexpression.
    436445
    437446\subsubsection{Argument-directed (Bottom-up)}
     
    451460A reasonable hybrid approach might take a top-down approach when the expression to be matched has a fixed type, and a bottom-up approach in untyped contexts.
    452461This approach may involve switching from one type to another at different levels of the expression tree.
    453 For instance:
     462For instance, in:
    454463\begin{lstlisting}
    455464forall(otype T)
     
    460469int x = f( f( '!' ) );
    461470\end{lstlisting}
    462 The outer call to ©f© must have a return type that is (implicitly convertable to) ©int©, so a top-down approach is used to select \textit{(1)} as the proper interpretation of ©f©. \textit{(1)}'s parameter ©x©, however, is an unbound type variable, and can thus take a value of any complete type, providing no guidance for the choice of candidate for the inner call to ©f©. The leaf expression ©'!'©, however, determines a zero-cost interpretation of the inner ©f© as \textit{(2)}, providing a minimal-cost expression resolution where ©T© is bound to ©void*©.
    463 
    464 Deciding when to switch between bottom-up and top-down resolution to minimize wasted work in a hybrid algorithm is a necessarily heuristic process, and though finding good heuristics for which subexpressions to swich matching strategies on is an open question, one reasonable approach might be to set a threshold $t$ for the number of candidate functions, and to use top-down resolution for any subexpression with fewer than $t$ candidate functions, to minimize the number of unmatchable argument interpretations computed, but to use bottom-up resolution for any subexpression with at least $t$ candidate functions, to reduce duplication in argument interpretation computation between the different candidate functions.
     471the outer call to ©f© must have a return type that is (implicitly convertable to) ©int©, so a top-down approach is used to select \textit{(1)} as the proper interpretation of ©f©. \textit{(1)}'s parameter ©x©, however, is an unbound type variable, and can thus take a value of any complete type, providing no guidance for the choice of candidate for the inner call to ©f©. The leaf expression ©'!'©, however, determines a zero-cost interpretation of the inner ©f© as \textit{(2)}, providing a minimal-cost expression resolution where ©T© is bound to ©void*©.
     472
     473Deciding when to switch between bottom-up and top-down resolution to minimize wasted work in a hybrid algorithm is a necessarily heuristic process, and finding good heuristics for which subexpressions to swich matching strategies on is an open question.
     474One reasonable approach might be to set a threshold $t$ for the number of candidate functions, and to use top-down resolution for any subexpression with fewer than $t$ candidate functions, to minimize the number of unmatchable argument interpretations computed, but to use bottom-up resolution for any subexpression with at least $t$ candidate functions, to reduce duplication in argument interpretation computation between the different candidate functions.
    465475
    466476Ganzinger and Ripken~\cite{Ganzinger80} propose an approach (later refined by Pennello~\etal~\cite{Pennello80}) that uses a top-down filtering pass followed by a bottom-up filtering pass to reduce the number of candidate interpretations; they prove that for the Ada programming language a small number of such iterations is sufficient to converge to a solution for the expression resolution problem.
    467477Persch~\etal~\cite{PW:overload} developed a similar two-pass approach where the bottom-up pass is followed by the top-down pass.
    468 These algorithms differ from the hybrid approach under investigation in that they take multiple passes over the expression tree to yield a solution, and also in that they apply both filtering heuristics to all expression nodes; \CFA's polymorphic functions and implicit conversions make the approach of filtering out invalid types taken by all of these algorithms infeasible.
     478These algorithms differ from the hybrid approach under investigation in that they take multiple passes over the expression tree to yield a solution, and that they also apply both filtering heuristics to all expression nodes; \CFA's polymorphic functions and implicit conversions make the approach of filtering out invalid types taken by all of these algorithms infeasible.
    469479
    470480\subsubsection{Common Subexpression Caching}
     
    480490\CC~\cite{ANSI98:C++} includes both name overloading and implicit conversions in its expression resolution specification, though unlike \CFA it does complete type-checking on a generated monomorphization of template functions, where \CFA simply checks a list of type constraints.
    481491The upcoming Concepts standard~\cite{C++concepts} defines a system of type constraints similar in principle to \CFA's.
    482 Cormack and Wright~\cite{Cormack90} present an algorithm which integrates overload resolution with a polymorphic type inference approach very similar to \CFA's.
     492Cormack and Wright~\cite{Cormack90} present an algorithm that integrates overload resolution with a polymorphic type inference approach very similar to \CFA's.
    483493However, their algorithm does not account for implicit conversions other than polymorphic type binding and their discussion of their overload resolution algorithm is not sufficiently detailed to classify it with the other argument-parameter matching approaches\footnote{Their overload resolution algorithm is possibly a variant of Ganzinger and Ripken~\cite{Ganzinger80} or Pennello~\etal~\cite{Pennello80}, modified to allow for polymorphic type binding.}.
    484494
     
    486496Bilson does account for implicit conversions in his algorithm, but it is unclear if the approach is optimal.
    487497His algorithm integrates checking for valid implicit conversions into the argument-parameter-matching step, essentially trading more expensive matching for a smaller number of argument interpretations.
    488 This approach may result in the same subexpression being checked for a type match with the same type multiple times, though again memoization may mitigate this cost, and this approach does not generate implicit conversions that are not useful to match the containing function.
    489 Calculating implicit conversions on parameters pairs naturally with a top-down approach to expression resolution, though it can also be used in a bottom-up approach, as Bilson demonstrates.
     498This approach may result in the same subexpression being checked for a type match with the same type multiple times, though again memoization may mitigate this cost; however, this approach does not generate implicit conversions that are not useful to match the containing function.
    490499
    491500\subsubsection{On Arguments}
    492501Another approach is to generate a set of possible implicit conversions for each set of interpretations of a given argument.
    493502This approach has the benefit of detecting ambiguous interpretations of arguments at the level of the argument rather than its containing call, never finds more than one interpretation of the argument with a given type, and re-uses calculation of implicit conversions between function candidates.
    494 On the other hand, this approach may unncessarily generate argument interpretations that never match any parameter, wasting work.
    495 Further, in the presence of tuple types this approach may lead to a combinatorial explosion of argument interpretations considered, unless the tuple can be considered as a sequence of elements rather than a unified whole.
    496 Calculating implicit conversions on arguments is a viable approach for bottom-up expression resolution, though it may be difficult to apply in a top-down approach due to the presence of a target type for the expression interpretation.
     503On the other hand, this approach may unnecessarily generate argument interpretations that never match any parameter, wasting work.
     504Furthermore, in the presence of tuple types, this approach may lead to a combinatorial explosion of argument interpretations considered, unless the tuple can be considered as a sequence of elements rather than a unified whole.
    497505
    498506\subsection{Candidate Set Generation}
    499 All the algorithms discussed to this point generate the complete set of candidate argument interpretations before attempting to match the containing function call expression.
    500 However, given that the top-level expression interpretation that is ultimately chosen is the minimal-cost valid interpretation, any consideration of non-minimal-cost interpretations is in some sense wasted work.
    501 Under the assumption that that programmers generally write function calls with relatively low-cost interpretations, a possible work-saving heuristic is to generate only the lowest-cost argument interpretations first, attempt to find a valid top-level interpretation using them, and only if that fails generate the next higher-cost argument interpretations.
     507All the algorithms discussed to this point generate the complete set of candidate argument interpretations before attempting to match the containing function-call expression.
     508However, given that the top-level expression interpretation that is ultimately chosen is the minimal-cost valid interpretation, any consideration of non-minimal-cost interpretations is wasted work.
     509Under the assumption that programmers generally write function calls with relatively low-cost interpretations, a possible work-saving heuristic is to generate only the lowest-cost argument interpretations first, attempt to find a valid top-level interpretation using them, and only if that fails generate the next higher-cost argument interpretations.
    502510
    503511\subsubsection{Eager}
     
    563571This comparison closes Baker's open research question, as well as potentially improving Bilson's \CFA compiler.
    564572
    565 Rather than testing all of these algorithms in-place in the \CFA compiler, a resolver prototype is being developed which acts on a simplified input language encapsulating the essential details of the \CFA type-system\footnote{Note this simplified input language is not a usable programming language.}.
     573Rather than testing all of these algorithms in-place in the \CFA compiler, a resolver prototype is being developed that acts on a simplified input language encapsulating the essential details of the \CFA type-system\footnote{Note this simplified input language is not a usable programming language.}.
    566574Multiple variants of this resolver prototype will be implemented, each encapsulating a different expression resolution variant, sharing as much code as feasible.
    567575These variants will be instrumented to test runtime performance, and run on a variety of input files; the input files may be generated programmatically or from exisiting code in \CFA or similar languages.
     
    571579As an example, there are currently multiple open proposals for how implicit conversions should interact with polymorphic type binding in \CFA, each with distinct levels of expressive power; if the resolver prototype is modified to support each proposal, the optimal algorithm for each proposal can be compared, providing an empirical demonstration of the trade-off between expressive power and compiler runtime.
    572580
    573 This proposed project should provide valuable data on how to implement a performant compiler for modern programming languages such as \CFA with powerful static type-systems, specifically targeting the feature interaction between name overloading and implicit conversions.
     581This proposed project should provide valuable data on how to implement a performant compiler for programming languages such as \CFA with powerful static type-systems, specifically targeting the feature interaction between name overloading and implicit conversions.
    574582This work is not limited in applicability to \CFA, but may also be useful for supporting efficient compilation of the upcoming Concepts standard~\cite{C++concepts} for \CC template constraints, for instance.
    575583
  • doc/user/user.tex

    r79841be r6943a987  
    1111%% Created On       : Wed Apr  6 14:53:29 2016
    1212%% Last Modified By : Peter A. Buhr
    13 %% Last Modified On : Tue Aug  2 17:39:02 2016
    14 %% Update Count     : 1286
     13%% Last Modified On : Sun Aug 14 08:23:06 2016
     14%% Update Count     : 1323
    1515%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    1616
     
    317317
    318318\item
    319 \Indexc{-no-include-std}\index{compilation option!-no-include-std@©-no-include-std©}
     319\Indexc{-no-include-stdhdr}\index{compilation option!-no-include-stdhdr@©-no-include-stdhdr©}
    320320Do not supply ©extern "C"© wrappers for \Celeven standard include files (see~\VRef{s:StandardHeaders}).
    321321\textbf{This option is \emph{not} the default.}
     
    807807
    808808
     809\section{Backquote Identifiers}
     810\label{s:BackquoteIdentifiers}
     811
     812\CFA accommodates keyword clashes by syntactic transformations using the \CFA backquote escape-mechanism:
     813\begin{lstlisting}
     814int `otype` = 3;                                // make keyword an identifier
     815double `choose` = 3.5;
     816\end{lstlisting}
     817Programs can be converted easily by enclosing keyword identifiers in backquotes, and the backquotes can be removed later when the identifier name is changed to an non-keyword name.
     818Clashes in C header files (see~\VRef{s:StandardHeaders}) can be handled automatically using the preprocessor, ©#include_next© and ©-I filename©:
     819\begin{lstlisting}
     820// include file uses the CFA keyword "otype".
     821#if ! defined( otype )                  // nesting ?
     822#define otype `otype`
     823#define __CFA_BFD_H__
     824#endif // ! otype
     825
     826#include_next <bfd.h>                   // must have internal check for multiple expansion
     827
     828#if defined( otype ) && defined( __CFA_BFD_H__ )        // reset only if set
     829#undef otype
     830#undef __CFA_BFD_H__
     831#endif // otype && __CFA_BFD_H__
     832\end{lstlisting}
     833
     834
    809835\section{Type Operators}
    810836
     
    10111037Alternatively, prototype definitions can be eliminated by using a two-pass compilation, and implicitly creating header files for exports.
    10121038The former is easy to do, while the latter is more complex.
    1013 Currently, \CFA does \emph{not} attempt to support named arguments.
     1039
     1040Furthermore, named arguments do not work well in a \CFA-style programming-languages because they potentially introduces a new criteria for type matching.
     1041For example, it is technically possible to disambiguate between these two overloaded definitions of ©f© based on named arguments at the call site:
     1042\begin{lstlisting}
     1043int f( int i, int j );
     1044int f( int x, double y );
     1045
     1046f( j : 3, i : 4 );                              §\C{// 1st f}§
     1047f( x : 7, y : 8.1 );                    §\C{// 2nd f}§
     1048f( 4, 5 );                                              §\C{// ambiguous call}§
     1049\end{lstlisting}
     1050However, named arguments compound routine resolution in conjunction with conversions:
     1051\begin{lstlisting}
     1052f( i : 3, 5.7 );                                §\C{// ambiguous call ?}§
     1053\end{lstlisting}
     1054Depending on the cost associated with named arguments, this call could be resolvable or ambiguous.
     1055Adding named argument into the routine resolution algorithm does not seem worth the complexity.
     1056Therefore, \CFA does \emph{not} attempt to support named arguments.
    10141057
    10151058\item[Default Arguments]
     
    10211064the allowable positional calls are:
    10221065\begin{lstlisting}
    1023 p();                            §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§
    1024 p( 4 );                         §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§
    1025 p( 4, 4 );                      §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§
    1026 p( 4, 4, 4 );           §\C{// rewrite $\Rightarrow$ p( 4, 4, 4 )}§
     1066p();                                                    §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§
     1067p( 4 );                                                 §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§
     1068p( 4, 4 );                                              §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§
     1069p( 4, 4, 4 );                                   §\C{// rewrite $\Rightarrow$ p( 4, 4, 4 )}§
    10271070// empty arguments
    1028 p(  , 4, 4 );           §\C{// rewrite $\Rightarrow$ p( 1, 4, 4 )}§
    1029 p( 4,  , 4 );           §\C{// rewrite $\Rightarrow$ p( 4, 2, 4 )}§
    1030 p( 4, 4,   );           §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§
    1031 p( 4,  ,   );           §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§
    1032 p(  , 4,   );           §\C{// rewrite $\Rightarrow$ p( 1, 4, 3 )}§
    1033 p(  ,  , 4 );           §\C{// rewrite $\Rightarrow$ p( 1, 2, 4 )}§
    1034 p(  ,  ,   );           §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§
     1071p(  , 4, 4 );                                   §\C{// rewrite $\Rightarrow$ p( 1, 4, 4 )}§
     1072p( 4,  , 4 );                                   §\C{// rewrite $\Rightarrow$ p( 4, 2, 4 )}§
     1073p( 4, 4,   );                                   §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§
     1074p( 4,  ,   );                                   §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§
     1075p(  , 4,   );                                   §\C{// rewrite $\Rightarrow$ p( 1, 4, 3 )}§
     1076p(  ,  , 4 );                                   §\C{// rewrite $\Rightarrow$ p( 1, 2, 4 )}§
     1077p(  ,  ,   );                                   §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§
    10351078\end{lstlisting}
    10361079Here the missing arguments are inserted from the default values in the parameter list.
     
    10671110The conflict occurs because both named and ellipse arguments must appear after positional arguments, giving two possibilities:
    10681111\begin{lstlisting}
    1069 p( /* positional */, . . ., /* named */ );
    1070 p( /* positional */, /* named */, . . . );
     1112p( /* positional */, ... , /* named */ );
     1113p( /* positional */, /* named */, ... );
    10711114\end{lstlisting}
    10721115While it is possible to implement both approaches, the first possibly is more complex than the second, \eg:
    10731116\begin{lstlisting}
    1074 p( int x, int y, int z, . . . );
    1075 p( 1, 4, 5, 6, z : 3, y : 2 ); §\C{// assume p( /* positional */, . . ., /* named */ );}§
    1076 p( 1, z : 3, y : 2, 4, 5, 6 ); §\C{// assume p( /* positional */, /* named */, . . . );}§
     1117p( int x, int y, int z, ... );
     1118p( 1, 4, 5, 6, z : 3, y : 2 ); §\C{// assume p( /* positional */, ... , /* named */ );}§
     1119p( 1, z : 3, y : 2, 4, 5, 6 ); §\C{// assume p( /* positional */, /* named */, ... );}§
    10771120\end{lstlisting}
    10781121In the first call, it is necessary for the programmer to conceptually rewrite the call, changing named arguments into positional, before knowing where the ellipse arguments begin.
     
    10821125The problem is exacerbated with default arguments, \eg:
    10831126\begin{lstlisting}
    1084 void p( int x, int y = 2, int z = 3. . . );
    1085 p( 1, 4, 5, 6, z : 3 );         §\C{// assume p( /* positional */, . . ., /* named */ );}§
    1086 p( 1, z : 3, 4, 5, 6 );         §\C{// assume p( /* positional */, /* named */, . . . );}§
     1127void p( int x, int y = 2, int z = 3... );
     1128p( 1, 4, 5, 6, z : 3 );         §\C{// assume p( /* positional */, ... , /* named */ );}§
     1129p( 1, z : 3, 4, 5, 6 );         §\C{// assume p( /* positional */, /* named */, ... );}§
    10871130\end{lstlisting}
    10881131The first call is an error because arguments 4 and 5 are actually positional not ellipse arguments;
     
    11291172\subsection{Type Nesting}
    11301173
    1131 \CFA allows \Index{type nesting}, and type qualification of the nested types (see \VRef[Figure]{f:TypeNestingQualification}), where as C hoists\index{type hoisting} (refactors) nested types into the enclosing scope and has no type qualification.
     1174\CFA allows \Index{type nesting}, and type qualification of the nested typres (see \VRef[Figure]{f:TypeNestingQualification}), where as C hoists\index{type hoisting} (refactors) nested types into the enclosing scope and has no type qualification.
    11321175\begin{figure}
     1176\centering
    11331177\begin{tabular}{@{}l@{\hspace{3em}}l|l@{}}
    11341178\multicolumn{1}{c@{\hspace{3em}}}{\textbf{C Type Nesting}}      & \multicolumn{1}{c}{\textbf{C Implicit Hoisting}}      & \multicolumn{1}{|c}{\textbf{\CFA}}    \\
     
    13971441Mass assignment has the following form:
    13981442\begin{lstlisting}
    1399 [ §\emph{lvalue}§, ..., §\emph{lvalue}§ ] = §\emph{expr}§;
     1443[ §\emph{lvalue}§, ... , §\emph{lvalue}§ ] = §\emph{expr}§;
    14001444\end{lstlisting}
    14011445\index{lvalue}
     
    14371481Multiple assignment has the following form:
    14381482\begin{lstlisting}
    1439 [ §\emph{lvalue}§, . . ., §\emph{lvalue}§ ] = [ §\emph{expr}§, . . ., §\emph{expr}§ ];
     1483[ §\emph{lvalue}§, ... , §\emph{lvalue}§ ] = [ §\emph{expr}§, ... , §\emph{expr}§ ];
    14401484\end{lstlisting}
    14411485\index{lvalue}
     
    18731917\begin{lstlisting}
    18741918switch ( i ) {
    1875   ®case 1, 3, 5®:
     1919  case ®1, 3, 5®:
    18761920        ...
    1877   ®case 2, 4, 6®:
     1921  case ®2, 4, 6®:
    18781922        ...
    18791923}
     
    19061950\begin{lstlisting}
    19071951switch ( i ) {
    1908   ®case 1~5:®
     1952  case ®1~5:®
    19091953        ...
    1910   ®case 10~15:®
     1954  case ®10~15:®
    19111955        ...
    19121956}
     
    19151959\begin{lstlisting}
    19161960switch ( i )
    1917   case 1 ... 5:
     1961  case ®1 ... 5®:
    19181962        ...
    1919   case 10 ... 15:
     1963  case ®10 ... 15®:
    19201964        ...
    19211965}
     
    43694413
    43704414
     4415\section{Incompatible}
     4416
     4417The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{ANSI14:C++}.
     4418
     4419\begin{enumerate}
     4420\item
     4421\begin{description}
     4422\item[Change:] add new keywords \\
     4423New keywords are added to \CFA (see~\VRef{s:NewKeywords}).
     4424\item[Rationale:] keywords added to implement new semantics of \CFA.
     4425\item[Effect on original feature:] change to semantics of well-defined feature. \\
     4426Any ISO C programs using these keywords as identifiers are invalid \CFA programs.
     4427\item[Difficulty of converting:] keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism (see~\VRef{s:BackquoteIdentifiers}):
     4428\item[How widely used:] clashes among new \CFA keywords and existing identifiers are rare.
     4429\end{description}
     4430
     4431\item
     4432\begin{description}
     4433\item[Change:] type of character literal ©int© to ©char© to allow more intuitive overloading:
     4434\begin{lstlisting}
     4435int rtn( int i );
     4436int rtn( char c );
     4437rtn( 'x' );                                             §\C{// programmer expects 2nd rtn to be called}§
     4438\end{lstlisting}
     4439\item[Rationale:] it is more intuitive for the call to ©rtn© to match the second version of definition of ©rtn© rather than the first.
     4440In particular, output of ©char© variable now print a character rather than the decimal ASCII value of the character.
     4441\begin{lstlisting}
     4442sout | 'x' | " " | (int)'x' | endl;
     4443x 120
     4444\end{lstlisting}
     4445Having to cast ©'x'© to ©char© is non-intuitive.
     4446\item[Effect on original feature:] change to semantics of well-defined feature that depend on:
     4447\begin{lstlisting}
     4448sizeof( 'x' ) == sizeof( int )
     4449\end{lstlisting}
     4450no long work the same in \CFA programs.
     4451\item[Difficulty of converting:] simple
     4452\item[How widely used:] programs that depend upon ©sizeof( 'x' )© are rare and can be changed to ©sizeof(char)©.
     4453\end{description}
     4454
     4455\item
     4456\begin{description}
     4457\item[Change:] make string literals ©const©:
     4458\begin{lstlisting}
     4459char * p = "abc";                               §\C{// valid in C, deprecated in \CFA}§
     4460char * q = expr ? "abc" : "de"; §\C{// valid in C, invalid in \CFA}§
     4461\end{lstlisting}
     4462The type of a string literal is changed from ©[] char© to ©const [] char©.
     4463Similarly, the type of a wide string literal is changed from ©[] wchar_t© to ©const [] wchar_t©.
     4464\item[Rationale:] This change is a safety issue:
     4465\begin{lstlisting}
     4466char * p = "abc";
     4467p[0] = 'w';                                             §\C{// segment fault or change constant literal}§
     4468\end{lstlisting}
     4469The same problem occurs when passing a string literal to a routine that changes its argument.
     4470\item[Effect on original feature:] change to semantics of well-defined feature.
     4471\item[Difficulty of converting:] simple syntactic transformation, because string literals can be converted to ©char *©.
     4472\item[How widely used:] programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are rare.
     4473\end{description}
     4474
     4475\item
     4476\begin{description}
     4477\item[Change:] remove \newterm{tentative definitions}, which only occurs at file scope:
     4478\begin{lstlisting}
     4479int i;                                                  §\C{// forward definition}§
     4480int *j = ®&i®;                                  §\C{// forward reference, valid in C, invalid in \CFA}§
     4481int i = 0;                                              §\C{// definition}§
     4482\end{lstlisting}
     4483is valid in C, and invalid in \CFA because duplicate overloaded object definitions at the same scope level are disallowed.
     4484This change makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example,
     4485\begin{lstlisting}
     4486struct X { int i; struct X *next; };
     4487static struct X a;                              §\C{// forward definition}§
     4488static struct X b = { 0, ®&a® };        §\C{// forward reference, valid in C, invalid in \CFA}§
     4489static struct X a = { 1, &b };  §\C{// definition}§
     4490\end{lstlisting}
     4491\item[Rationale:] avoids having different initialization rules for builtin types and userdefined types.
     4492\item[Effect on original feature:] change to semantics of well-defined feature.
     4493\item[Difficulty of converting:] the initializer for one of a set of mutually-referential file-local static objects must invoke a routine call to achieve the initialization.
     4494\item[How widely used:] seldom
     4495\end{description}
     4496
     4497\item
     4498\begin{description}
     4499\item[Change:] have ©struct© introduce a scope for nested types:
     4500\begin{lstlisting}
     4501enum ®Colour® { R, G, B, Y, C, M };
     4502struct Person {
     4503        enum ®Colour® { R, G, B };      §\C{// nested type}§
     4504        struct Face {                           §\C{// nested type}§
     4505                ®Colour® Eyes, Hair;    §\C{// type defined outside (1 level)}§
     4506        };
     4507        ß.ß®Colour® shirt;                      §\C{// type defined outside (top level)}§
     4508        ®Colour® pants;                         §\C{// type defined same level}§
     4509        Face looks[10];                         §\C{// type defined same level}§
     4510};
     4511®Colour® c = R;                                 §\C{// type/enum defined same level}§
     4512Personß.ß®Colour® pc = Personß.ßR;      §\C{// type/enum defined inside}§
     4513Personß.ßFace pretty;                   §\C{// type defined inside}§
     4514\end{lstlisting}
     4515In C, the name of the nested types belongs to the same scope as the name of the outermost enclosing structure, i.e., the nested types are hoisted to the scope of the outer-most type, which is not useful and confusing.
     4516\CFA is C \emph{incompatible} on this issue, and provides semantics similar to \Index*[C++]{\CC}.
     4517Nested types are not hoisted and can be referenced using the field selection operator ``©.©'', unlike the \CC scope-resolution operator ``©::©''.
     4518\item[Rationale:] ©struct© scope is crucial to \CFA as an information structuring and hiding mechanism.
     4519\item[Effect on original feature:] change to semantics of well-defined feature.
     4520\item[Difficulty of converting:] Semantic transformation.
     4521\item[How widely used:] C programs rarely have nest types because they are equivalent to the hoisted version.
     4522\end{description}
     4523
     4524\item
     4525\begin{description}
     4526\item[Change:] In C++, the name of a nested class is local to its enclosing class.
     4527\item[Rationale:] C++ classes have member functions which require that classes establish scopes.
     4528\item[Difficulty of converting:] Semantic transformation. To make the struct type name visible in the scope of the enclosing struct, the struct tag could be declared in the scope of the enclosing struct, before the enclosing struct is defined. Example:
     4529\begin{lstlisting}
     4530struct Y;                                               §\C{// struct Y and struct X are at the same scope}§
     4531struct X {
     4532struct Y { /* ... */ } y;
     4533};
     4534\end{lstlisting}
     4535All the definitions of C struct types enclosed in other struct definitions and accessed outside the scope of the enclosing struct could be exported to the scope of the enclosing struct.
     4536Note: this is a consequence of the difference in scope rules, which is documented in 3.3.
     4537\item[How widely used:] Seldom.
     4538\end{description}
     4539
     4540\item
     4541\begin{description}
     4542\item[Change:] comma expression is disallowed as subscript
     4543\item[Rationale:] safety issue to prevent subscripting error for multidimensional arrays: ©x[i,j]© instead of ©x[i][j]©, and this syntactic form then taken by \CFA for new style arrays.
     4544\item[Effect on original feature:] change to semantics of well-defined feature.
     4545\item[Difficulty of converting:] semantic transformation of ©x[i,j]© to ©x[(i,j)]©
     4546\item[How widely used:] seldom.
     4547\end{description}
     4548\end{enumerate}
     4549
     4550
    43714551\section{New Keywords}
    43724552\label{s:NewKeywords}
    43734553
    43744554\begin{quote2}
    4375 \begin{tabular}{ll}
    4376 ©catch©                 & ©lvalue©              \\
    4377 ©catchResume©   &                               \\
    4378 ©choose©                & ©otype©               \\
    4379                                 &                               \\
    4380 ©disable©               & ©throw©               \\
    4381 ©dtype©                 & ©throwResume© \\
    4382                                 & ©trait©               \\
    4383 ©enable©                & ©try©                 \\
    4384                                 &                               \\
    4385 ©fallthrough©                                   \\
    4386 ©fallthru©                                              \\
    4387 ©finally©                                               \\
    4388 ©forall©                                                \\
    4389 ©ftype©                                                 \\
     4555\begin{tabular}{lll}
     4556©catch©                 & ©fallthrough© & ©otype©               \\
     4557©catchResume©   & ©fallthru©    & ©throw©               \\
     4558©choose©                & ©finally©             & ©throwResume© \\
     4559©disable©               & ©forall©              & ©trait©               \\
     4560©dtype©                 & ©ftype©               & ©try©                 \\
     4561©enable©                & ©lvalue©              &                               \\
    43904562\end{tabular}
    43914563\end{quote2}
     
    43954567\label{s:StandardHeaders}
    43964568
    4397 C prescribes the following standard header-files:
     4569C prescribes the following standard header-files~\cite[\S~7.1.2]{C11}:
    43984570\begin{quote2}
    43994571\begin{minipage}{\linewidth}
     
    44124584\end{minipage}
    44134585\end{quote2}
    4414 For the prescribed head-files, \CFA implicit wraps their includes in an ©extern "C"©;
     4586For the prescribed head-files, \CFA implicitly wraps their includes in an ©extern "C"©;
    44154587hence, names in these include files are not mangled\index{mangling!name} (see~\VRef{s:Interoperability}).
    44164588All other C header files must be explicitly wrapped in ©extern "C"© to prevent name mangling.
    4417 
    4418 
    4419 \section{Incompatible}
    4420 
    4421 The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{ANSI14:C++}.
    4422 
    4423 \begin{enumerate}
    4424 \item
    4425 \begin{description}
    4426 \item[Change:] add new keywords (see~\VRef{s:NewKeywords}) \\
    4427 New keywords are added to \CFA.
    4428 \item[Rationale:] keywords added to implement new semantics of \CFA.
    4429 \item[Effect on original feature:] change to semantics of well-defined feature. \\
    4430 Any ISO C programs using these keywords as identifiers are invalid \CFA programs.
    4431 \item[Difficulty of converting:] keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism:
    4432 \begin{lstlisting}
    4433 int `otype` = 3;                                // make keyword an identifier
    4434 double `choose` = 3.5;
    4435 \end{lstlisting}
    4436 Programs can be converted automatically by enclosing keyword identifiers in backquotes, and the backquotes can be remove later when the identifier name is changed.
    4437 Clashes in C system libraries (include files) can be handled automatically using preprocessor, ©#include_next© and ©-Ifilename©:
    4438 \begin{lstlisting}
    4439 // include file uses the CFA keyword "otype".
    4440 #if ! defined( otype )                  // nesting ?
    4441 #define otype `otype`
    4442 #define __CFA_BFD_H__
    4443 #endif // ! otype
    4444 
    4445 #include_next <bfd.h>                   // must have internal check for multiple expansion
    4446 
    4447 #if defined( otype ) && defined( __CFA_BFD_H__ )        // reset only if set
    4448 #undef otype
    4449 #undef __CFA_BFD_H__
    4450 #endif // otype && __CFA_BFD_H__
    4451 \end{lstlisting}
    4452 \item[How widely used:] clashes among new \CFA keywords and existing identifiers are rare.
    4453 \end{description}
    4454 
    4455 \item
    4456 \begin{description}
    4457 \item[Change:] type of character literal ©int© to ©char© to allow more intuitive overloading:
    4458 \begin{lstlisting}
    4459 int rtn( int i );
    4460 int rtn( char c );
    4461 rtn( 'x' );                                             // programmer expects 2nd rtn to be called
    4462 \end{lstlisting}
    4463 \item[Rationale:] it is more intuitive for the call to ©rtn© to match the second version of definition of ©rtn© rather than the first.
    4464 In particular, output of ©char© variable now print a character rather than the decimal ASCII value of the character.
    4465 \begin{lstlisting}
    4466 sout | 'x' | " " | (int)'x' | endl;
    4467 x 120
    4468 \end{lstlisting}
    4469 Having to cast ©'x'© to ©char© is non-intuitive.
    4470 \item[Effect on original feature:] change to semantics of well-defined feature that depend on:
    4471 \begin{lstlisting}
    4472 sizeof( 'x' ) == sizeof( int )
    4473 \end{lstlisting}
    4474 no long work the same in \CFA programs.
    4475 \item[Difficulty of converting:] simple
    4476 \item[How widely used:] programs that depend upon ©sizeof( 'x' )© are rare and can be changed to ©sizeof(char)©.
    4477 \end{description}
    4478 
    4479 \item
    4480 \begin{description}
    4481 \item[Change:] make string literals ©const©:
    4482 \begin{lstlisting}
    4483 char * p = "abc";                               // valid in C, deprecated in §\CFA§
    4484 char * q = expr ? "abc" : "de"; // valid in C, invalid in §\CFA§
    4485 \end{lstlisting}
    4486 The type of a string literal is changed from ©[] char© to ©const [] char©.
    4487 Similarly, the type of a wide string literal is changed from ©[] wchar_t© to ©const [] wchar_t©.
    4488 \item[Rationale:] This change is a safety issue:
    4489 \begin{lstlisting}
    4490 char * p = "abc";
    4491 p[0] = 'w';                                             // segment fault or change constant literal
    4492 \end{lstlisting}
    4493 The same problem occurs when passing a string literal to a routine that changes its argument.
    4494 \item[Effect on original feature:] change to semantics of well-defined feature.
    4495 \item[Difficulty of converting:] simple syntactic transformation, because string literals can be converted to ©char *©.
    4496 \item[How widely used:] programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are rare.
    4497 \end{description}
    4498 
    4499 \item
    4500 \begin{description}
    4501 \item[Change:] remove \newterm{tentative definitions}, which only occurs at file scope:
    4502 \begin{lstlisting}
    4503 int i;                                                  // forward definition
    4504 int *j = ®&i®;                                  // forward reference, valid in C, invalid in §\CFA§
    4505 int i = 0;                                              // definition
    4506 \end{lstlisting}
    4507 is valid in C, and invalid in \CFA because duplicate overloaded object definitions at the same scope level are disallowed.
    4508 This change makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example,
    4509 \begin{lstlisting}
    4510 struct X { int i; struct X *next; };
    4511 static struct X a;                              // forward definition
    4512 static struct X b = { 0, ®&a® };        // forward reference, valid in C, invalid in §\CFA§
    4513 static struct X a = { 1, &b };  // definition
    4514 \end{lstlisting}
    4515 \item[Rationale:] avoids having different initialization rules for builtin types and userdefined types.
    4516 \item[Effect on original feature:] change to semantics of well-defined feature.
    4517 \item[Difficulty of converting:] the initializer for one of a set of mutually-referential file-local static objects must invoke a routine call to achieve the initialization.
    4518 \item[How widely used:] seldom
    4519 \end{description}
    4520 
    4521 \item
    4522 \begin{description}
    4523 \item[Change:] have ©struct© introduce a scope for nested types
    4524 In C, the name of the nested types belongs to the same scope as the name of the outermost enclosing
    4525 Example:
    4526 \begin{lstlisting}
    4527 enum ®Colour® { R, G, B, Y, C, M };
    4528 struct Person {
    4529         enum ®Colour® { R, G, B };      // nested type
    4530         struct Face {                           // nested type
    4531                 ®Colour® Eyes, Hair;            // type defined outside (1 level)
    4532         };
    4533         ß.ß®Colour® shirt;                              // type defined outside (top level)
    4534         ®Colour® pants;                         // type defined same level
    4535         Face looks[10];                         // type defined same level
    4536 };
    4537 ®Colour® c = R;                                 // type/enum defined same level
    4538 Personß.ß®Colour® pc = Personß.ßR;      // type/enum defined inside
    4539 Personß.ßFace pretty;                           // type defined inside
    4540 \end{lstlisting}
    4541 \item[Rationale:] ©struct© scope is crucial to \CFA as an information structuring and hiding mechanism.
    4542 \item[Effect on original feature:] change to semantics of well-defined feature.
    4543 \item[Difficulty of converting:] Semantic transformation.
    4544 \item[How widely used:] C programs rarely have nest types because they are equivalent to the hoisted version.
    4545 
    4546 \CFA is C \emph{incompatible} on this issue, and provides semantics similar to \Index*[C++]{\CC}.
    4547 Nested types are not hoisted and can be referenced using the field selection operator ``©.©'', unlike the \CC scope-resolution operator ``©::©''.
    4548 Given that nested types in C are equivalent to not using them, \ie they are essentially useless, it is unlikely there are any realistic usages that break because of this incompatibility.
    4549 \end{description}
    4550 
    4551 \item
    4552 \begin{description}
    4553 \item[Change:] In C++, the name of a nested class is local to its enclosing class.
    4554 \item[Rationale:] C++ classes have member functions which require that classes establish scopes.
    4555 \item[Difficulty of converting:] Semantic transformation. To make the struct type name visible in the scope of the enclosing struct, the struct tag could be declared in the scope of the enclosing struct, before the enclosing struct is defined. Example:
    4556 \begin{lstlisting}
    4557 struct Y; // struct Y and struct X are at the same scope
    4558 struct X {
    4559 struct Y { /* ... */ } y;
    4560 };
    4561 \end{lstlisting}
    4562 All the definitions of C struct types enclosed in other struct definitions and accessed outside the scope of the enclosing struct could be exported to the scope of the enclosing struct.
    4563 Note: this is a consequence of the difference in scope rules, which is documented in 3.3.
    4564 \item[How widely used:] Seldom.
    4565 \end{description}
    4566 
    4567 \item
    4568 \begin{description}
    4569 \item[Change:] comma expression is disallowed as subscript
    4570 \item[Rationale:] safety issue to prevent subscripting error for multidimensional arrays: ©x[i,j]© instead of ©x[i][j]©, and this syntactic form then taken by \CFA for new style arrays.
    4571 \item[Effect on original feature:] change to semantics of well-defined feature.
    4572 \item[Difficulty of converting:] semantic transformation of ©x[i,j]© to ©x[(i,j)]©
    4573 \item[How widely used:] seldom.
    4574 \end{description}
    4575 \end{enumerate}
    45764589
    45774590
     
    47494762\subsection{malloc}
    47504763
     4764\leavevmode
    47514765\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    47524766forall( otype T ) T * malloc( void );§\indexc{malloc}§
     
    47654779forall( otype T ) T * memset( T * ptr );                                // remove when default value available
    47664780\end{lstlisting}
    4767 \
     4781
    47684782
    47694783\subsection{ato / strto}
    47704784
     4785\leavevmode
    47714786\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    47724787int ato( const char * ptr );§\indexc{ato}§
     
    47964811long double _Complex strto( const char * sptr, char ** eptr );
    47974812\end{lstlisting}
    4798 \
    47994813
    48004814
    48014815\subsection{bsearch / qsort}
    48024816
     4817\leavevmode
    48034818\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    48044819forall( otype T | { int ?<?( T, T ); } )
     
    48084823void qsort( const T * arr, size_t dimension );§\indexc{qsort}§
    48094824\end{lstlisting}
    4810 \
    48114825
    48124826
    48134827\subsection{abs}
    48144828
     4829\leavevmode
    48154830\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    48164831char abs( char );§\indexc{abs}§
     
    48254840long double abs( long double _Complex );
    48264841\end{lstlisting}
    4827 \
    48284842
    48294843
    48304844\subsection{random}
    48314845
     4846\leavevmode
    48324847\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    48334848void rand48seed( long int s );§\indexc{rand48seed}§
     
    48434858long double _Complex rand48();
    48444859\end{lstlisting}
    4845 \
    48464860
    48474861
    48484862\subsection{min / max / clamp / swap}
    48494863
     4864\leavevmode
    48504865\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    48514866forall( otype T | { int ?<?( T, T ); } )
     
    48614876void swap( T * t1, T * t2 );§\indexc{swap}§
    48624877\end{lstlisting}
    4863 \
    48644878
    48654879
     
    48724886\subsection{General}
    48734887
     4888\leavevmode
    48744889\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    48754890float fabs( float );§\indexc{fabs}§
     
    49174932long double nan( const char * );
    49184933\end{lstlisting}
    4919 \
    49204934
    49214935
    49224936\subsection{Exponential}
    49234937
     4938\leavevmode
    49244939\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    49254940float exp( float );§\indexc{exp}§
     
    49744989long double logb( long double );
    49754990\end{lstlisting}
    4976 \
    49774991
    49784992
    49794993\subsection{Power}
    49804994
     4995\leavevmode
    49814996\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    49824997float sqrt( float );§\indexc{sqrt}§
     
    50025017long double _Complex pow( long double _Complex, long double _Complex );
    50035018\end{lstlisting}
    5004 \
    50055019
    50065020
    50075021\subsection{Trigonometric}
    50085022
     5023\leavevmode
    50095024\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    50105025float sin( float );§\indexc{sin}§
     
    50585073long double atan( long double, long double );
    50595074\end{lstlisting}
    5060 \
    50615075
    50625076
    50635077\subsection{Hyperbolic}
    50645078
     5079\leavevmode
    50655080\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    50665081float sinh( float );§\indexc{sinh}§
     
    51065121long double _Complex atanh( long double _Complex );
    51075122\end{lstlisting}
    5108 \
    51095123
    51105124
    51115125\subsection{Error / Gamma}
    51125126
     5127\leavevmode
    51135128\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    51145129float erf( float );§\indexc{erf}§
     
    51375152long double tgamma( long double );
    51385153\end{lstlisting}
    5139 \
    51405154
    51415155
    51425156\subsection{Nearest Integer}
    51435157
     5158\leavevmode
    51445159\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    51455160float floor( float );§\indexc{floor}§
     
    51915206long long int llround( long double );
    51925207\end{lstlisting}
    5193 \
    51945208
    51955209
    51965210\subsection{Manipulation}
    51975211
     5212\leavevmode
    51985213\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
    51995214float copysign( float, float );§\indexc{copysign}§
     
    52325247long double scalbln( long double, long int );
    52335248\end{lstlisting}
    5234 \
    52355249
    52365250
  • src/CodeGen/CodeGenerator.cc

    r79841be r6943a987  
    8383        }
    8484
    85         CodeGenerator::CodeGenerator( std::ostream & os ) : indent( *this), cur_indent( 0 ), insideFunction( false ), output( os ), printLabels( *this ) {}
     85        CodeGenerator::CodeGenerator( std::ostream & os, bool mangle ) : indent( *this), cur_indent( 0 ), insideFunction( false ), output( os ), printLabels( *this ), mangle( mangle ) {}
    8686
    8787        CodeGenerator::CodeGenerator( std::ostream & os, std::string init, int indentation, bool infunp )
     
    9595        }
    9696
    97         string mangleName( DeclarationWithType * decl ) {
     97        string CodeGenerator::mangleName( DeclarationWithType * decl ) {
     98                if ( ! mangle ) return decl->get_name();
    9899                if ( decl->get_mangleName() != "" ) {
    99100                        // need to incorporate scope level in order to differentiate names for destructors
     
    311312                                                        Type * type = InitTweak::getPointerBase( (*arg)->get_results().front() );
    312313                                                        assert( type );
    313                                                         newExpr->get_results().push_back( type );
     314                                                        newExpr->get_results().push_back( type->clone() );
    314315                                                        *arg = newExpr;
    315316                                                } // if
  • src/CodeGen/CodeGenerator.h

    r79841be r6943a987  
    3030                static int tabsize;
    3131
    32                 CodeGenerator( std::ostream &os );
     32                CodeGenerator( std::ostream &os, bool mangle = true );
    3333                CodeGenerator( std::ostream &os, std::string, int indent = 0, bool infun = false );
    3434                CodeGenerator( std::ostream &os, char *, int indent = 0, bool infun = false );
     
    114114                std::ostream &output;
    115115                LabelPrinter printLabels;
     116                bool mangle = true;
    116117
    117118                void printDesignators( std::list< Expression * > & );
     
    119120                void handleAggregate( AggregateDecl *aggDecl );
    120121                void handleTypedef( NamedTypeDecl *namedType );
     122                std::string mangleName( DeclarationWithType * decl );
    121123        }; // CodeGenerator
    122124
  • src/CodeGen/GenType.cc

    r79841be r6943a987  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // GenType.cc -- 
     7// GenType.cc --
    88//
    99// Author           : Richard C. Bilson
     
    2828        class GenType : public Visitor {
    2929          public:
    30                 GenType( const std::string &typeString );
     30                GenType( const std::string &typeString, bool mangle = true );
    3131                std::string get_typeString() const { return typeString; }
    3232                void set_typeString( const std::string &newValue ) { typeString = newValue; }
    33  
     33
    3434                virtual void visit( FunctionType *funcType );
    3535                virtual void visit( VoidType *voidType );
     
    4242                virtual void visit( TypeInstType *typeInst );
    4343                virtual void visit( VarArgsType *varArgsType );
    44  
     44
    4545          private:
    4646                void handleQualifiers( Type *type );
    4747                void genArray( const Type::Qualifiers &qualifiers, Type *base, Expression *dimension, bool isVarLen, bool isStatic );
    48  
     48
    4949                std::string typeString;
     50                bool mangle = true;
    5051        };
    5152
    52         std::string genType( Type *type, const std::string &baseString ) {
    53                 GenType gt( baseString );
     53        std::string genType( Type *type, const std::string &baseString, bool mangle ) {
     54                GenType gt( baseString, mangle );
    5455                type->accept( gt );
    5556                return gt.get_typeString();
    5657        }
    5758
    58         GenType::GenType( const std::string &typeString ) : typeString( typeString ) {}
     59        GenType::GenType( const std::string &typeString, bool mangle ) : typeString( typeString ), mangle( mangle ) {}
    5960
    6061        void GenType::visit( VoidType *voidType ) {
     
    100101                } // if
    101102                if ( dimension != 0 ) {
    102                         CodeGenerator cg( os );
     103                        CodeGenerator cg( os, mangle );
    103104                        dimension->accept( cg );
    104105                } else if ( isVarLen ) {
     
    109110
    110111                typeString = os.str();
    111  
     112
    112113                base->accept( *this );
    113114        }
     
    142143                        } // if
    143144                } // if
    144  
     145
    145146                /************* parameters ***************/
    146147
     
    154155                        } // if
    155156                } else {
    156                         CodeGenerator cg( os );
     157                        CodeGenerator cg( os, mangle );
    157158                        os << "(" ;
    158159
     
    164165                        os << ")";
    165166                } // if
    166  
     167
    167168                typeString = os.str();
    168169
  • src/CodeGen/GenType.h

    r79841be r6943a987  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // GenType.h -- 
     7// GenType.h --
    88//
    99// Author           : Richard C. Bilson
     
    2121
    2222namespace CodeGen {
    23         std::string genType( Type *type, const std::string &baseString );
     23        std::string genType( Type *type, const std::string &baseString, bool mangle = true );
    2424} // namespace CodeGen
    2525
  • src/Common/CompilerError.h

    r79841be r6943a987  
    1010// Created On       : Mon May 18 07:44:20 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue May 19 07:20:37 2015
    13 // Update Count     : 2
     12// Last Modified On : Thu Aug 18 23:41:30 2016
     13// Update Count     : 3
    1414//
    1515
     
    1818
    1919#include <string>
    20 //#include "../config.h"
    2120
    2221class CompilerError : public std::exception {
  • src/Common/module.mk

    r79841be r6943a987  
    1111## Created On       : Mon Jun  1 17:49:17 2015
    1212## Last Modified By : Peter A. Buhr
    13 ## Last Modified On : Mon Jun  1 17:51:23 2015
    14 ## Update Count     : 1
     13## Last Modified On : Thu Aug 18 13:29:04 2016
     14## Update Count     : 2
    1515###############################################################################
    1616
    1717SRC += Common/SemanticError.cc \
    18        Common/UniqueName.cc
     18       Common/UniqueName.cc \
     19       Common/Assert.cc
  • src/Common/utility.h

    r79841be r6943a987  
    4949}
    5050
     51template< typename T, typename U >
     52static inline T * maybeMoveBuild( const U *orig ) {
     53        T* ret = maybeBuild<T>(orig);
     54        delete orig;
     55        return ret;
     56}
     57
    5158template< typename Input_iterator >
    5259void printEnums( Input_iterator begin, Input_iterator end, const char * const *name_array, std::ostream &os ) {
     
    137144
    138145template < typename T >
    139 std::string toString ( T value ) {
     146void toString_single ( std::ostream & os, const T & value ) {
     147        os << value;
     148}
     149
     150template < typename T, typename... Params >
     151void toString_single ( std::ostream & os, const T & value, const Params & ... params ) {
     152        os << value;
     153        toString_single( os, params ... );
     154}
     155
     156template < typename ... Params >
     157std::string toString ( const Params & ... params ) {
    140158        std::ostringstream os;
    141         os << value; // << std::ends;
     159        toString_single( os, params... );
    142160        return os.str();
    143161}
     
    211229}
    212230
     231template< typename T >
     232void warn_single( const T & arg ) {
     233        std::cerr << arg << std::endl;
     234}
     235
     236template< typename T, typename... Params >
     237void warn_single(const T & arg, const Params & ... params ) {
     238        std::cerr << arg;
     239        warn_single( params... );
     240}
     241
     242template< typename... Params >
     243void warn( const Params & ... params ) {
     244        std::cerr << "Warning: ";
     245        warn_single( params... );
     246}
     247
    213248#endif // _UTILITY_H
    214249
  • src/InitTweak/FixInit.cc

    r79841be r6943a987  
    3333#include "GenPoly/PolyMutator.h"
    3434#include "SynTree/AddStmtVisitor.h"
     35#include "CodeGen/GenType.h"  // for warnings
    3536
    3637bool ctordtorp = false;
     
    174175                        virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
    175176                };
     177
     178                class WarnStructMembers : public Visitor {
     179                  public:
     180                        typedef Visitor Parent;
     181                        /// warn if a user-defined constructor or destructor is missing calls for
     182                        /// a struct member or if a member is used before constructed
     183                        static void warnings( std::list< Declaration * > & translationUnit );
     184
     185                        virtual void visit( FunctionDecl * funcDecl );
     186
     187                        virtual void visit( MemberExpr * memberExpr );
     188                        virtual void visit( ApplicationExpr * appExpr );
     189
     190                  private:
     191                        void handleFirstParam( Expression * firstParam );
     192
     193                        FunctionDecl * function = 0;
     194                        std::set< DeclarationWithType * > unhandled;
     195                        ObjectDecl * thisParam = 0;
     196                };
    176197        } // namespace
    177198
     
    187208                // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
    188209                FixCopyCtors::fixCopyCtors( translationUnit );
     210
     211                WarnStructMembers::warnings( translationUnit );
    189212        }
    190213
     
    231254                }
    232255
     256                void WarnStructMembers::warnings( std::list< Declaration * > & translationUnit ) {
     257                        if ( true ) { // fix this condition to skip this pass if warnings aren't enabled
     258                                WarnStructMembers warner;
     259                                acceptAll( translationUnit, warner );
     260                        }
     261                }
     262
    233263                Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
    234264                        appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
     
    242272                                        FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
    243273                                        assert( ftype );
    244                                         if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
     274                                        if ( (isConstructor( funcDecl->get_name() ) || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
    245275                                                Type * t1 = ftype->get_parameters().front()->get_type();
    246276                                                Type * t2 = ftype->get_parameters().back()->get_type();
     
    253283                                                        return appExpr;
    254284                                                } // if
    255                                         } else if ( funcDecl->get_name() == "^?{}" ) {
     285                                        } else if ( isDestructor( funcDecl->get_name() ) ) {
    256286                                                // correctness: never copy construct arguments to a destructor
    257287                                                return appExpr;
     
    284314                        UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
    285315                        untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
    286                         if (cpArg) untyped->get_args().push_back( cpArg );
     316                        if (cpArg) untyped->get_args().push_back( cpArg->clone() );
    287317
    288318                        // resolve copy constructor
     
    670700                        } // switch
    671701                }
     702
     703                bool checkWarnings( FunctionDecl * funcDecl ) {
     704                        // only check for warnings if the current function is a user-defined
     705                        // constructor or destructor
     706                        if ( ! funcDecl ) return false;
     707                        if ( ! funcDecl->get_statements() ) return false;
     708                        return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
     709                }
     710
     711                void WarnStructMembers::visit( FunctionDecl * funcDecl ) {
     712                        WarnStructMembers old = *this;
     713                        *this = WarnStructMembers();
     714
     715                        function = funcDecl;
     716                        if ( checkWarnings( funcDecl ) ) {
     717                                FunctionType * type = funcDecl->get_functionType();
     718                                assert( ! type->get_parameters().empty() );
     719                                thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
     720                                PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
     721                                StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
     722                                if ( structType ) {
     723                                        StructDecl * structDecl = structType->get_baseStruct();
     724                                        for ( Declaration * member : structDecl->get_members() ) {
     725                                                if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
     726                                                        // record all of the struct type's members that need to be constructed or
     727                                                        // destructed by the end of the function
     728                                                        unhandled.insert( field );
     729                                                }
     730                                        }
     731                                }
     732                        }
     733                        Parent::visit( funcDecl );
     734
     735                        for ( DeclarationWithType * member : unhandled ) {
     736                                // emit a warning for each unhandled member
     737                                warn( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", member ", member->get_name(), " may not have been ", isConstructor( funcDecl->get_name() ) ? "constructed" : "destructed" );
     738                        }
     739
     740                        *this = old;
     741                }
     742
     743                void WarnStructMembers::visit( ApplicationExpr * appExpr ) {
     744                        if ( ! checkWarnings( function ) ) return;
     745
     746                        std::string fname = getFunctionName( appExpr );
     747                        if ( fname == function->get_name() ) {
     748                                // call to same kind of function
     749                                Expression * firstParam = appExpr->get_args().front();
     750
     751                                if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
     752                                        // if calling another constructor on thisParam, assume that function handles
     753                                        // all members - if it doesn't a warning will appear in that function.
     754                                        if ( varExpr->get_var() == thisParam ) {
     755                                                unhandled.clear();
     756                                        }
     757                                } else {
     758                                        // if first parameter is a member expression then
     759                                        // remove the member from unhandled set.
     760                                        handleFirstParam( firstParam );
     761                                }
     762                        } else if ( fname == "?=?" && isIntrinsicCallExpr( appExpr ) ) {
     763                                // forgive use of intrinsic assignment to construct, since instrinsic constructors
     764                                // codegen as assignment anyway.
     765                                assert( appExpr->get_args().size() == 2 );
     766                                handleFirstParam( appExpr->get_args().front() );
     767                        }
     768
     769                        Parent::visit( appExpr );
     770                }
     771
     772                void WarnStructMembers::handleFirstParam( Expression * firstParam ) {
     773                        using namespace std;
     774                        if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
     775                                if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
     776                                        if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
     777                                                if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
     778                                                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
     779                                                                if ( varExpr->get_var() == thisParam ) {
     780                                                                        unhandled.erase( memberExpr->get_member() );
     781                                                                }
     782                                                        }
     783                                                }
     784                                        }
     785                                }
     786                        }
     787                }
     788
     789                void WarnStructMembers::visit( MemberExpr * memberExpr ) {
     790                        if ( ! checkWarnings( function ) ) return;
     791                        if ( ! isConstructor( function->get_name() ) ) return;
     792
     793                        if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
     794                                if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
     795                                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
     796                                                if ( varExpr->get_var() == thisParam ) {
     797                                                        if ( unhandled.count( memberExpr->get_member() ) ) {
     798                                                                // emit a warning because a member was used before it was constructed
     799                                                                warn( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", member ", memberExpr->get_member()->get_name(), " used before being constructed" );
     800                                                        }
     801                                                }
     802                                        }
     803                                }
     804                        }
     805                        Parent::visit( memberExpr );
     806                }
    672807        } // namespace
    673808} // namespace InitTweak
  • src/InitTweak/InitTweak.cc

    r79841be r6943a987  
    291291        }
    292292
     293        namespace {
     294                template <typename Predicate>
     295                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
     296                        std::list< Expression * > callExprs;
     297                        collectCtorDtorCalls( stmt, callExprs );
     298                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
     299                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
     300                }
     301        }
     302
    293303        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
    294                 std::list< Expression * > callExprs;
    295                 collectCtorDtorCalls( stmt, callExprs );
    296                 // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
    297                 return std::all_of( callExprs.begin(), callExprs.end(), []( Expression * callExpr ){
     304                return allofCtorDtor( stmt, []( Expression * callExpr ){
    298305                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
    299306                                assert( ! appExpr->get_function()->get_results().empty() );
     
    303310                        }
    304311                        return false;
     312                });
     313        }
     314
     315        bool isIntrinsicCallStmt( Statement * stmt ) {
     316                return allofCtorDtor( stmt, []( Expression * callExpr ) {
     317                        return isIntrinsicCallExpr( callExpr );
    305318                });
    306319        }
     
    420433        }
    421434
     435        bool isConstructor( const std::string & str ) { return str == "?{}"; }
     436        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
     437        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
    422438}
  • src/InitTweak/InitTweak.h

    r79841be r6943a987  
    2626// helper functions for initialization
    2727namespace InitTweak {
     28        bool isConstructor( const std::string & );
     29        bool isDestructor( const std::string & );
     30        bool isCtorDtor( const std::string & );
     31
    2832        /// transform Initializer into an argument list that can be passed to a call expression
    2933        std::list< Expression * > makeInitList( Initializer * init );
     
    4145        /// Intended to be used for default ctor/dtor calls, but might have use elsewhere.
    4246        /// Currently has assertions that make it less than fully general.
    43         bool isIntrinsicSingleArgCallStmt( Statement * expr );
     47        bool isIntrinsicSingleArgCallStmt( Statement * stmt );
     48
     49        /// True if stmt is a call statement where the function called is intrinsic.
     50        bool isIntrinsicCallStmt( Statement * stmt );
    4451
    4552        /// get all Ctor/Dtor call expressions from a Statement
  • src/Makefile.am

    r79841be r6943a987  
    1111## Created On       : Sun May 31 08:51:46 2015
    1212## Last Modified By : Peter A. Buhr
    13 ## Last Modified On : Fri Jul  8 12:22:25 2016
    14 ## Update Count     : 60
     13## Last Modified On : Sat Aug 20 11:13:12 2016
     14## Update Count     : 71
    1515###############################################################################
    1616
     
    4242cfa_cpplib_PROGRAMS = driver/cfa-cpp
    4343driver_cfa_cpp_SOURCES = ${SRC}
    44 driver_cfa_cpp_LDADD = ${LEXLIB}        # yywrap
    45 # need files Common/utility.h
    46 driver_cfa_cpp_CXXFLAGS = -Wno-deprecated -Wall -DDEBUG_ALL
    47 
    48 AM_CXXFLAGS = -g -std=c++11
     44driver_cfa_cpp_LDADD = ${LEXLIB}                        # yywrap
     45driver_cfa_cpp_CXXFLAGS = -Wno-deprecated -Wall -DDEBUG_ALL -rdynamic -I${abs_top_srcdir}/src/include
    4946
    5047MAINTAINERCLEANFILES += ${libdir}/${notdir ${cfa_cpplib_PROGRAMS}}
  • src/Makefile.in

    r79841be r6943a987  
    105105        Common/driver_cfa_cpp-SemanticError.$(OBJEXT) \
    106106        Common/driver_cfa_cpp-UniqueName.$(OBJEXT) \
     107        Common/driver_cfa_cpp-Assert.$(OBJEXT) \
    107108        ControlStruct/driver_cfa_cpp-LabelGenerator.$(OBJEXT) \
    108109        ControlStruct/driver_cfa_cpp-LabelFixer.$(OBJEXT) \
     
    137138        Parser/driver_cfa_cpp-LinkageSpec.$(OBJEXT) \
    138139        Parser/driver_cfa_cpp-parseutility.$(OBJEXT) \
    139         Parser/driver_cfa_cpp-Parser.$(OBJEXT) \
    140140        ResolvExpr/driver_cfa_cpp-AlternativeFinder.$(OBJEXT) \
    141141        ResolvExpr/driver_cfa_cpp-Alternative.$(OBJEXT) \
     
    370370        CodeGen/CodeGenerator.cc CodeGen/GenType.cc \
    371371        CodeGen/FixNames.cc CodeGen/OperatorTable.cc \
    372         Common/SemanticError.cc Common/UniqueName.cc \
     372        Common/SemanticError.cc Common/UniqueName.cc Common/Assert.cc \
    373373        ControlStruct/LabelGenerator.cc ControlStruct/LabelFixer.cc \
    374374        ControlStruct/MLEMutator.cc ControlStruct/Mutate.cc \
     
    385385        Parser/ExpressionNode.cc Parser/StatementNode.cc \
    386386        Parser/InitializerNode.cc Parser/TypeData.cc \
    387         Parser/LinkageSpec.cc Parser/parseutility.cc Parser/Parser.cc \
     387        Parser/LinkageSpec.cc Parser/parseutility.cc \
    388388        ResolvExpr/AlternativeFinder.cc ResolvExpr/Alternative.cc \
    389389        ResolvExpr/Unify.cc ResolvExpr/PtrsAssignable.cc \
     
    426426cfa_cpplibdir = ${libdir}
    427427driver_cfa_cpp_SOURCES = ${SRC}
    428 driver_cfa_cpp_LDADD = ${LEXLIB}        # yywrap
    429 # need files Common/utility.h
    430 driver_cfa_cpp_CXXFLAGS = -Wno-deprecated -Wall -DDEBUG_ALL
    431 AM_CXXFLAGS = -g -std=c++11
     428driver_cfa_cpp_LDADD = ${LEXLIB}                        # yywrap
     429driver_cfa_cpp_CXXFLAGS = -Wno-deprecated -Wall -DDEBUG_ALL -rdynamic -I${abs_top_srcdir}/src/include
    432430all: $(BUILT_SOURCES)
    433431        $(MAKE) $(AM_MAKEFLAGS) all-am
     
    528526        Common/$(DEPDIR)/$(am__dirstamp)
    529527Common/driver_cfa_cpp-UniqueName.$(OBJEXT): Common/$(am__dirstamp) \
     528        Common/$(DEPDIR)/$(am__dirstamp)
     529Common/driver_cfa_cpp-Assert.$(OBJEXT): Common/$(am__dirstamp) \
    530530        Common/$(DEPDIR)/$(am__dirstamp)
    531531ControlStruct/$(am__dirstamp):
     
    632632        Parser/$(DEPDIR)/$(am__dirstamp)
    633633Parser/driver_cfa_cpp-parseutility.$(OBJEXT): Parser/$(am__dirstamp) \
    634         Parser/$(DEPDIR)/$(am__dirstamp)
    635 Parser/driver_cfa_cpp-Parser.$(OBJEXT): Parser/$(am__dirstamp) \
    636634        Parser/$(DEPDIR)/$(am__dirstamp)
    637635ResolvExpr/$(am__dirstamp):
     
    817815        -rm -f CodeGen/driver_cfa_cpp-Generate.$(OBJEXT)
    818816        -rm -f CodeGen/driver_cfa_cpp-OperatorTable.$(OBJEXT)
     817        -rm -f Common/driver_cfa_cpp-Assert.$(OBJEXT)
    819818        -rm -f Common/driver_cfa_cpp-SemanticError.$(OBJEXT)
    820819        -rm -f Common/driver_cfa_cpp-UniqueName.$(OBJEXT)
     
    845844        -rm -f Parser/driver_cfa_cpp-LinkageSpec.$(OBJEXT)
    846845        -rm -f Parser/driver_cfa_cpp-ParseNode.$(OBJEXT)
    847         -rm -f Parser/driver_cfa_cpp-Parser.$(OBJEXT)
    848846        -rm -f Parser/driver_cfa_cpp-StatementNode.$(OBJEXT)
    849847        -rm -f Parser/driver_cfa_cpp-TypeData.$(OBJEXT)
     
    927925@AMDEP_TRUE@@am__include@ @am__quote@CodeGen/$(DEPDIR)/driver_cfa_cpp-Generate.Po@am__quote@
    928926@AMDEP_TRUE@@am__include@ @am__quote@CodeGen/$(DEPDIR)/driver_cfa_cpp-OperatorTable.Po@am__quote@
     927@AMDEP_TRUE@@am__include@ @am__quote@Common/$(DEPDIR)/driver_cfa_cpp-Assert.Po@am__quote@
    929928@AMDEP_TRUE@@am__include@ @am__quote@Common/$(DEPDIR)/driver_cfa_cpp-SemanticError.Po@am__quote@
    930929@AMDEP_TRUE@@am__include@ @am__quote@Common/$(DEPDIR)/driver_cfa_cpp-UniqueName.Po@am__quote@
     
    955954@AMDEP_TRUE@@am__include@ @am__quote@Parser/$(DEPDIR)/driver_cfa_cpp-LinkageSpec.Po@am__quote@
    956955@AMDEP_TRUE@@am__include@ @am__quote@Parser/$(DEPDIR)/driver_cfa_cpp-ParseNode.Po@am__quote@
    957 @AMDEP_TRUE@@am__include@ @am__quote@Parser/$(DEPDIR)/driver_cfa_cpp-Parser.Po@am__quote@
    958956@AMDEP_TRUE@@am__include@ @am__quote@Parser/$(DEPDIR)/driver_cfa_cpp-StatementNode.Po@am__quote@
    959957@AMDEP_TRUE@@am__include@ @am__quote@Parser/$(DEPDIR)/driver_cfa_cpp-TypeData.Po@am__quote@
     
    11691167@am__fastdepCXX_FALSE@  $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o Common/driver_cfa_cpp-UniqueName.obj `if test -f 'Common/UniqueName.cc'; then $(CYGPATH_W) 'Common/UniqueName.cc'; else $(CYGPATH_W) '$(srcdir)/Common/UniqueName.cc'; fi`
    11701168
     1169Common/driver_cfa_cpp-Assert.o: Common/Assert.cc
     1170@am__fastdepCXX_TRUE@   $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -MT Common/driver_cfa_cpp-Assert.o -MD -MP -MF Common/$(DEPDIR)/driver_cfa_cpp-Assert.Tpo -c -o Common/driver_cfa_cpp-Assert.o `test -f 'Common/Assert.cc' || echo '$(srcdir)/'`Common/Assert.cc
     1171@am__fastdepCXX_TRUE@   $(AM_V_at)$(am__mv) Common/$(DEPDIR)/driver_cfa_cpp-Assert.Tpo Common/$(DEPDIR)/driver_cfa_cpp-Assert.Po
     1172@AMDEP_TRUE@@am__fastdepCXX_FALSE@      $(AM_V_CXX)source='Common/Assert.cc' object='Common/driver_cfa_cpp-Assert.o' libtool=no @AMDEPBACKSLASH@
     1173@AMDEP_TRUE@@am__fastdepCXX_FALSE@      DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
     1174@am__fastdepCXX_FALSE@  $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o Common/driver_cfa_cpp-Assert.o `test -f 'Common/Assert.cc' || echo '$(srcdir)/'`Common/Assert.cc
     1175
     1176Common/driver_cfa_cpp-Assert.obj: Common/Assert.cc
     1177@am__fastdepCXX_TRUE@   $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -MT Common/driver_cfa_cpp-Assert.obj -MD -MP -MF Common/$(DEPDIR)/driver_cfa_cpp-Assert.Tpo -c -o Common/driver_cfa_cpp-Assert.obj `if test -f 'Common/Assert.cc'; then $(CYGPATH_W) 'Common/Assert.cc'; else $(CYGPATH_W) '$(srcdir)/Common/Assert.cc'; fi`
     1178@am__fastdepCXX_TRUE@   $(AM_V_at)$(am__mv) Common/$(DEPDIR)/driver_cfa_cpp-Assert.Tpo Common/$(DEPDIR)/driver_cfa_cpp-Assert.Po
     1179@AMDEP_TRUE@@am__fastdepCXX_FALSE@      $(AM_V_CXX)source='Common/Assert.cc' object='Common/driver_cfa_cpp-Assert.obj' libtool=no @AMDEPBACKSLASH@
     1180@AMDEP_TRUE@@am__fastdepCXX_FALSE@      DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
     1181@am__fastdepCXX_FALSE@  $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o Common/driver_cfa_cpp-Assert.obj `if test -f 'Common/Assert.cc'; then $(CYGPATH_W) 'Common/Assert.cc'; else $(CYGPATH_W) '$(srcdir)/Common/Assert.cc'; fi`
     1182
    11711183ControlStruct/driver_cfa_cpp-LabelGenerator.o: ControlStruct/LabelGenerator.cc
    11721184@am__fastdepCXX_TRUE@   $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -MT ControlStruct/driver_cfa_cpp-LabelGenerator.o -MD -MP -MF ControlStruct/$(DEPDIR)/driver_cfa_cpp-LabelGenerator.Tpo -c -o ControlStruct/driver_cfa_cpp-LabelGenerator.o `test -f 'ControlStruct/LabelGenerator.cc' || echo '$(srcdir)/'`ControlStruct/LabelGenerator.cc
     
    16161628@AMDEP_TRUE@@am__fastdepCXX_FALSE@      DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    16171629@am__fastdepCXX_FALSE@  $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o Parser/driver_cfa_cpp-parseutility.obj `if test -f 'Parser/parseutility.cc'; then $(CYGPATH_W) 'Parser/parseutility.cc'; else $(CYGPATH_W) '$(srcdir)/Parser/parseutility.cc'; fi`
    1618 
    1619 Parser/driver_cfa_cpp-Parser.o: Parser/Parser.cc
    1620 @am__fastdepCXX_TRUE@   $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -MT Parser/driver_cfa_cpp-Parser.o -MD -MP -MF Parser/$(DEPDIR)/driver_cfa_cpp-Parser.Tpo -c -o Parser/driver_cfa_cpp-Parser.o `test -f 'Parser/Parser.cc' || echo '$(srcdir)/'`Parser/Parser.cc
    1621 @am__fastdepCXX_TRUE@   $(AM_V_at)$(am__mv) Parser/$(DEPDIR)/driver_cfa_cpp-Parser.Tpo Parser/$(DEPDIR)/driver_cfa_cpp-Parser.Po
    1622 @AMDEP_TRUE@@am__fastdepCXX_FALSE@      $(AM_V_CXX)source='Parser/Parser.cc' object='Parser/driver_cfa_cpp-Parser.o' libtool=no @AMDEPBACKSLASH@
    1623 @AMDEP_TRUE@@am__fastdepCXX_FALSE@      DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    1624 @am__fastdepCXX_FALSE@  $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o Parser/driver_cfa_cpp-Parser.o `test -f 'Parser/Parser.cc' || echo '$(srcdir)/'`Parser/Parser.cc
    1625 
    1626 Parser/driver_cfa_cpp-Parser.obj: Parser/Parser.cc
    1627 @am__fastdepCXX_TRUE@   $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -MT Parser/driver_cfa_cpp-Parser.obj -MD -MP -MF Parser/$(DEPDIR)/driver_cfa_cpp-Parser.Tpo -c -o Parser/driver_cfa_cpp-Parser.obj `if test -f 'Parser/Parser.cc'; then $(CYGPATH_W) 'Parser/Parser.cc'; else $(CYGPATH_W) '$(srcdir)/Parser/Parser.cc'; fi`
    1628 @am__fastdepCXX_TRUE@   $(AM_V_at)$(am__mv) Parser/$(DEPDIR)/driver_cfa_cpp-Parser.Tpo Parser/$(DEPDIR)/driver_cfa_cpp-Parser.Po
    1629 @AMDEP_TRUE@@am__fastdepCXX_FALSE@      $(AM_V_CXX)source='Parser/Parser.cc' object='Parser/driver_cfa_cpp-Parser.obj' libtool=no @AMDEPBACKSLASH@
    1630 @AMDEP_TRUE@@am__fastdepCXX_FALSE@      DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    1631 @am__fastdepCXX_FALSE@  $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o Parser/driver_cfa_cpp-Parser.obj `if test -f 'Parser/Parser.cc'; then $(CYGPATH_W) 'Parser/Parser.cc'; else $(CYGPATH_W) '$(srcdir)/Parser/Parser.cc'; fi`
    16321630
    16331631ResolvExpr/driver_cfa_cpp-AlternativeFinder.o: ResolvExpr/AlternativeFinder.cc
  • src/Parser/DeclarationNode.cc

    r79841be r6943a987  
    1010// Created On       : Sat May 16 12:34:05 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue Aug  9 08:39:20 2016
    13 // Update Count     : 169
     12// Last Modified On : Sun Aug 28 22:12:44 2016
     13// Update Count     : 278
    1414//
    1515
     
    2525#include "SynTree/Expression.h"
    2626
    27 #include "Parser.h"
    2827#include "TypedefTable.h"
    2928extern TypedefTable typedefTable;
     
    4241UniqueName DeclarationNode::anonymous( "__anonymous" );
    4342
    44 extern LinkageSpec::Type linkage;                                               // defined in parser.yy
     43extern LinkageSpec::Spec linkage;                                               // defined in parser.yy
    4544
    4645DeclarationNode *DeclarationNode::clone() const {
     
    4847        newnode->type = maybeClone( type );
    4948        newnode->name = name;
    50         newnode->storageClasses = storageClasses;
    51 //PAB   newnode->bitfieldWidth = maybeClone( bitfieldWidth );
    52         newnode->bitfieldWidth = bitfieldWidth;
     49        newnode->storageClass = storageClass;
     50        newnode->isInline = isInline;
     51        newnode->isNoreturn = isNoreturn;
     52        newnode->bitfieldWidth = maybeClone( bitfieldWidth );
    5353        newnode->hasEllipsis = hasEllipsis;
    54         newnode->initializer = initializer;
    55         newnode->next = maybeClone( next );
     54        newnode->initializer = maybeClone( initializer );
     55        newnode->set_next( maybeClone( get_next() ) );
    5656        newnode->linkage = linkage;
    5757        return newnode;
    5858} // DeclarationNode::clone
    5959
    60 DeclarationNode::DeclarationNode() : type( 0 ), bitfieldWidth( 0 ), initializer( 0 ), hasEllipsis( false ), linkage( ::linkage ) {
     60DeclarationNode::DeclarationNode()
     61        : type( 0 )
     62        , storageClass( NoStorageClass )
     63        , isInline( false )
     64        , isNoreturn( false )
     65        , bitfieldWidth( 0 )
     66        , initializer( 0 )
     67        , hasEllipsis( false )
     68        , linkage( ::linkage )
     69        , extension( false )
     70        , error() {
    6171}
    6272
     
    8393        } // if
    8494
    85         printEnums( storageClasses.begin(), storageClasses.end(), DeclarationNode::storageName, os );
     95        if ( storageClass != NoStorageClass ) os << DeclarationNode::storageName[storageClass] << ' ';
     96        if ( isInline ) os << DeclarationNode::storageName[Inline] << ' ';
     97        if ( isNoreturn ) os << DeclarationNode::storageName[Noreturn] << ' ';
    8698        if ( type ) {
    8799                type->print( os, indent );
     
    135147} // DeclarationNode::newFunction
    136148
    137 DeclarationNode *DeclarationNode::newQualifier( Qualifier q ) {
     149DeclarationNode * DeclarationNode::newQualifier( Qualifier q ) {
    138150        DeclarationNode *newnode = new DeclarationNode;
    139151        newnode->type = new TypeData();
    140         newnode->type->qualifiers.push_back( q );
     152        newnode->type->qualifiers[ q ] = 1;
    141153        return newnode;
    142154} // DeclarationNode::newQualifier
    143155
    144 DeclarationNode *DeclarationNode::newStorageClass( DeclarationNode::StorageClass sc ) {
    145         DeclarationNode *newnode = new DeclarationNode;
    146         newnode->storageClasses.push_back( sc );
     156DeclarationNode * DeclarationNode::newForall( DeclarationNode *forall ) {
     157        DeclarationNode *newnode = new DeclarationNode;
     158        newnode->type = new TypeData( TypeData::Unknown );
     159        newnode->type->forall = forall;
     160        return newnode;
     161} // DeclarationNode::newForall
     162
     163DeclarationNode * DeclarationNode::newStorageClass( DeclarationNode::StorageClass sc ) {
     164        DeclarationNode *newnode = new DeclarationNode;
     165        //switch (sc) {
     166        //      case Inline: newnode->isInline = true; break;
     167        //      case Noreturn: newnode->isNoreturn = true; break;
     168        //      default: newnode->storageClass = sc; break;
     169        //}
     170        newnode->storageClass = sc;
    147171        return newnode;
    148172} // DeclarationNode::newStorageClass
    149173
    150 DeclarationNode *DeclarationNode::newBasicType( BasicType bt ) {
     174DeclarationNode * DeclarationNode::newBasicType( BasicType bt ) {
    151175        DeclarationNode *newnode = new DeclarationNode;
    152176        newnode->type = new TypeData( TypeData::Basic );
     
    155179} // DeclarationNode::newBasicType
    156180
    157 DeclarationNode *DeclarationNode::newBuiltinType( BuiltinType bt ) {
     181DeclarationNode * DeclarationNode::newModifier( Modifier mod ) {
     182        DeclarationNode *newnode = new DeclarationNode;
     183        newnode->type = new TypeData( TypeData::Basic );
     184        newnode->type->basic->modifiers.push_back( mod );
     185        return newnode;
     186} // DeclarationNode::newModifier
     187
     188DeclarationNode * DeclarationNode::newBuiltinType( BuiltinType bt ) {
    158189        DeclarationNode *newnode = new DeclarationNode;
    159190        newnode->type = new TypeData( TypeData::Builtin );
     
    162193} // DeclarationNode::newBuiltinType
    163194
    164 DeclarationNode *DeclarationNode::newModifier( Modifier mod ) {
    165         DeclarationNode *newnode = new DeclarationNode;
    166         newnode->type = new TypeData( TypeData::Basic );
    167         newnode->type->basic->modifiers.push_back( mod );
    168         return newnode;
    169 } // DeclarationNode::newModifier
    170 
    171 DeclarationNode *DeclarationNode::newForall( DeclarationNode *forall ) {
    172         DeclarationNode *newnode = new DeclarationNode;
    173         newnode->type = new TypeData( TypeData::Unknown );
    174         newnode->type->forall = forall;
    175         return newnode;
    176 } // DeclarationNode::newForall
    177 
    178 DeclarationNode *DeclarationNode::newFromTypedef( std::string *name ) {
     195DeclarationNode * DeclarationNode::newFromTypedef( std::string *name ) {
    179196        DeclarationNode *newnode = new DeclarationNode;
    180197        newnode->type = new TypeData( TypeData::SymbolicInst );
     
    185202} // DeclarationNode::newFromTypedef
    186203
    187 DeclarationNode *DeclarationNode::newAggregate( Aggregate kind, const std::string *name, ExpressionNode *actuals, DeclarationNode *fields, bool body ) {
     204DeclarationNode * DeclarationNode::newAggregate( Aggregate kind, const std::string *name, ExpressionNode *actuals, DeclarationNode *fields, bool body ) {
    188205        DeclarationNode *newnode = new DeclarationNode;
    189206        newnode->type = new TypeData( TypeData::Aggregate );
     
    214231        DeclarationNode *newnode = new DeclarationNode;
    215232        newnode->name = assign_strptr( name );
    216         newnode->enumeratorValue = constant;
     233        newnode->enumeratorValue.reset( constant );
    217234        typedefTable.addToEnclosingScope( newnode->name, TypedefTable::ID );
    218235        return newnode;
     
    284301        newnode->type->array->dimension = size;
    285302        newnode->type->array->isStatic = isStatic;
    286         if ( newnode->type->array->dimension == 0 || dynamic_cast<ConstantExpr *>( newnode->type->array->dimension->build() ) ) {
     303        if ( newnode->type->array->dimension == 0 || newnode->type->array->dimension->isExpressionType<ConstantExpr *>() ) {
    287304                newnode->type->array->isVarLen = false;
    288305        } else {
     
    353370                        src = 0;
    354371                } else {
    355                         dst->qualifiers.splice( dst->qualifiers.end(), src->qualifiers );
    356                 } // if
    357         } // if
    358 }
     372                        dst->qualifiers |= src->qualifiers;
     373                } // if
     374        } // if
     375}
     376
     377void DeclarationNode::checkQualifiers( const TypeData *src, const TypeData *dst ) {
     378        TypeData::Qualifiers qsrc = src->qualifiers, qdst = dst->qualifiers;
     379
     380        if ( (qsrc & qdst).any() ) {                                            // common bits between qualifier masks ?
     381                error = "duplicate qualifier ";
     382                int j = 0;                                                                              // separator detector
     383                for ( int i = 0; i < DeclarationNode::NoOfQualifier; i += 1 ) {
     384                        if ( qsrc[i] & qdst[i] ) {                                      // find specific qualifiers in common
     385                                if ( j > 0 ) error += ", ";
     386                                error += DeclarationNode::qualifierName[i];
     387                                j += 1;
     388                        } // if
     389                } // for
     390                error += " in declaration of ";
     391        } // if
     392} // DeclarationNode::checkQualifiers
    359393
    360394DeclarationNode *DeclarationNode::addQualifiers( DeclarationNode *q ) {
    361395        if ( q ) {
    362                 storageClasses.splice( storageClasses.end(), q->storageClasses );
     396                copyStorageClasses(q);
    363397                if ( q->type ) {
    364398                        if ( ! type ) {
    365399                                type = new TypeData;
     400                        } else {
     401                                checkQualifiers( q->type, type );
    366402                        } // if
    367403                        addQualifiersToType( q->type, type );
     
    387423
    388424DeclarationNode *DeclarationNode::copyStorageClasses( DeclarationNode *q ) {
    389         storageClasses = q->storageClasses;
     425        isInline = isInline || q->isInline;
     426        isNoreturn = isNoreturn || q->isNoreturn;
     427        if ( storageClass == NoStorageClass ) {
     428                storageClass = q->storageClass;
     429        } else if ( q->storageClass != NoStorageClass ) {
     430                q->error = "invalid combination of storage classes in declaration of ";
     431        } // if
     432        if ( error.empty() ) error = q->error;
    390433        return this;
    391434}
     
    406449                        switch ( dst->kind ) {
    407450                          case TypeData::Unknown:
    408                                 src->qualifiers.splice( src->qualifiers.end(), dst->qualifiers );
     451                                src->qualifiers |= dst->qualifiers;
    409452                                dst = src;
    410453                                src = 0;
    411454                                break;
    412455                          case TypeData::Basic:
    413                                 dst->qualifiers.splice( dst->qualifiers.end(), src->qualifiers );
     456                                dst->qualifiers |= src->qualifiers;
    414457                                if ( src->kind != TypeData::Unknown ) {
    415458                                        assert( src->kind == TypeData::Basic );
     
    427470                                                dst->base->aggInst->params = maybeClone( src->aggregate->actuals );
    428471                                        } // if
    429                                         dst->base->qualifiers.splice( dst->base->qualifiers.end(), src->qualifiers );
     472                                        dst->base->qualifiers |= src->qualifiers;
    430473                                        src = 0;
    431474                                        break;
     
    447490DeclarationNode *DeclarationNode::addType( DeclarationNode *o ) {
    448491        if ( o ) {
    449                 storageClasses.splice( storageClasses.end(), o->storageClasses );
     492                copyStorageClasses( o );
    450493                if ( o->type ) {
    451494                        if ( ! type ) {
     
    456499                                                type->aggInst->params = maybeClone( o->type->aggregate->actuals );
    457500                                        } // if
    458                                         type->qualifiers.splice( type->qualifiers.end(), o->type->qualifiers );
     501                                        type->qualifiers |= o->type->qualifiers;
    459502                                } else {
    460503                                        type = o->type;
     
    470513
    471514                // there may be typedefs chained onto the type
    472                 if ( o->get_link() ) {
    473                         set_link( o->get_link()->clone() );
     515                if ( o->get_next() ) {
     516                        set_last( o->get_next()->clone() );
    474517                } // if
    475518        } // if
     
    591634                                        p->type->base->aggInst->params = maybeClone( type->aggregate->actuals );
    592635                                } // if
    593                                 p->type->base->qualifiers.splice( p->type->base->qualifiers.end(), type->qualifiers );
     636                                p->type->base->qualifiers |= type->qualifiers;
    594637                                break;
    595638
     
    628671                                        lastArray->base->aggInst->params = maybeClone( type->aggregate->actuals );
    629672                                } // if
    630                                 lastArray->base->qualifiers.splice( lastArray->base->qualifiers.end(), type->qualifiers );
     673                                lastArray->base->qualifiers |= type->qualifiers;
    631674                                break;
    632675                          default:
     
    694737        } // if
    695738        newnode->type->forall = maybeClone( type->forall );
    696         newnode->storageClasses = storageClasses;
     739        newnode->copyStorageClasses( this );
    697740        newnode->name = assign_strptr( newName );
    698741        return newnode;
     
    701744DeclarationNode *DeclarationNode::cloneBaseType( DeclarationNode *o ) {
    702745        if ( o ) {
    703                 o->storageClasses.insert( o->storageClasses.end(), storageClasses.begin(), storageClasses.end() );
     746                o->copyStorageClasses( this );
    704747                if ( type ) {
    705748                        TypeData *srcType = type;
     
    734777        DeclarationNode *newnode = new DeclarationNode;
    735778        newnode->type = maybeClone( type );
    736         newnode->storageClasses = storageClasses;
     779        newnode->copyStorageClasses( this );
    737780        newnode->name = assign_strptr( newName );
    738781        return newnode;
     
    741784DeclarationNode *DeclarationNode::cloneType( DeclarationNode *o ) {
    742785        if ( o ) {
    743                 o->storageClasses.insert( o->storageClasses.end(), storageClasses.begin(), storageClasses.end() );
     786                o->copyStorageClasses( this );
    744787                if ( type ) {
    745788                        TypeData *newType = type->clone();
     
    752795                } // if
    753796        } // if
     797        delete o;
    754798        return o;
    755 }
    756 
    757 DeclarationNode *DeclarationNode::appendList( DeclarationNode *node ) {
    758         if ( node != 0 ) {
    759                 set_link( node );
    760         } // if
    761         return this;
    762799}
    763800
    764801DeclarationNode *DeclarationNode::extractAggregate() const {
    765802        if ( type ) {
    766                 TypeData *ret = type->extractAggregate();
     803                TypeData *ret = typeextractAggregate( type );
    767804                if ( ret ) {
    768805                        DeclarationNode *newnode = new DeclarationNode;
     
    776813void buildList( const DeclarationNode *firstNode, std::list< Declaration * > &outputList ) {
    777814        SemanticError errors;
    778         std::back_insert_iterator< std::list< Declaration *> > out( outputList );
     815        std::back_insert_iterator< std::list< Declaration * > > out( outputList );
    779816        const DeclarationNode *cur = firstNode;
    780817        while ( cur ) {
     
    786823                                        *out++ = decl;
    787824                                } // if
     825                                delete extr;
    788826                        } // if
    789827                        Declaration *decl = cur->build();
     
    794832                        errors.append( e );
    795833                } // try
    796                 cur = dynamic_cast<DeclarationNode *>( cur->get_link() );
     834                cur = dynamic_cast< DeclarationNode * >( cur->get_next() );
    797835        } // while
    798836        if ( ! errors.isEmpty() ) {
     
    801839}
    802840
    803 void buildList( const DeclarationNode *firstNode, std::list< DeclarationWithType *> &outputList ) {
     841void buildList( const DeclarationNode *firstNode, std::list< DeclarationWithType * > &outputList ) {
    804842        SemanticError errors;
    805         std::back_insert_iterator< std::list< DeclarationWithType *> > out( outputList );
     843        std::back_insert_iterator< std::list< DeclarationWithType * > > out( outputList );
    806844        const DeclarationNode *cur = firstNode;
    807845        while ( cur ) {
     
    817855                        Declaration *decl = cur->build();
    818856                        if ( decl ) {
    819                                 if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType *>( decl ) ) {
     857                                if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
    820858                                        *out++ = dwt;
    821                                 } else if ( StructDecl *agg = dynamic_cast< StructDecl *>( decl ) ) {
     859                                } else if ( StructDecl *agg = dynamic_cast< StructDecl * >( decl ) ) {
    822860                                        StructInstType *inst = new StructInstType( Type::Qualifiers(), agg->get_name() );
    823861                                        *out++ = new ObjectDecl( "", DeclarationNode::NoStorageClass, linkage, 0, inst, 0 );
    824862                                        delete agg;
    825                                 } else if ( UnionDecl *agg = dynamic_cast< UnionDecl *>( decl ) ) {
     863                                } else if ( UnionDecl *agg = dynamic_cast< UnionDecl * >( decl ) ) {
    826864                                        UnionInstType *inst = new UnionInstType( Type::Qualifiers(), agg->get_name() );
    827865                                        *out++ = new ObjectDecl( "", DeclarationNode::NoStorageClass, linkage, 0, inst, 0 );
     
    831869                        errors.append( e );
    832870                } // try
    833                 cur = dynamic_cast< DeclarationNode *>( cur->get_link() );
     871                cur = dynamic_cast< DeclarationNode * >( cur->get_next() );
    834872        } // while
    835873        if ( ! errors.isEmpty() ) {
     
    838876}
    839877
    840 void buildTypeList( const DeclarationNode *firstNode, std::list< Type *> &outputList ) {
     878void buildTypeList( const DeclarationNode *firstNode, std::list< Type * > &outputList ) {
    841879        SemanticError errors;
    842         std::back_insert_iterator< std::list< Type *> > out( outputList );
     880        std::back_insert_iterator< std::list< Type * > > out( outputList );
    843881        const DeclarationNode *cur = firstNode;
    844882        while ( cur ) {
     
    848886                        errors.append( e );
    849887                } // try
    850                 cur = dynamic_cast< DeclarationNode *>( cur->get_link() );
     888                cur = dynamic_cast< DeclarationNode * >( cur->get_next() );
    851889        } // while
    852890        if ( ! errors.isEmpty() ) {
     
    856894
    857895Declaration *DeclarationNode::build() const {
     896        if ( ! error.empty() ) throw SemanticError( error, this );
    858897        if ( type ) {
    859                 return type->buildDecl( name, buildStorageClass(), maybeBuild< Expression >( bitfieldWidth ), buildFuncSpecifier( Inline ), buildFuncSpecifier( Noreturn ), linkage, maybeBuild< Initializer >(initializer) )->set_extension( extension );
    860         } // if
    861         if ( ! buildFuncSpecifier( Inline ) && ! buildFuncSpecifier( Noreturn ) ) {
    862                 return (new ObjectDecl( name, buildStorageClass(), linkage, maybeBuild< Expression >( bitfieldWidth ), 0, maybeBuild< Initializer >( initializer ) ))->set_extension( extension );
     898                return buildDecl( type, name, storageClass, maybeBuild< Expression >( bitfieldWidth ), isInline, isNoreturn, linkage, maybeBuild< Initializer >(initializer) )->set_extension( extension );
     899        } // if
     900        if ( ! isInline && ! isNoreturn ) {
     901                return (new ObjectDecl( name, storageClass, linkage, maybeBuild< Expression >( bitfieldWidth ), 0, maybeBuild< Initializer >( initializer ) ))->set_extension( extension );
    863902        } // if
    864903        throw SemanticError( "invalid function specifier in declaration of ", this );
     
    870909        switch ( type->kind ) {
    871910          case TypeData::Enum:
    872                 return new EnumInstType( type->buildQualifiers(), type->enumeration->name );
     911                return new EnumInstType( buildQualifiers( type ), type->enumeration->name );
    873912          case TypeData::Aggregate: {
    874913                  ReferenceToType *ret;
    875914                  switch ( type->aggregate->kind ) {
    876915                        case DeclarationNode::Struct:
    877                           ret = new StructInstType( type->buildQualifiers(), type->aggregate->name );
     916                          ret = new StructInstType( buildQualifiers( type ), type->aggregate->name );
    878917                          break;
    879918                        case DeclarationNode::Union:
    880                           ret = new UnionInstType( type->buildQualifiers(), type->aggregate->name );
     919                          ret = new UnionInstType( buildQualifiers( type ), type->aggregate->name );
    881920                          break;
    882921                        case DeclarationNode::Trait:
    883                           ret = new TraitInstType( type->buildQualifiers(), type->aggregate->name );
     922                          ret = new TraitInstType( buildQualifiers( type ), type->aggregate->name );
    884923                          break;
    885924                        default:
     
    890929          }
    891930          case TypeData::Symbolic: {
    892                   TypeInstType *ret = new TypeInstType( type->buildQualifiers(), type->symbolic->name, false );
     931                  TypeInstType *ret = new TypeInstType( buildQualifiers( type ), type->symbolic->name, false );
    893932                  buildList( type->symbolic->actuals, ret->get_parameters() );
    894933                  return ret;
    895934          }
    896935          default:
    897                 return type->build();
     936                return typebuild( type );
    898937        } // switch
    899938}
    900939
    901 DeclarationNode::StorageClass DeclarationNode::buildStorageClass() const {
    902         DeclarationNode::StorageClass ret = DeclarationNode::NoStorageClass;
    903         for ( std::list< DeclarationNode::StorageClass >::const_iterator i = storageClasses.begin(); i != storageClasses.end(); ++i ) {
    904           if ( *i == DeclarationNode::Inline || *i == DeclarationNode::Noreturn ) continue; // ignore function specifiers
    905           if ( ret != DeclarationNode::NoStorageClass ) {       // already have a valid storage class ?
    906                         throw SemanticError( "invalid combination of storage classes in declaration of ", this );
    907                 } // if
    908                 ret = *i;
    909         } // for
    910         return ret;
    911 }
    912 
    913 bool DeclarationNode::buildFuncSpecifier( DeclarationNode::StorageClass key ) const {
    914         std::list< DeclarationNode::StorageClass >::const_iterator first = std::find( storageClasses.begin(), storageClasses.end(), key );
    915   if ( first == storageClasses.end() ) return false;    // not found
    916         first = std::find( ++first, storageClasses.end(), key ); // found
    917   if ( first == storageClasses.end() ) return true;             // not found again
    918         throw SemanticError( "duplicate function specifier in declaration of ", this );
    919 }
     940// DeclarationNode::StorageClass DeclarationNode::buildStorageClass() const {
     941//      DeclarationNode::StorageClass ret = DeclarationNode::NoStorageClass;
     942//      for ( std::list< DeclarationNode::StorageClass >::const_iterator i = storageClasses.begin(); i != storageClasses.end(); ++i ) {
     943//        if ( *i == DeclarationNode::Inline || *i == DeclarationNode::Noreturn ) continue; // ignore function specifiers
     944//        if ( ret != DeclarationNode::NoStorageClass ) {       // already have a valid storage class ?
     945//                      throw SemanticError( "invalid combination of storage classes in declaration of ", this );
     946//              } // if
     947//              ret = *i;
     948//      } // for
     949//      return ret;
     950// }
     951
     952// bool DeclarationNode::buildFuncSpecifier( DeclarationNode::StorageClass key ) const {
     953//      std::list< DeclarationNode::StorageClass >::const_iterator first = std::find( storageClasses.begin(), storageClasses.end(), key );
     954//   if ( first == storageClasses.end() ) return false; // not found
     955//      first = std::find( ++first, storageClasses.end(), key ); // found
     956//   if ( first == storageClasses.end() ) return true;          // not found again
     957//      throw SemanticError( "duplicate function specifier in declaration of ", this );
     958// }
    920959
    921960// Local Variables: //
  • src/Parser/ExpressionNode.cc

    r79841be r6943a987  
    1010// Created On       : Sat May 16 13:17:07 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Wed Aug 10 11:07:38 2016
    13 // Update Count     : 486
     12// Last Modified On : Thu Aug 25 21:39:40 2016
     13// Update Count     : 503
    1414//
    1515
     
    3232using namespace std;
    3333
    34 ExpressionNode::ExpressionNode( const ExpressionNode &other ) : ParseNode( other.name ), extension( other.extension ) {}
     34ExpressionNode::ExpressionNode( const ExpressionNode &other ) : ParseNode( other.get_name() ), extension( other.extension ) {}
    3535
    3636//##############################################################################
     
    5757static inline bool checkX( char c ) { return c == 'x' || c == 'X'; }
    5858
    59 Expression *build_constantInteger( std::string & str ) {
     59Expression *build_constantInteger( const std::string & str ) {
    6060        static const BasicType::Kind kind[2][3] = {
    6161                { BasicType::SignedInt, BasicType::LongSignedInt, BasicType::LongLongSignedInt },
     
    120120        } // if
    121121
    122         return new ConstantExpr( Constant( new BasicType( emptyQualifiers, kind[Unsigned][size] ), str ) );
     122        Expression * ret = new ConstantExpr( Constant( new BasicType( emptyQualifiers, kind[Unsigned][size] ), str ) );
     123        delete &str;                                                                            // created by lex
     124        return ret;
    123125} // build_constantInteger
    124126
    125 Expression *build_constantFloat( std::string & str ) {
     127Expression *build_constantFloat( const std::string & str ) {
    126128        static const BasicType::Kind kind[2][3] = {
    127129                { BasicType::Float, BasicType::Double, BasicType::LongDouble },
     
    150152        } // if
    151153
    152         return new ConstantExpr( Constant( new BasicType( emptyQualifiers, kind[complx][size] ), str ) );
     154        Expression * ret = new ConstantExpr( Constant( new BasicType( emptyQualifiers, kind[complx][size] ), str ) );
     155        delete &str;                                                                            // created by lex
     156        return ret;
    153157} // build_constantFloat
    154158
    155 Expression *build_constantChar( std::string & str ) {
    156         return new ConstantExpr( Constant( new BasicType( emptyQualifiers, BasicType::Char ), str ) );
     159Expression *build_constantChar( const std::string & str ) {
     160        Expression * ret = new ConstantExpr( Constant( new BasicType( emptyQualifiers, BasicType::Char ), str ) );
     161        delete &str;                                                                            // created by lex
     162        return ret;
    157163} // build_constantChar
    158164
    159 ConstantExpr *build_constantStr( std::string & str ) {
     165ConstantExpr *build_constantStr( const std::string & str ) {
    160166        // string should probably be a primitive type
    161167        ArrayType *at = new ArrayType( emptyQualifiers, new BasicType( emptyQualifiers, BasicType::Char ),
     
    163169                                                                                        toString( str.size()+1-2 ) ) ),  // +1 for '\0' and -2 for '"'
    164170                                                                   false, false );
    165         return new ConstantExpr( Constant( at, str ) );
     171        ConstantExpr * ret = new ConstantExpr( Constant( at, str ) );
     172        delete &str;                                                                            // created by lex
     173        return ret;
    166174} // build_constantStr
    167175
    168 //##############################################################################
    169 
    170176NameExpr * build_varref( const string *name, bool labelp ) {
    171         return new NameExpr( *name, nullptr );
    172 }
    173 
    174 //##############################################################################
     177        NameExpr *expr = new NameExpr( *name, nullptr );
     178        delete name;
     179        return expr;
     180}
    175181
    176182static const char *OperName[] = {
     
    178184        "SizeOf", "AlignOf", "OffsetOf", "?+?", "?-?", "?*?", "?/?", "?%?", "||", "&&",
    179185        "?|?", "?&?", "?^?", "Cast", "?<<?", "?>>?", "?<?", "?>?", "?<=?", "?>=?", "?==?", "?!=?",
    180         "?=?", "?*=?", "?/=?", "?%=?", "?+=?", "?-=?", "?<<=?", "?>>=?", "?&=?", "?^=?", "?|=?",
     186        "?=?", "?@=?", "?*=?", "?/=?", "?%=?", "?+=?", "?-=?", "?<<=?", "?>>=?", "?&=?", "?^=?", "?|=?",
    181187        "?[?]", "...",
    182188        // monadic
     
    184190};
    185191
    186 //##############################################################################
    187 
    188192Expression *build_cast( DeclarationNode *decl_node, ExpressionNode *expr_node ) {
    189         Type *targetType = decl_node->buildType();
     193        Type *targetType = maybeMoveBuildType( decl_node );
    190194        if ( dynamic_cast< VoidType * >( targetType ) ) {
    191195                delete targetType;
    192                 return new CastExpr( maybeBuild<Expression>(expr_node) );
     196                return new CastExpr( maybeMoveBuild< Expression >(expr_node) );
    193197        } else {
    194                 return new CastExpr( maybeBuild<Expression>(expr_node), targetType );
     198                return new CastExpr( maybeMoveBuild< Expression >(expr_node), targetType );
    195199        } // if
    196200}
    197201
    198202Expression *build_fieldSel( ExpressionNode *expr_node, NameExpr *member ) {
    199         UntypedMemberExpr *ret = new UntypedMemberExpr( member->get_name(), maybeBuild<Expression>(expr_node) );
     203        UntypedMemberExpr *ret = new UntypedMemberExpr( member->get_name(), maybeMoveBuild< Expression >(expr_node) );
    200204        delete member;
    201205        return ret;
     
    204208Expression *build_pfieldSel( ExpressionNode *expr_node, NameExpr *member ) {
    205209        UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
    206         deref->get_args().push_back( maybeBuild<Expression>(expr_node) );
     210        deref->get_args().push_back( maybeMoveBuild< Expression >(expr_node) );
    207211        UntypedMemberExpr *ret = new UntypedMemberExpr( member->get_name(), deref );
    208212        delete member;
     
    211215
    212216Expression *build_addressOf( ExpressionNode *expr_node ) {
    213                 return new AddressExpr( maybeBuild<Expression>(expr_node) );
     217                return new AddressExpr( maybeMoveBuild< Expression >(expr_node) );
    214218}
    215219Expression *build_sizeOfexpr( ExpressionNode *expr_node ) {
    216         return new SizeofExpr( maybeBuild<Expression>(expr_node) );
     220        return new SizeofExpr( maybeMoveBuild< Expression >(expr_node) );
    217221}
    218222Expression *build_sizeOftype( DeclarationNode *decl_node ) {
    219         return new SizeofExpr( decl_node->buildType() );
     223        return new SizeofExpr( maybeMoveBuildType( decl_node ) );
    220224}
    221225Expression *build_alignOfexpr( ExpressionNode *expr_node ) {
    222         return new AlignofExpr( maybeBuild<Expression>(expr_node) );
     226        return new AlignofExpr( maybeMoveBuild< Expression >(expr_node) );
    223227}
    224228Expression *build_alignOftype( DeclarationNode *decl_node ) {
    225         return new AlignofExpr( decl_node->buildType() );
     229        return new AlignofExpr( maybeMoveBuildType( decl_node) );
    226230}
    227231Expression *build_offsetOf( DeclarationNode *decl_node, NameExpr *member ) {
    228         return new UntypedOffsetofExpr( decl_node->buildType(), member->get_name() );
     232        Expression* ret = new UntypedOffsetofExpr( maybeMoveBuildType( decl_node ), member->get_name() );
     233        delete member;
     234        return ret;
    229235}
    230236
    231237Expression *build_and_or( ExpressionNode *expr_node1, ExpressionNode *expr_node2, bool kind ) {
    232         return new LogicalExpr( notZeroExpr( maybeBuild<Expression>(expr_node1) ), notZeroExpr( maybeBuild<Expression>(expr_node2) ), kind );
     238        return new LogicalExpr( notZeroExpr( maybeMoveBuild< Expression >(expr_node1) ), notZeroExpr( maybeMoveBuild< Expression >(expr_node2) ), kind );
    233239}
    234240
    235241Expression *build_unary_val( OperKinds op, ExpressionNode *expr_node ) {
    236         std::list<Expression *> args;
    237         args.push_back( maybeBuild<Expression>(expr_node) );
     242        std::list< Expression * > args;
     243        args.push_back( maybeMoveBuild< Expression >(expr_node) );
    238244        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
    239245}
    240246Expression *build_unary_ptr( OperKinds op, ExpressionNode *expr_node ) {
    241         std::list<Expression *> args;
    242         args.push_back( new AddressExpr( maybeBuild<Expression>(expr_node) ) );
     247        std::list< Expression * > args;
     248        args.push_back( new AddressExpr( maybeMoveBuild< Expression >(expr_node) ) );
    243249        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
    244250}
    245251Expression *build_binary_val( OperKinds op, ExpressionNode *expr_node1, ExpressionNode *expr_node2 ) {
    246         std::list<Expression *> args;
    247         args.push_back( maybeBuild<Expression>(expr_node1) );
    248         args.push_back( maybeBuild<Expression>(expr_node2) );
     252        std::list< Expression * > args;
     253        args.push_back( maybeMoveBuild< Expression >(expr_node1) );
     254        args.push_back( maybeMoveBuild< Expression >(expr_node2) );
    249255        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
    250256}
    251257Expression *build_binary_ptr( OperKinds op, ExpressionNode *expr_node1, ExpressionNode *expr_node2 ) {
    252         std::list<Expression *> args;
    253         args.push_back( new AddressExpr( maybeBuild<Expression>(expr_node1) ) );
    254         args.push_back( maybeBuild<Expression>(expr_node2) );
     258        std::list< Expression * > args;
     259        args.push_back( new AddressExpr( maybeMoveBuild< Expression >(expr_node1) ) );
     260        args.push_back( maybeMoveBuild< Expression >(expr_node2) );
    255261        return new UntypedExpr( new NameExpr( OperName[ (int)op ] ), args );
    256262}
    257263
    258264Expression *build_cond( ExpressionNode *expr_node1, ExpressionNode *expr_node2, ExpressionNode *expr_node3 ) {
    259         return new ConditionalExpr( notZeroExpr( maybeBuild<Expression>(expr_node1) ), maybeBuild<Expression>(expr_node2), maybeBuild<Expression>(expr_node3) );
     265        return new ConditionalExpr( notZeroExpr( maybeMoveBuild< Expression >(expr_node1) ), maybeMoveBuild< Expression >(expr_node2), maybeMoveBuild< Expression >(expr_node3) );
    260266}
    261267
    262268Expression *build_comma( ExpressionNode *expr_node1, ExpressionNode *expr_node2 ) {
    263         return new CommaExpr( maybeBuild<Expression>(expr_node1), maybeBuild<Expression>(expr_node2) );
     269        return new CommaExpr( maybeMoveBuild< Expression >(expr_node1), maybeMoveBuild< Expression >(expr_node2) );
    264270}
    265271
    266272Expression *build_attrexpr( NameExpr *var, ExpressionNode * expr_node ) {
    267         return new AttrExpr( var, maybeBuild<Expression>(expr_node) );
     273        return new AttrExpr( var, maybeMoveBuild< Expression >(expr_node) );
    268274}
    269275Expression *build_attrtype( NameExpr *var, DeclarationNode * decl_node ) {
    270         return new AttrExpr( var, decl_node->buildType() );
     276        return new AttrExpr( var, maybeMoveBuildType( decl_node ) );
    271277}
    272278
    273279Expression *build_tuple( ExpressionNode * expr_node ) {
    274280        TupleExpr *ret = new TupleExpr();
    275         buildList( expr_node, ret->get_exprs() );
     281        buildMoveList( expr_node, ret->get_exprs() );
    276282        return ret;
    277283}
    278284
    279285Expression *build_func( ExpressionNode * function, ExpressionNode * expr_node ) {
    280         std::list<Expression *> args;
    281 
    282         buildList( expr_node, args );
    283         return new UntypedExpr( maybeBuild<Expression>(function), args, nullptr );
     286        std::list< Expression * > args;
     287        buildMoveList( expr_node, args );
     288        return new UntypedExpr( maybeMoveBuild< Expression >(function), args, nullptr );
    284289}
    285290
    286291Expression *build_range( ExpressionNode * low, ExpressionNode *high ) {
    287         Expression *low_cexpr = maybeBuild<Expression>( low );
    288         Expression *high_cexpr = maybeBuild<Expression>( high );
    289         return new RangeExpr( low_cexpr, high_cexpr );
    290 }
    291 
    292 //##############################################################################
    293 
    294 Expression *build_asm( ExpressionNode *inout, ConstantExpr *constraint, ExpressionNode *operand ) {
    295         return new AsmExpr( maybeBuild< Expression >( inout ), constraint, maybeBuild<Expression>(operand) );
    296 }
    297 
    298 //##############################################################################
    299 
    300 void LabelNode::print( std::ostream &os, int indent ) const {}
    301 
    302 void LabelNode::printOneLine( std::ostream &os, int indent ) const {}
    303 
    304 //##############################################################################
     292        return new RangeExpr( maybeMoveBuild< Expression >( low ), maybeMoveBuild< Expression >( high ) );
     293}
     294
     295Expression *build_asmexpr( ExpressionNode *inout, ConstantExpr *constraint, ExpressionNode *operand ) {
     296        return new AsmExpr( maybeMoveBuild< Expression >( inout ), constraint, maybeMoveBuild< Expression >(operand) );
     297}
    305298
    306299Expression *build_valexpr( StatementNode *s ) {
    307         return new UntypedValofExpr( maybeBuild<Statement>(s), nullptr );
    308 }
    309 
    310 //##############################################################################
    311  
    312 // ForCtlExprNode::ForCtlExprNode( ParseNode *init_, ExpressionNode *cond, ExpressionNode *incr ) throw ( SemanticError ) : condition( cond ), change( incr ) {
    313 //      if ( init_ == 0 )
    314 //              init = 0;
    315 //      else {
    316 //              DeclarationNode *decl;
    317 //              ExpressionNode *exp;
    318 
    319 //              if (( decl = dynamic_cast<DeclarationNode *>(init_) ) != 0)
    320 //                      init = new StatementNode( decl );
    321 //              else if (( exp = dynamic_cast<ExpressionNode *>( init_)) != 0)
    322 //                      init = new StatementNode( StatementNode::Exp, exp );
    323 //              else
    324 //                      throw SemanticError("Error in for control expression");
    325 //      }
    326 // }
    327 
    328 // ForCtlExprNode::ForCtlExprNode( const ForCtlExprNode &other )
    329 //      : ExpressionNode( other ), init( maybeClone( other.init ) ), condition( maybeClone( other.condition ) ), change( maybeClone( other.change ) ) {
    330 // }
    331 
    332 // ForCtlExprNode::~ForCtlExprNode() {
    333 //      delete init;
    334 //      delete condition;
    335 //      delete change;
    336 // }
    337 
    338 // Expression *ForCtlExprNode::build() const {
    339 //      // this shouldn't be used!
    340 //      assert( false );
    341 //      return 0;
    342 // }
    343 
    344 // void ForCtlExprNode::print( std::ostream &os, int indent ) const{
    345 //      os << string( indent,' ' ) << "For Control Expression -- :" << endl;
    346 
    347 //      os << string( indent + 2, ' ' ) << "initialization:" << endl;
    348 //      if ( init != 0 )
    349 //              init->printList( os, indent + 4 );
    350 
    351 //      os << string( indent + 2, ' ' ) << "condition: " << endl;
    352 //      if ( condition != 0 )
    353 //              condition->print( os, indent + 4 );
    354 //      os << string( indent + 2, ' ' ) << "increment: " << endl;
    355 //      if ( change != 0 )
    356 //              change->print( os, indent + 4 );
    357 // }
    358 
    359 // void ForCtlExprNode::printOneLine( std::ostream &, int indent ) const {
    360 //      assert( false );
    361 // }
    362 
    363 //##############################################################################
    364 
     300        return new UntypedValofExpr( maybeMoveBuild< Statement >(s), nullptr );
     301}
    365302Expression *build_typevalue( DeclarationNode *decl ) {
    366         return new TypeExpr( decl->buildType() );
    367 }
    368 
    369 //##############################################################################
     303        return new TypeExpr( maybeMoveBuildType( decl ) );
     304}
    370305
    371306Expression *build_compoundLiteral( DeclarationNode *decl_node, InitializerNode *kids ) {
    372         Declaration * newDecl = maybeBuild<Declaration>(decl_node); // compound literal type
     307        Declaration * newDecl = maybeBuild< Declaration >(decl_node); // compound literal type
    373308        if ( DeclarationWithType * newDeclWithType = dynamic_cast< DeclarationWithType * >( newDecl ) ) { // non-sue compound-literal type
    374                 return new CompoundLiteralExpr( newDeclWithType->get_type(), maybeBuild<Initializer>(kids) );
     309                return new CompoundLiteralExpr( newDeclWithType->get_type(), maybeMoveBuild< Initializer >(kids) );
    375310        // these types do not have associated type information
    376311        } else if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( newDecl )  ) {
    377                 return new CompoundLiteralExpr( new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() ), maybeBuild<Initializer>(kids) );
     312                return new CompoundLiteralExpr( new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
    378313        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( newDecl )  ) {
    379                 return new CompoundLiteralExpr( new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() ), maybeBuild<Initializer>(kids) );
     314                return new CompoundLiteralExpr( new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
    380315        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( newDecl )  ) {
    381                 return new CompoundLiteralExpr( new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() ), maybeBuild<Initializer>(kids) );
     316                return new CompoundLiteralExpr( new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() ), maybeMoveBuild< Initializer >(kids) );
    382317        } else {
    383318                assert( false );
  • src/Parser/InitializerNode.cc

    r79841be r6943a987  
    1010// Created On       : Sat May 16 13:20:24 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Jul  4 15:37:15 2016
    13 // Update Count     : 15
     12// Last Modified On : Mon Aug 15 18:27:02 2016
     13// Update Count     : 20
    1414//
    1515
     
    2525        : expr( _expr ), aggregate( aggrp ), designator( des ), kids( 0 ), maybeConstructed( true ) {
    2626        if ( aggrp )
    27                 kids = dynamic_cast< InitializerNode *>( get_link() );
     27                kids = dynamic_cast< InitializerNode * >( get_next() );
    2828
    2929        if ( kids != 0 )
    30                 set_link( 0 );
     30                set_last( 0 );
    3131}
    3232
     
    3434        : expr( 0 ), aggregate( aggrp ), designator( des ), kids( 0 ), maybeConstructed( true ) {
    3535        if ( init != 0 )
    36                 set_link(init);
     36                set_last( init );
    3737
    3838        if ( aggrp )
    39                 kids = dynamic_cast< InitializerNode *>( get_link() );
     39                kids = dynamic_cast< InitializerNode * >( get_next() );
    4040
    4141        if ( kids != 0 )
     
    4545InitializerNode::~InitializerNode() {
    4646        delete expr;
     47        delete designator;
     48        delete kids;
    4749}
    4850
     
    5860                        while ( curdes != 0) {
    5961                                curdes->printOneLine(os);
    60                                 curdes = (ExpressionNode *)(curdes->get_link());
     62                                curdes = (ExpressionNode *)(curdes->get_next());
    6163                                if ( curdes ) os << ", ";
    6264                        } // while
     
    7274
    7375        InitializerNode *moreInit;
    74         if  ( get_link() != 0 && ((moreInit = dynamic_cast< InitializerNode * >( get_link() ) ) != 0) )
     76        if  ( get_next() != 0 && ((moreInit = dynamic_cast< InitializerNode * >( get_next() ) ) != 0) )
    7577                moreInit->printOneLine( os );
    7678}
     
    8284                //assert( next_init() != 0 );
    8385
    84                 std::list< Initializer *> initlist;
    85                 buildList<Initializer, InitializerNode>( next_init(), initlist );
     86                std::list< Initializer * > initlist;
     87                buildList< Initializer, InitializerNode >( next_init(), initlist );
    8688
    87                 std::list< Expression *> designlist;
     89                std::list< Expression * > designlist;
    8890
    8991                if ( designator != 0 ) {
    90                         buildList<Expression, ExpressionNode>( designator, designlist );
     92                        buildList< Expression, ExpressionNode >( designator, designlist );
    9193                } // if
    9294
    9395                return new ListInit( initlist, designlist, maybeConstructed );
    9496        } else {
    95                 std::list< Expression *> designators;
     97                std::list< Expression * > designators;
    9698
    9799                if ( designator != 0 )
    98                         buildList<Expression, ExpressionNode>( designator, designators );
     100                        buildList< Expression, ExpressionNode >( designator, designators );
    99101
    100102                if ( get_expression() != 0)
    101                         return new SingleInit( maybeBuild<Expression>( get_expression() ), designators, maybeConstructed );
     103                        return new SingleInit( maybeBuild< Expression >( get_expression() ), designators, maybeConstructed );
    102104        } // if
    103105
  • src/Parser/LinkageSpec.cc

    r79841be r6943a987  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // LinkageSpec.cc -- 
    8 // 
     7// LinkageSpec.cc --
     8//
    99// Author           : Rodolfo G. Esteves
    1010// Created On       : Sat May 16 13:22:09 2015
    11 // Last Modified By : Rob Schluntz
    12 // Last Modified On : Wed Aug 19 15:53:05 2015
    13 // Update Count     : 5
    14 // 
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Sun Aug 21 12:32:53 2016
     13// Update Count     : 17
     14//
    1515
    1616#include <string>
     
    2020#include "Common/SemanticError.h"
    2121
    22 LinkageSpec::Type LinkageSpec::fromString( const std::string &stringSpec ) {
    23         if ( stringSpec == "\"Cforall\"" ) {
     22LinkageSpec::Spec LinkageSpec::fromString( const std::string &spec ) {
     23        if ( spec == "\"Cforall\"" ) {
    2424                return Cforall;
    25         } else if ( stringSpec == "\"C\"" ) {
     25        } else if ( spec == "\"C\"" ) {
    2626                return C;
    2727        } else {
    28                 throw SemanticError( "Invalid linkage specifier " + stringSpec );
    29         }
     28                throw SemanticError( "Invalid linkage specifier " + spec );
     29        } // if
     30        delete &spec;                                                                           // allocated by lexer
    3031}
    3132
    32 std::string LinkageSpec::toString( LinkageSpec::Type linkage ) {
    33         switch ( linkage ) {
    34           case Intrinsic:
    35                 return "intrinsic";
    36           case Cforall:
    37                 return "Cforall";
    38           case C:
    39                 return "C";
    40           case AutoGen:
    41                 return "automatically generated";
    42           case Compiler:
    43                 return "compiler built-in";
    44         }
    45         assert( false );
    46         return "";
     33std::string LinkageSpec::toString( LinkageSpec::Spec linkage ) {
     34        assert( linkage >= 0 && linkage < LinkageSpec::NoOfSpecs );
     35        static const char *linkageKinds[LinkageSpec::NoOfSpecs] = {
     36                "intrinsic", "Cforall", "C", "automatically generated", "compiler built-in",
     37        };
     38        return linkageKinds[linkage];
    4739}
    4840
    49 bool LinkageSpec::isDecoratable( Type t ) {
    50         switch ( t ) {
    51           case Intrinsic:
    52           case Cforall:
    53           case AutoGen:
    54                 return true;
    55           case C:
    56           case Compiler:
    57                 return false;
    58         }
    59         assert( false );
    60         return false;
     41bool LinkageSpec::isDecoratable( Spec spec ) {
     42        assert( spec >= 0 && spec < LinkageSpec::NoOfSpecs );
     43        static bool decoratable[LinkageSpec::NoOfSpecs] = {
     44                //      Intrinsic,      Cforall,        C,              AutoGen,        Compiler
     45                        true,           true,           false,  true,           false,
     46        };
     47        return decoratable[spec];
    6148}
    6249
    63 bool LinkageSpec::isGeneratable( Type t ) {
    64         switch ( t ) {
    65           case Intrinsic:
    66           case Cforall:
    67           case AutoGen:
    68           case C:
    69                 return true;
    70           case Compiler:
    71                 return false;
    72         }
    73         assert( false );
    74         return false;
     50bool LinkageSpec::isGeneratable( Spec spec ) {
     51        assert( spec >= 0 && spec < LinkageSpec::NoOfSpecs );
     52        static bool generatable[LinkageSpec::NoOfSpecs] = {
     53                //      Intrinsic,      Cforall,        C,              AutoGen,        Compiler
     54                        true,           true,           true,   true,           false,
     55        };
     56        return generatable[spec];
    7557}
    7658
    77 bool LinkageSpec::isOverloadable( Type t ) {
    78         return isDecoratable( t );
     59bool LinkageSpec::isOverridable( Spec spec ) {
     60        assert( spec >= 0 && spec < LinkageSpec::NoOfSpecs );
     61        static bool overridable[LinkageSpec::NoOfSpecs] = {
     62                //      Intrinsic,      Cforall,        C,              AutoGen,        Compiler
     63                        true,           false,          false,  true,           false,
     64        };
     65        return overridable[spec];
    7966}
    8067
    81 
    82 bool LinkageSpec::isOverridable( Type t ) {
    83         switch ( t ) {
    84           case Intrinsic:
    85           case AutoGen:
    86                 return true;
    87           case Cforall:
    88           case C:
    89           case Compiler:
    90                 return false;
    91         }
    92         assert( false );
    93         return false;
    94 }
    95 
    96 bool LinkageSpec::isBuiltin( Type t ) {
    97         switch ( t ) {
    98           case Cforall:
    99           case AutoGen:
    100           case C:
    101                 return false;
    102           case Intrinsic:
    103           case Compiler:
    104                 return true;
    105         }
    106         assert( false );
    107         return false;
     68bool LinkageSpec::isBuiltin( Spec spec ) {
     69        assert( spec >= 0 && spec < LinkageSpec::NoOfSpecs );
     70        static bool builtin[LinkageSpec::NoOfSpecs] = {
     71                //      Intrinsic,      Cforall,        C,              AutoGen,        Compiler
     72                        true,           false,          false,  false,          true,
     73        };
     74        return builtin[spec];
    10875}
    10976
  • src/Parser/LinkageSpec.h

    r79841be r6943a987  
    99// Author           : Rodolfo G. Esteves
    1010// Created On       : Sat May 16 13:24:28 2015
    11 // Last Modified By : Rob Schluntz
    12 // Last Modified On : Tue Aug 18 14:11:55 2015
    13 // Update Count     : 5
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Sat Aug 20 19:22:23 2016
     13// Update Count     : 8
    1414//
    1515
     
    2020
    2121struct LinkageSpec {
    22         enum Type {
     22        enum Spec {
    2323                Intrinsic,                                                                              // C built-in defined in prelude
    2424                Cforall,                                                                                // ordinary
    2525                C,                                                                                              // not overloadable, not mangled
    2626                AutoGen,                                                                                // built by translator (struct assignment)
    27                 Compiler                                                                                // gcc internal
     27                Compiler,                                                                               // gcc internal
     28                NoOfSpecs
    2829        };
    2930 
    30         static Type fromString( const std::string & );
    31         static std::string toString( Type );
     31        static Spec fromString( const std::string & );
     32        static std::string toString( Spec );
    3233 
    33         static bool isDecoratable( Type );
    34         static bool isGeneratable( Type );
    35         static bool isOverloadable( Type );
    36         static bool isOverridable( Type );
    37         static bool isBuiltin( Type );
     34        static bool isDecoratable( Spec );
     35        static bool isGeneratable( Spec );
     36        static bool isOverridable( Spec );
     37        static bool isBuiltin( Spec );
    3838};
    3939
  • src/Parser/ParseNode.cc

    r79841be r6943a987  
    1010// Created On       : Sat May 16 13:26:29 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sun Aug  7 23:32:47 2016
    13 // Update Count     : 94
     12// Last Modified On : Wed Aug 17 23:14:16 2016
     13// Update Count     : 126
    1414//
    1515
     
    1717using namespace std;
    1818
    19 // Builder
    2019int ParseNode::indent_by = 4;
    21 
    22 ParseNode::ParseNode() : next( 0 ) {};
    23 ParseNode::ParseNode( const string *name ) : name( *name ), next( 0 ) { delete name; }
    24 ParseNode::ParseNode( const string &name ) : name( name ), next( 0 ) { }
    25 
    26 ParseNode::~ParseNode() {
    27         delete next;
    28 };
    29 
    30 ParseNode *ParseNode::get_last() {
    31         ParseNode *current = this;
    32 
    33         while ( current->get_link() != 0 )
    34         current = current->get_link();
    35 
    36         return current;
    37 }
    38 
    39 ParseNode *ParseNode::set_link( ParseNode *next_ ) {
    40         if ( next_ != 0 ) get_last()->next = next_;
    41         return this;
    42 }
    43 
    44 void ParseNode::print( std::ostream &os, int indent ) const {}
    45 
    46 
    47 void ParseNode::printList( std::ostream &os, int indent ) const {
    48         print( os, indent );
    49 
    50         if ( next ) {
    51                 next->printList( os, indent );
    52         } // if
    53 }
    54 
    55 ParseNode &ParseNode::operator,( ParseNode &p ) {
    56         set_link( &p );
    57 
    58         return *this;
    59 }
    60 
    61 ParseNode *mkList( ParseNode &pn ) {
    62         // it just relies on `operator,' to take care of the "arguments" and provides a nice interface to an awful-looking
    63         // address-of, rendering, for example (StatementNode *)(&(*$5 + *$7)) into (StatementNode *)mkList(($5, $7))
    64         // (although "nice" is probably not the word)
    65         return &pn;
    66 }
    6720
    6821// Local Variables: //
  • src/Parser/ParseNode.h

    r79841be r6943a987  
    1010// Created On       : Sat May 16 13:28:16 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Aug 11 12:24:11 2016
    13 // Update Count     : 443
     12// Last Modified On : Sun Aug 28 21:14:51 2016
     13// Update Count     : 575
    1414//
    1515
     
    2222#include <memory>
    2323
    24 #include "Common/utility.h"
    2524#include "Parser/LinkageSpec.h"
    2625#include "SynTree/Type.h"
    2726#include "SynTree/Expression.h"
    2827#include "SynTree/Statement.h"
    29 //#include "SynTree/Declaration.h"
     28#include "SynTree/Label.h"
     29#include "Common/utility.h"
    3030#include "Common/UniqueName.h"
    31 #include "SynTree/Label.h"
    3231
    3332class StatementNode;
     
    3736class InitializerNode;
    3837
    39 // Builder
     38//##############################################################################
     39
    4040class ParseNode {
    4141  public:
    42         ParseNode();
    43         ParseNode( const std::string * );
    44         ParseNode( const std::string & );                                       // for copy constructing subclasses
    45         virtual ~ParseNode();
    46 
    47         ParseNode *get_link() const { return next; }
    48         ParseNode *get_last();
    49         ParseNode *set_link( ParseNode * );
    50         void set_next( ParseNode *newlink ) { next = newlink; }
    51 
    52         virtual ParseNode *clone() const { return 0; };
     42        ParseNode() {};
     43        ParseNode( const std::string *name ) : name( *name ) { assert( false ); delete name; }
     44        ParseNode( const std::string &name ) : name( name ) { assert( false ); }
     45        virtual ~ParseNode() { delete next; };
     46        virtual ParseNode *clone() const = 0;
     47
     48        ParseNode *get_next() const { return next; }
     49        ParseNode *set_next( ParseNode *newlink ) { next = newlink; return this; }
     50        ParseNode *get_last() {
     51                ParseNode *current;
     52                for ( current = this; current->get_next() != 0; current = current->get_next() );
     53                return current;
     54        }
     55        ParseNode *set_last( ParseNode *newlast ) {
     56                if ( newlast != 0 ) get_last()->set_next( newlast );
     57                return this;
     58        }
    5359
    5460        const std::string &get_name() const { return name; }
    5561        void set_name( const std::string &newValue ) { name = newValue; }
    5662
    57         virtual void print( std::ostream &os, int indent = 0 ) const;
    58         virtual void printList( std::ostream &os, int indent = 0 ) const;
    59 
    60         ParseNode &operator,( ParseNode & );
    61   protected:
     63        virtual void print( std::ostream &os, int indent = 0 ) const {}
     64        virtual void printList( std::ostream &os, int indent = 0 ) const {}
     65  private:
     66        static int indent_by;
     67
     68        ParseNode *next = nullptr;
    6269        std::string name;
    63         static int indent_by;
    64         ParseNode *next;
    65 };
    66 
    67 ParseNode *mkList( ParseNode & );
     70}; // ParseNode
    6871
    6972//##############################################################################
     
    7477        InitializerNode( InitializerNode *, bool aggrp = false, ExpressionNode *des = 0 );
    7578        ~InitializerNode();
     79        virtual InitializerNode *clone() const { assert( false ); return nullptr; }
    7680
    7781        ExpressionNode *get_expression() const { return expr; }
     
    9296        ExpressionNode *expr;
    9397        bool aggregate;
    94         ExpressionNode *designator; // may be list
     98        ExpressionNode *designator;                                                     // may be list
    9599        InitializerNode *kids;
    96100        bool maybeConstructed;
    97 };
    98 
    99 //##############################################################################
    100 
    101 class ExpressionNode : public ParseNode {
     101}; // InitializerNode
     102
     103//##############################################################################
     104
     105class ExpressionNode final : public ParseNode {
    102106  public:
    103107        ExpressionNode( Expression * expr = nullptr ) : expr( expr ) {}
     
    105109        ExpressionNode( const ExpressionNode &other );
    106110        virtual ~ExpressionNode() {}
    107 
    108         virtual ExpressionNode *clone() const { return 0; }
     111        virtual ExpressionNode *clone() const { return expr ? new ExpressionNode( expr->clone() ) : nullptr; }
    109112
    110113        bool get_extension() const { return extension; }
    111114        ExpressionNode *set_extension( bool exten ) { extension = exten; return this; }
    112115
    113         virtual void print( std::ostream &os, int indent = 0 ) const {}
    114         virtual void printOneLine( std::ostream &os, int indent = 0 ) const {}
    115 
    116         virtual Expression *build() const { return expr; }
     116        void print( std::ostream &os, int indent = 0 ) const {}
     117        void printOneLine( std::ostream &os, int indent = 0 ) const {}
     118
     119        template<typename T>
     120        bool isExpressionType() const {
     121                return nullptr != dynamic_cast<T>(expr.get());
     122        }
     123
     124        Expression *build() const { return const_cast<ExpressionNode*>(this)->expr.release(); }
    117125  private:
    118126        bool extension = false;
    119         Expression *expr;
    120 };
     127        std::unique_ptr<Expression> expr;
     128}; // ExpressionNode
    121129
    122130template< typename T >
    123 struct maybeBuild_t<Expression, T> {
     131struct maybeBuild_t< Expression, T > {
    124132        static inline Expression * doit( const T *orig ) {
    125133                if ( orig ) {
     
    128136                        return p;
    129137                } else {
    130                         return 0;
     138                        return nullptr;
    131139                } // if
    132140        }
    133141};
    134 
    135 //##############################################################################
    136 
    137 Expression *build_constantInteger( std::string &str );
    138 Expression *build_constantFloat( std::string &str );
    139 Expression *build_constantChar( std::string &str );
    140 ConstantExpr *build_constantStr( std::string &str );
    141 
    142 //##############################################################################
    143 
    144 NameExpr *build_varref( const std::string *name, bool labelp = false );
    145 
    146 //##############################################################################
    147 
    148 Expression *build_typevalue( DeclarationNode *decl );
    149 
    150 //##############################################################################
    151142
    152143enum class OperKinds {
     
    154145        SizeOf, AlignOf, OffsetOf, Plus, Minus, Mul, Div, Mod, Or, And,
    155146        BitOr, BitAnd, Xor, Cast, LShift, RShift, LThan, GThan, LEThan, GEThan, Eq, Neq,
    156         Assign, MulAssn, DivAssn, ModAssn, PlusAssn, MinusAssn, LSAssn, RSAssn, AndAssn, ERAssn, OrAssn,
     147        Assign, AtAssn, MulAssn, DivAssn, ModAssn, PlusAssn, MinusAssn, LSAssn, RSAssn, AndAssn, ERAssn, OrAssn,
    157148        Index, Range,
    158149        // monadic
    159150        UnPlus, UnMinus, AddressOf, PointTo, Neg, BitNeg, Incr, IncrPost, Decr, DecrPost, LabelAddress,
    160151        Ctor, Dtor,
     152}; // OperKinds
     153
     154struct LabelNode {
     155        std::list< Label > labels;
    161156};
     157
     158Expression *build_constantInteger( const std::string &str );
     159Expression *build_constantFloat( const std::string &str );
     160Expression *build_constantChar( const std::string &str );
     161ConstantExpr *build_constantStr( const std::string &str );
     162
     163NameExpr *build_varref( const std::string *name, bool labelp = false );
     164Expression *build_typevalue( DeclarationNode *decl );
    162165
    163166Expression *build_cast( DeclarationNode * decl_node, ExpressionNode *expr_node );
     
    183186Expression *build_func( ExpressionNode * function, ExpressionNode * expr_node );
    184187Expression *build_range( ExpressionNode * low, ExpressionNode *high );
    185 
    186 //##############################################################################
    187 
    188 Expression *build_asm( ExpressionNode *inout, ConstantExpr *constraint, ExpressionNode *operand );
    189 
    190 //##############################################################################
    191 
    192 class LabelNode : public ExpressionNode {
    193   public:
    194         virtual Expression *build() const { return NULL; }
    195         virtual LabelNode *clone() const { assert( false ); return new LabelNode( *this ); }
    196 
    197         virtual void print( std::ostream &os, int indent = 0) const;
    198         virtual void printOneLine( std::ostream &os, int indent = 0) const;
    199 
    200         const std::list< Label > &get_labels() const { return labels; };
    201         void append_label( std::string * label ) { labels.push_back( *label ); delete label; }
    202   private:
    203         std::list< Label > labels;
    204 };
    205 
    206 //##############################################################################
    207 
     188Expression *build_asmexpr( ExpressionNode *inout, ConstantExpr *constraint, ExpressionNode *operand );
    208189Expression *build_valexpr( StatementNode *s );
    209 
    210 //##############################################################################
    211 
    212190Expression *build_compoundLiteral( DeclarationNode *decl_node, InitializerNode *kids );
    213191
     
    218196class DeclarationNode : public ParseNode {
    219197  public:
    220         enum Qualifier { Const, Restrict, Volatile, Lvalue, Atomic };
     198        enum Qualifier { Const, Restrict, Volatile, Lvalue, Atomic, NoOfQualifier };
    221199        enum StorageClass { Extern, Static, Auto, Register, Inline, Fortran, Noreturn, Threadlocal, NoStorageClass, };
    222200        enum BasicType { Char, Int, Float, Double, Void, Bool, Complex, Imaginary };
     
    226204        enum BuiltinType { Valist };
    227205
     206        static const char *qualifierName[];
    228207        static const char *storageName[];
    229         static const char *qualifierName[];
    230208        static const char *basicTypeName[];
    231209        static const char *modifierName[];
     
    236214        static DeclarationNode *newFunction( std::string *name, DeclarationNode *ret, DeclarationNode *param, StatementNode *body, bool newStyle = false );
    237215        static DeclarationNode *newQualifier( Qualifier );
     216        static DeclarationNode *newForall( DeclarationNode *);
    238217        static DeclarationNode *newStorageClass( StorageClass );
    239218        static DeclarationNode *newBasicType( BasicType );
    240219        static DeclarationNode *newModifier( Modifier );
    241         static DeclarationNode *newForall( DeclarationNode *);
     220        static DeclarationNode *newBuiltinType( BuiltinType );
    242221        static DeclarationNode *newFromTypedef( std::string *);
    243222        static DeclarationNode *newAggregate( Aggregate kind, const std::string *name, ExpressionNode *actuals, DeclarationNode *fields, bool body );
     
    258237        static DeclarationNode *newAttr( std::string *, ExpressionNode *expr );
    259238        static DeclarationNode *newAttr( std::string *, DeclarationNode *type );
    260         static DeclarationNode *newBuiltinType( BuiltinType );
     239
     240        DeclarationNode();
     241        ~DeclarationNode();
     242        DeclarationNode *clone() const;
    261243
    262244        DeclarationNode *addQualifiers( DeclarationNode *);
     245        void checkQualifiers( const TypeData *, const TypeData * );
    263246        DeclarationNode *copyStorageClasses( DeclarationNode *);
    264247        DeclarationNode *addType( DeclarationNode *);
     
    275258        DeclarationNode *addNewArray( DeclarationNode *array );
    276259        DeclarationNode *addParamList( DeclarationNode *list );
    277         DeclarationNode *addIdList( DeclarationNode *list );       // old-style functions
     260        DeclarationNode *addIdList( DeclarationNode *list ); // old-style functions
    278261        DeclarationNode *addInitializer( InitializerNode *init );
    279262
     
    284267        DeclarationNode *cloneBaseType( DeclarationNode *newdecl );
    285268
    286         DeclarationNode *appendList( DeclarationNode * );
    287 
    288         DeclarationNode *clone() const;
     269        DeclarationNode *appendList( DeclarationNode *node ) {
     270                return (DeclarationNode *)set_last( node );
     271        }
     272
    289273        void print( std::ostream &os, int indent = 0 ) const;
    290274        void printList( std::ostream &os, int indent = 0 ) const;
     
    295279        bool get_hasEllipsis() const;
    296280        const std::string &get_name() const { return name; }
    297         LinkageSpec::Type get_linkage() const { return linkage; }
     281        LinkageSpec::Spec get_linkage() const { return linkage; }
    298282        DeclarationNode *extractAggregate() const;
    299         ExpressionNode *get_enumeratorValue() const { return enumeratorValue; }
     283        bool has_enumeratorValue() const { return (bool)enumeratorValue; }
     284        ExpressionNode *consume_enumeratorValue() const { return const_cast<DeclarationNode*>(this)->enumeratorValue.release(); }
    300285
    301286        bool get_extension() const { return extension; }
    302287        DeclarationNode *set_extension( bool exten ) { extension = exten; return this; }
    303 
    304         DeclarationNode();
    305         ~DeclarationNode();
    306   private:
    307         StorageClass buildStorageClass() const;
    308         bool buildFuncSpecifier( StorageClass key ) const;
     288  public:
     289        // StorageClass buildStorageClass() const;
     290        // bool buildFuncSpecifier( StorageClass key ) const;
    309291
    310292        TypeData *type;
    311293        std::string name;
    312         std::list< StorageClass > storageClasses;
     294        // std::list< StorageClass > storageClasses;
     295        StorageClass storageClass;
     296        bool isInline, isNoreturn;
    313297        std::list< std::string > attributes;
    314298        ExpressionNode *bitfieldWidth;
    315         ExpressionNode *enumeratorValue;
     299        std::unique_ptr<ExpressionNode> enumeratorValue;
    316300        InitializerNode *initializer;
    317301        bool hasEllipsis;
    318         LinkageSpec::Type linkage;
     302        LinkageSpec::Spec linkage;
    319303        bool extension = false;
     304        std::string error;
    320305
    321306        static UniqueName anonymous;
     
    323308
    324309Type *buildType( TypeData *type );
    325 
    326 //##############################################################################
    327 
    328 class StatementNode : public ParseNode {
    329   public:
    330         enum Type { Exp,   If,        Switch,  Case,    Default,  Choose,   Fallthru,
    331                                 While, Do,        For,
    332                                 Goto,  Continue,  Break,   Return,  Throw,
    333                                 Try,   Catch,     Finally, Asm,
    334                                 Decl
    335         };
    336 
    337         StatementNode();
    338         StatementNode( const std::string *name );
    339         StatementNode( Type t, ExpressionNode *control = 0, StatementNode *block = 0 );
    340         StatementNode( Type t, std::string *target );
     310//Type::Qualifiers buildQualifiers( const TypeData::Qualifiers & qualifiers );
     311
     312static inline Type * maybeMoveBuildType( const DeclarationNode *orig ) {
     313        Type* ret = orig ? orig->buildType() : nullptr;
     314        delete orig;
     315        return ret;
     316}
     317
     318//##############################################################################
     319
     320class StatementNode final : public ParseNode {
     321  public:
     322        StatementNode() { stmt = nullptr; }
     323        StatementNode( Statement *stmt ) : stmt( stmt ) {}
    341324        StatementNode( DeclarationNode *decl );
    342 
    343         ~StatementNode();
    344 
    345         static StatementNode *newCatchStmt( DeclarationNode *d = 0, StatementNode *s = 0, bool catchRestP = false );
    346 
    347         StatementNode *set_block( StatementNode *b ) { block = b; return this; }
    348         StatementNode *get_block() const { return block; }
    349 
    350         void set_control( ExpressionNode *c ) { control = c; }
    351         ExpressionNode *get_control() const { return control; }
    352 
    353         StatementNode::Type get_type() const { return type; }
    354 
    355         virtual StatementNode *add_label( const std::string * );
    356         virtual std::list<std::string> get_labels() const { return labels; }
    357 
    358         void addDeclaration( DeclarationNode *newDecl ) { decl = newDecl; }
    359         void setCatchRest( bool newVal ) { isCatchRest = newVal; }
    360 
    361         std::string get_target() const;
    362 
    363         // StatementNode *add_controlexp( ExpressionNode * );
    364         StatementNode *append_block( StatementNode * );
     325        virtual ~StatementNode() {}
     326
     327        virtual StatementNode *clone() const final { assert( false ); return nullptr; }
     328        Statement *build() const { return const_cast<StatementNode*>(this)->stmt.release(); }
     329
     330        virtual StatementNode *add_label( const std::string * name ) {
     331                stmt->get_labels().emplace_back( *name );
     332                delete name;
     333                return this;
     334        }
     335
    365336        virtual StatementNode *append_last_case( StatementNode * );
    366 
    367         void print( std::ostream &os, int indent = 0) const;
    368         virtual StatementNode *clone() const;
    369         virtual Statement *build() const;
    370   private:
    371         static const char *StType[];
    372         Type type;
    373         ExpressionNode *control;
    374         StatementNode *block;
    375         std::list<std::string> labels;
    376         std::string *target;                            // target label for jump statements
    377         DeclarationNode *decl;
    378         bool isCatchRest;
    379 }; // StatementNode
    380 
    381 class StatementNode2 : public StatementNode {
    382   public:
    383         StatementNode2() {}
    384         StatementNode2( Statement *stmt ) : stmt( stmt ) {}
    385         virtual ~StatementNode2() {}
    386 
    387         virtual StatementNode2 *clone() const { assert( false ); return nullptr; }
    388         virtual Statement *build() const { return stmt; }
    389 
    390         virtual StatementNode2 *add_label( const std::string * name ) {
    391                 stmt->get_labels().emplace_back( *name );
    392                 return this;
    393         }
    394         virtual StatementNode *append_last_case( StatementNode * );
    395         virtual std::list<std::string> get_labels() const { assert( false ); return StatementNode::get_labels(); }
    396337
    397338        virtual void print( std::ostream &os, int indent = 0 ) {}
    398339        virtual void printList( std::ostream &os, int indent = 0 ) {}
    399340  private:
    400         Statement *stmt;
     341        std::unique_ptr<Statement> stmt;
    401342}; // StatementNode
     343
     344Statement *build_expr( ExpressionNode *ctl );
    402345
    403346struct ForCtl {
    404347        ForCtl( ExpressionNode *expr, ExpressionNode *condition, ExpressionNode *change ) :
    405                 init( new StatementNode( StatementNode::Exp, expr ) ), condition( condition ), change( change ) {}
     348                init( new StatementNode( build_expr( expr ) ) ), condition( condition ), change( change ) {}
    406349        ForCtl( DeclarationNode *decl, ExpressionNode *condition, ExpressionNode *change ) :
    407350                init( new StatementNode( decl ) ), condition( condition ), change( change ) {}
     
    412355};
    413356
    414 Statement *build_expr( ExpressionNode *ctl );
    415357Statement *build_if( ExpressionNode *ctl, StatementNode *then_stmt, StatementNode *else_stmt );
    416358Statement *build_switch( ExpressionNode *ctl, StatementNode *stmt );
     
    419361Statement *build_while( ExpressionNode *ctl, StatementNode *stmt, bool kind = false );
    420362Statement *build_for( ForCtl *forctl, StatementNode *stmt );
    421 Statement *build_branch( std::string identifier, BranchStmt::Type kind );
     363Statement *build_branch( BranchStmt::Type kind );
     364Statement *build_branch( std::string *identifier, BranchStmt::Type kind );
    422365Statement *build_computedgoto( ExpressionNode *ctl );
    423366Statement *build_return( ExpressionNode *ctl );
    424367Statement *build_throw( ExpressionNode *ctl );
    425 
    426 //##############################################################################
    427 
    428 class CompoundStmtNode : public StatementNode {
    429   public:
    430         CompoundStmtNode();
    431         CompoundStmtNode( const std::string * );
    432         CompoundStmtNode( StatementNode * );
    433         ~CompoundStmtNode();
    434 
    435         void add_statement( StatementNode * );
    436 
    437         void print( std::ostream &os, int indent = 0 ) const;
    438         virtual Statement *build() const;
    439   private:
    440         StatementNode *first, *last;
    441 };
    442 
    443 //##############################################################################
    444 
    445 class AsmStmtNode : public StatementNode {
    446   public:
    447         AsmStmtNode( Type, bool voltile, ConstantExpr *instruction, ExpressionNode *output = 0, ExpressionNode *input = 0, ExpressionNode *clobber = 0, LabelNode *gotolabels = 0 );
    448         ~AsmStmtNode();
    449 
    450         void print( std::ostream &os, int indent = 0 ) const;
    451         Statement *build() const;
    452   private:
    453         bool voltile;
    454         ConstantExpr *instruction;
    455         ExpressionNode *output, *input;
    456         ExpressionNode *clobber;
    457         std::list< Label > gotolabels;
    458 };
     368Statement *build_try( StatementNode *try_stmt, StatementNode *catch_stmt, StatementNode *finally_stmt );
     369Statement *build_catch( DeclarationNode *decl, StatementNode *stmt, bool catchAny = false );
     370Statement *build_finally( StatementNode *stmt );
     371Statement *build_compound( StatementNode *first );
     372Statement *build_asmstmt( bool voltile, ConstantExpr *instruction, ExpressionNode *output = 0, ExpressionNode *input = 0, ExpressionNode *clobber = 0, LabelNode *gotolabels = 0 );
    459373
    460374//##############################################################################
     
    463377void buildList( const NodeType *firstNode, std::list< SynTreeType * > &outputList ) {
    464378        SemanticError errors;
    465         std::back_insert_iterator< std::list< SynTreeType *> > out( outputList );
     379        std::back_insert_iterator< std::list< SynTreeType * > > out( outputList );
    466380        const NodeType *cur = firstNode;
    467381
    468382        while ( cur ) {
    469383                try {
    470 //                      SynTreeType *result = dynamic_cast< SynTreeType *>( maybeBuild<typename std::result_of<decltype(&NodeType::build)(NodeType)>::type>( cur ) );
    471                         SynTreeType *result = dynamic_cast< SynTreeType *>( maybeBuild<typename std::pointer_traits<decltype(cur->build())>::element_type>( cur ) );
     384//                      SynTreeType *result = dynamic_cast< SynTreeType * >( maybeBuild< typename std::result_of< decltype(&NodeType::build)(NodeType)>::type >( cur ) );
     385                        SynTreeType *result = dynamic_cast< SynTreeType * >( maybeBuild< typename std::pointer_traits< decltype(cur->build())>::element_type >( cur ) );
    472386                        if ( result ) {
    473387                                *out++ = result;
     
    477391                        errors.append( e );
    478392                } // try
    479                 cur = dynamic_cast< NodeType *>( cur->get_link() );
     393                cur = dynamic_cast< NodeType * >( cur->get_next() );
    480394        } // while
    481395        if ( ! errors.isEmpty() ) {
     
    486400// in DeclarationNode.cc
    487401void buildList( const DeclarationNode *firstNode, std::list< Declaration * > &outputList );
    488 void buildList( const DeclarationNode *firstNode, std::list< DeclarationWithType *> &outputList );
     402void buildList( const DeclarationNode *firstNode, std::list< DeclarationWithType * > &outputList );
    489403void buildTypeList( const DeclarationNode *firstNode, std::list< Type * > &outputList );
     404
     405template< typename SynTreeType, typename NodeType >
     406void buildMoveList( const NodeType *firstNode, std::list< SynTreeType * > &outputList ) {
     407        buildList(firstNode, outputList);
     408        delete firstNode;
     409}
     410
    490411
    491412#endif // PARSENODE_H
  • src/Parser/StatementNode.cc

    r79841be r6943a987  
    1010// Created On       : Sat May 16 14:59:41 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Aug 11 16:19:45 2016
    13 // Update Count     : 210
     12// Last Modified On : Sun Aug 21 11:59:37 2016
     13// Update Count     : 325
    1414//
    1515
     
    2626using namespace std;
    2727
    28 const char *StatementNode::StType[] = {
    29         "Exp",   "If",       "Switch", "Case",    "Default",  "Choose",   "Fallthru",
    30         "While", "Do",       "For",
    31         "Goto",  "Continue", "Break",  "Return",  "Throw",
    32         "Try",   "Catch",    "Finally", "Asm",
    33         "Decl"
    34 };
    35 
    36 StatementNode::StatementNode() : ParseNode(), control( 0 ), block( 0 ), labels( 0 ), target( 0 ), decl( 0 ), isCatchRest ( false ) {}
    37 
    38 StatementNode::StatementNode( const string *name ) : ParseNode( name ), control( 0 ), block( 0 ), labels( 0 ), target( 0 ), decl( 0 ), isCatchRest ( false ) {}
    39 
    40 StatementNode::StatementNode( DeclarationNode *decl ) : type( Decl ), control( 0 ), block( 0 ), labels( 0 ), target( 0 ), isCatchRest ( false ) {
     28
     29StatementNode::StatementNode( DeclarationNode *decl ) {
    4130        if ( decl ) {
    42                 if ( DeclarationNode *agg = decl->extractAggregate() ) {
    43                         this->decl = agg;
    44                         StatementNode *nextStmt = new StatementNode;
    45                         nextStmt->type = Decl;
    46                         nextStmt->decl = decl;
    47                         next = nextStmt;
    48                         if ( decl->get_link() ) {
    49                                 next->set_next( new StatementNode( dynamic_cast< DeclarationNode* >( decl->get_link() ) ) );
     31                DeclarationNode *agg = decl->extractAggregate();
     32                if ( agg ) {
     33                        StatementNode *nextStmt = new StatementNode( new DeclStmt( noLabels, maybeBuild< Declaration >( decl ) ) );
     34                        set_next( nextStmt );
     35                        if ( decl->get_next() ) {
     36                                get_next()->set_next( new StatementNode( dynamic_cast< DeclarationNode * >(decl->get_next()) ) );
    5037                                decl->set_next( 0 );
    5138                        } // if
    5239                } else {
    53                         if ( decl->get_link() ) {
    54                                 next = new StatementNode( dynamic_cast< DeclarationNode* >( decl->get_link() ) );
     40                        if ( decl->get_next() ) {
     41                                set_next(new StatementNode( dynamic_cast< DeclarationNode * >( decl->get_next() ) ) );
    5542                                decl->set_next( 0 );
    5643                        } // if
    57                         this->decl = decl;
     44                        agg = decl;
    5845                } // if
     46                stmt.reset( new DeclStmt( noLabels, maybeMoveBuild< Declaration >(agg) ) );
     47        } else {
     48                assert( false );
    5949        } // if
    6050}
    6151
    62 StatementNode::StatementNode( Type t, ExpressionNode *ctrl_label, StatementNode *block ) : type( t ), control( ctrl_label ), block( block ), labels( 0 ), target( 0 ), decl( 0 ), isCatchRest ( false ) {
    63         this->control = ( t == Default ) ? 0 : control;
    64 }
    65 
    66 StatementNode::StatementNode( Type t, string *target ) : type( t ), control( 0 ), block( 0 ), labels( 0 ), target( target ), decl( 0 ), isCatchRest ( false ) {}
    67 
    68 StatementNode::~StatementNode() {
    69         delete control;
    70         delete block;
    71         delete target;
    72         delete decl;
    73 }
    74 
    75 StatementNode * StatementNode::newCatchStmt( DeclarationNode *d, StatementNode *s, bool catchRestP ) {
    76         StatementNode *ret = new StatementNode( StatementNode::Catch, 0, s );
    77         ret->addDeclaration( d );
    78         ret->setCatchRest( catchRestP );
    79 
    80         return ret;
    81 }
    82 
    83 std::string StatementNode::get_target() const{
    84         if ( target )
    85                 return *target;
    86 
    87         return string("");
    88 }
    89 
    90 StatementNode * StatementNode::clone() const {
    91         StatementNode *newnode = new StatementNode( type, maybeClone( control ), maybeClone( block ) );
    92         if ( target ) {
    93                 newnode->target = new string( *target );
    94         } else {
    95                 newnode->target = 0;
    96         } // if
    97         newnode->decl = maybeClone( decl );
    98         return newnode;
    99 }
    100 
    101 StatementNode *StatementNode::add_label( const std::string *l ) {
    102         if ( l != 0 ) {
    103                 labels.push_front( *l );
    104                 delete l;
    105         } // if
    106         return this;
    107 }
    108 
    109 StatementNode *StatementNode::append_block( StatementNode *stmt ) {
    110         if ( stmt != 0 ) {
    111                 if ( block == 0 )
    112                         block = stmt;
    113                 else
    114                         block->set_link( stmt );
    115         } // if
    116         return this;
    117 }
    118 
    11952StatementNode *StatementNode::append_last_case( StatementNode *stmt ) {
    120         assert( false );
    121         if ( stmt != 0 ) {
    122                 StatementNode *next = ( StatementNode *)get_link();
    123                 if ( next && ( next->get_type() == StatementNode::Case || next->get_type() == StatementNode::Default ) )
    124                         next->append_last_case( stmt );
    125                 else
    126                         if ( block == 0 )
    127                                 block = stmt;
    128                         else
    129                                 block->set_link( stmt );
    130         } // if
    131         return this;
    132 }
    133 
    134 StatementNode *StatementNode2::append_last_case( StatementNode *stmt ) {
    13553        StatementNode *prev = this;
    136         for ( StatementNode * curr = prev; curr != nullptr; curr = (StatementNode *)curr->get_link() ) {
    137                 StatementNode2 *node = dynamic_cast<StatementNode2 *>(curr);
    138                 assert( node );
    139                 assert( dynamic_cast<CaseStmt *>(node->stmt) );
     54        // find end of list and maintain previous pointer
     55        for ( StatementNode * curr = prev; curr != nullptr; curr = (StatementNode *)curr->get_next() ) {
     56                StatementNode *node = safe_dynamic_cast< StatementNode * >(curr);
     57                assert( dynamic_cast< CaseStmt * >(node->stmt.get()) );
    14058                prev = curr;
    14159        } // for
    142         StatementNode2 *node = dynamic_cast<StatementNode2 *>(prev);
    143         std::list<Statement *> stmts;
    144         buildList( stmt, stmts );
    145         CaseStmt * caseStmt;
    146         caseStmt = dynamic_cast<CaseStmt *>(node->stmt);
     60        // convert from StatementNode list to Statement list
     61        StatementNode *node = dynamic_cast< StatementNode * >(prev);
     62        std::list< Statement * > stmts;
     63        buildMoveList( stmt, stmts );
     64        // splice any new Statements to end of current Statements
     65        CaseStmt * caseStmt = dynamic_cast< CaseStmt * >(node->stmt.get());
    14766        caseStmt->get_statements().splice( caseStmt->get_statements().end(), stmts );
    14867        return this;
    14968}
    15069
    151 void StatementNode::print( std::ostream &os, int indent ) const {
    152         if ( ! labels.empty() ) {
    153                 std::list<std::string>::const_iterator i;
    154 
    155                 os << string( indent, ' ' );
    156                 for ( i = labels.begin(); i != labels.end(); i++ )
    157                         os << *i << ":";
    158                 os << endl;
    159         } // if
    160 
    161         switch ( type ) {
    162           case Decl:
    163                 decl->print( os, indent );
    164                 break;
    165           case Exp:
    166                 if ( control ) {
    167                         os << string( indent, ' ' );
    168                         control->print( os, indent );
    169                         os << endl;
    170                 } else
    171                         os << string( indent, ' ' ) << "Null Statement" << endl;
    172                 break;
    173           default:
    174                 os << string( indent, ' ' ) << StatementNode::StType[type] << endl;
    175                 if ( type == Catch ) {
    176                         if ( decl ) {
    177                                 os << string( indent + ParseNode::indent_by, ' ' ) << "Declaration: " << endl;
    178                                 decl->print( os, indent + 2 * ParseNode::indent_by );
    179                         } else if ( isCatchRest ) {
    180                                 os << string( indent + ParseNode::indent_by, ' ' ) << "Catches the rest " << endl;
    181                         } else {
    182                                 ; // should never reach here
    183                         } // if
    184                 } // if
    185                 if ( control ) {
    186                         os << string( indent + ParseNode::indent_by, ' ' ) << "Control: " << endl;
    187                         control->printList( os, indent + 2 * ParseNode::indent_by );
    188                 } // if
    189                 if ( block ) {
    190                         os << string( indent + ParseNode::indent_by, ' ' ) << "Cases: " << endl;
    191                         block->printList( os, indent + 2 * ParseNode::indent_by );
    192                 } // if
    193                 if ( target ) {
    194                         os << string( indent + ParseNode::indent_by, ' ' ) << "Target: " << get_target() << endl;
    195                 } // if
    196                 break;
    197         } // switch
    198 }
    199 
    200 Statement *StatementNode::build() const {
    201         std::list<Statement *> branches;
    202         std::list<Expression *> exps;
    203         std::list<Label> labs;
    204 
    205         if ( ! labels.empty() ) {
    206                 std::back_insert_iterator< std::list<Label> > lab_it( labs );
    207                 copy( labels.begin(), labels.end(), lab_it );
    208         } // if
    209 
    210         // try {
    211         buildList<Statement, StatementNode>( get_block(), branches );
    212 
    213         switch ( type ) {
    214           case Decl:
    215                 return new DeclStmt( labs, maybeBuild< Declaration >( decl ) );
    216           case Exp:
    217                 {
    218                         Expression *e = maybeBuild< Expression >( get_control() );
    219 
    220                         if ( e )
    221                                 return new ExprStmt( labs, e );
    222                         else
    223                                 return new NullStmt( labs );
    224                 }
    225                 assert( false );
    226           case If:
    227                 // {
    228                 //      Statement *thenb = 0, *elseb = 0;
    229                 //      assert( branches.size() >= 1 );
    230 
    231                 //      thenb = branches.front();
    232                 //      branches.pop_front();
    233                 //      if ( ! branches.empty() ) {
    234                 //              elseb = branches.front();
    235                 //              branches.pop_front();
    236                 //      } // if
    237                 //      return new IfStmt( labs, notZeroExpr( maybeBuild<Expression>(get_control()) ), thenb, elseb );
    238                 // }
    239                 assert( false );
    240           case Switch:
    241                 // return new SwitchStmt( labs, maybeBuild<Expression>(get_control()), branches );
    242                 assert( false );
    243           case Case:
    244                 //return new CaseStmt( labs, maybeBuild<Expression>(get_control() ), branches );
    245                 assert( false );
    246           case Default:
    247                 //return new CaseStmt( labs, 0, branches, true );
    248                 assert( false );
    249           case While:
    250                 // assert( branches.size() == 1 );
    251                 // return new WhileStmt( labs, notZeroExpr( maybeBuild<Expression>(get_control()) ), branches.front() );
    252                 assert( false );
    253           case Do:
    254                 // assert( branches.size() == 1 );
    255                 // return new WhileStmt( labs, notZeroExpr( maybeBuild<Expression>(get_control()) ), branches.front(), true );
    256                 assert( false );
    257           case For:
    258                 // {
    259                 //      assert( branches.size() == 1 );
    260 
    261                 //      ForCtlExprNode *ctl = dynamic_cast<ForCtlExprNode *>( get_control() );
    262                 //      assert( ctl != 0 );
    263 
    264                 //      std::list<Statement *> init;
    265                 //      if ( ctl->get_init() != 0 ) {
    266                 //              buildList( ctl->get_init(), init );
    267                 //      } // if
    268 
    269                 //      Expression *cond = 0;
    270                 //      if ( ctl->get_condition() != 0 )
    271                 //              cond = notZeroExpr( maybeBuild<Expression>(ctl->get_condition()) );
    272 
    273                 //      Expression *incr = 0;
    274                 //      if ( ctl->get_change() != 0 )
    275                 //              incr = maybeBuild<Expression>(ctl->get_change());
    276 
    277                 //      return new ForStmt( labs, init, cond, incr, branches.front() );
    278                 // }
    279                 assert( false );
    280           case Goto:
    281                 // {
    282                 //      if ( get_target() == "" ) {                                     // computed goto
    283                 //              assert( get_control() != 0 );
    284                 //              return new BranchStmt( labs, maybeBuild<Expression>(get_control()), BranchStmt::Goto );
    285                 //      } // if
    286 
    287                 //      return new BranchStmt( labs, get_target(), BranchStmt::Goto );
    288                 // }
    289                 assert( false );
    290           case Break:
    291                 // return new BranchStmt( labs, get_target(), BranchStmt::Break );
    292                 assert( false );
    293           case Continue:
    294                 // return new BranchStmt( labs, get_target(), BranchStmt::Continue );
    295                 assert( false );
    296           case Return:
    297           case Throw :
    298                 // buildList( get_control(), exps );
    299                 // if ( exps.size() ==0 )
    300                 //      return new ReturnStmt( labs, 0, type == Throw );
    301                 // if ( exps.size() > 0 )
    302                 //      return new ReturnStmt( labs, exps.back(), type == Throw );
    303                 assert( false );
    304           case Try:
    305                 {
    306                         assert( branches.size() >= 0 );
    307                         CompoundStmt *tryBlock = dynamic_cast<CompoundStmt *>( branches.front());
    308                         branches.pop_front();
    309                         FinallyStmt *finallyBlock = 0;
    310                         if ( ( finallyBlock = dynamic_cast<FinallyStmt *>( branches.back())) ) {
    311                                 branches.pop_back();
    312                         } // if
    313                         return new TryStmt( labs, tryBlock, branches, finallyBlock );
    314                 }
    315           case Catch:
    316                 {
    317                         assert( branches.size() == 1 );
    318 
    319                         return new CatchStmt( labs, maybeBuild< Declaration >( decl ), branches.front(), isCatchRest );
    320                 }
    321           case Finally:
    322                 {
    323                         assert( branches.size() == 1 );
    324                         CompoundStmt *block = dynamic_cast<CompoundStmt *>( branches.front() );
    325                         assert( block != 0 );
    326 
    327                         return new FinallyStmt( labs, block );
    328                 }
    329           case Asm:
    330                 assert( false );
    331           default:
    332                 // shouldn't be here
    333                 return 0;
    334         } // switch
    335 }
    336 
    33770Statement *build_expr( ExpressionNode *ctl ) {
    338         Expression *e = maybeBuild< Expression >( ctl );
     71        Expression *e = maybeMoveBuild< Expression >( ctl );
    33972
    34073        if ( e )
     
    34679Statement *build_if( ExpressionNode *ctl, StatementNode *then_stmt, StatementNode *else_stmt ) {
    34780        Statement *thenb, *elseb = 0;
    348         std::list<Statement *> branches;
    349         buildList<Statement, StatementNode>( then_stmt, branches );
     81        std::list< Statement * > branches;
     82        buildMoveList< Statement, StatementNode >( then_stmt, branches );
    35083        assert( branches.size() == 1 );
    35184        thenb = branches.front();
    35285
    35386        if ( else_stmt ) {
    354                 std::list<Statement *> branches;
    355                 buildList<Statement, StatementNode>( else_stmt, branches );
     87                std::list< Statement * > branches;
     88                buildMoveList< Statement, StatementNode >( else_stmt, branches );
    35689                assert( branches.size() == 1 );
    35790                elseb = branches.front();
    35891        } // if
    359         return new IfStmt( noLabels, notZeroExpr( maybeBuild<Expression>(ctl) ), thenb, elseb );
     92        return new IfStmt( noLabels, notZeroExpr( maybeMoveBuild< Expression >(ctl) ), thenb, elseb );
    36093}
    36194
    36295Statement *build_switch( ExpressionNode *ctl, StatementNode *stmt ) {
    363         std::list<Statement *> branches;
    364         buildList<Statement, StatementNode>( stmt, branches );
     96        std::list< Statement * > branches;
     97        buildMoveList< Statement, StatementNode >( stmt, branches );
    36598        assert( branches.size() >= 0 );                                         // size == 0 for switch (...) {}, i.e., no declaration or statements
    366         return new SwitchStmt( noLabels, maybeBuild<Expression>(ctl), branches );
     99        return new SwitchStmt( noLabels, maybeMoveBuild< Expression >(ctl), branches );
    367100}
    368101Statement *build_case( ExpressionNode *ctl ) {
    369         std::list<Statement *> branches;
    370         return new CaseStmt( noLabels, maybeBuild<Expression>(ctl), branches );
     102        std::list< Statement * > branches;
     103        return new CaseStmt( noLabels, maybeMoveBuild< Expression >(ctl), branches );
    371104}
    372105Statement *build_default() {
    373         std::list<Statement *> branches;
     106        std::list< Statement * > branches;
    374107        return new CaseStmt( noLabels, nullptr, branches, true );
    375108}
    376109
    377110Statement *build_while( ExpressionNode *ctl, StatementNode *stmt, bool kind ) {
    378         std::list<Statement *> branches;
    379         buildList<Statement, StatementNode>( stmt, branches );
    380         assert( branches.size() == 1 );
    381         return new WhileStmt( noLabels, notZeroExpr( maybeBuild<Expression>(ctl) ), branches.front(), kind );
     111        std::list< Statement * > branches;
     112        buildMoveList< Statement, StatementNode >( stmt, branches );
     113        assert( branches.size() == 1 );
     114        return new WhileStmt( noLabels, notZeroExpr( maybeMoveBuild< Expression >(ctl) ), branches.front(), kind );
    382115}
    383116
    384117Statement *build_for( ForCtl *forctl, StatementNode *stmt ) {
    385         std::list<Statement *> branches;
    386         buildList<Statement, StatementNode>( stmt, branches );
    387         assert( branches.size() == 1 );
    388 
    389         std::list<Statement *> init;
     118        std::list< Statement * > branches;
     119        buildMoveList< Statement, StatementNode >( stmt, branches );
     120        assert( branches.size() == 1 );
     121
     122        std::list< Statement * > init;
    390123        if ( forctl->init != 0 ) {
    391                 buildList( forctl->init, init );
     124                buildMoveList( forctl->init, init );
    392125        } // if
    393126
    394127        Expression *cond = 0;
    395128        if ( forctl->condition != 0 )
    396                 cond = notZeroExpr( maybeBuild<Expression>(forctl->condition) );
     129                cond = notZeroExpr( maybeMoveBuild< Expression >(forctl->condition) );
    397130
    398131        Expression *incr = 0;
    399132        if ( forctl->change != 0 )
    400                 incr = maybeBuild<Expression>(forctl->change);
     133                incr = maybeMoveBuild< Expression >(forctl->change);
    401134
    402135        delete forctl;
     
    404137}
    405138
    406 Statement *build_branch( std::string identifier, BranchStmt::Type kind ) {
    407         return new BranchStmt( noLabels, identifier, kind );
     139Statement *build_branch( BranchStmt::Type kind ) {
     140        Statement * ret = new BranchStmt( noLabels, "", kind );
     141        return ret;
     142}
     143Statement *build_branch( std::string *identifier, BranchStmt::Type kind ) {
     144        Statement * ret = new BranchStmt( noLabels, *identifier, kind );
     145        delete identifier;                                                                      // allocated by lexer
     146        return ret;
    408147}
    409148Statement *build_computedgoto( ExpressionNode *ctl ) {
    410         return new BranchStmt( noLabels, maybeBuild<Expression>(ctl), BranchStmt::Goto );
     149        return new BranchStmt( noLabels, maybeMoveBuild< Expression >(ctl), BranchStmt::Goto );
    411150}
    412151
    413152Statement *build_return( ExpressionNode *ctl ) {
    414         std::list<Expression *> exps;
    415         buildList( ctl, exps );
     153        std::list< Expression * > exps;
     154        buildMoveList( ctl, exps );
    416155        return new ReturnStmt( noLabels, exps.size() > 0 ? exps.back() : nullptr );
    417156}
    418157Statement *build_throw( ExpressionNode *ctl ) {
    419         std::list<Expression *> exps;
    420         buildList( ctl, exps );
    421         return new ReturnStmt( noLabels, exps.size() > 0 ? exps.back() : nullptr, true );
    422 }
    423 
    424 
    425 CompoundStmtNode::CompoundStmtNode() : first( 0 ), last( 0 ) {}
    426 
    427 CompoundStmtNode::CompoundStmtNode( const string *name_ ) : StatementNode( name_ ), first( 0 ), last( 0 ) {}
    428 
    429 CompoundStmtNode::CompoundStmtNode( StatementNode *stmt ) : first( stmt ) {
    430         if ( first ) {
    431                 last = ( StatementNode *)( stmt->get_last());
    432         } else {
    433                 last = 0;
    434         } // if
    435 }
    436 
    437 CompoundStmtNode::~CompoundStmtNode() {
    438         delete first;
    439 }
    440 
    441 void CompoundStmtNode::add_statement( StatementNode *stmt ) {
    442         if ( stmt != 0 ) {
    443                 last->set_link( stmt );
    444                 last = ( StatementNode *)( stmt->get_link());
    445         } // if
    446 }
    447 
    448 void CompoundStmtNode::print( ostream &os, int indent ) const {
    449         if ( first ) {
    450                 first->printList( os, indent+2 );
    451         } // if
    452 }
    453 
    454 Statement *CompoundStmtNode::build() const {
    455         std::list<Label> labs;
    456         const std::list<std::string> &labels = get_labels();
    457 
    458         if ( ! labels.empty() ) {
    459                 std::back_insert_iterator< std::list<Label> > lab_it( labs );
    460                 copy( labels.begin(), labels.end(), lab_it );
    461         } // if
    462 
    463         CompoundStmt *cs = new CompoundStmt( labs );
    464         buildList( first, cs->get_kids() );
     158        std::list< Expression * > exps;
     159        buildMoveList( ctl, exps );
     160        assertf( exps.size() < 2, "This means we are leaking memory");
     161        return new ReturnStmt( noLabels, !exps.empty() ? exps.back() : nullptr, true );
     162}
     163
     164Statement *build_try( StatementNode *try_stmt, StatementNode *catch_stmt, StatementNode *finally_stmt ) {
     165        std::list< Statement * > branches;
     166        buildMoveList< Statement, StatementNode >( catch_stmt, branches );
     167        CompoundStmt *tryBlock = safe_dynamic_cast< CompoundStmt * >(maybeMoveBuild< Statement >(try_stmt));
     168        FinallyStmt *finallyBlock = dynamic_cast< FinallyStmt * >(maybeMoveBuild< Statement >(finally_stmt) );
     169        return new TryStmt( noLabels, tryBlock, branches, finallyBlock );
     170}
     171Statement *build_catch( DeclarationNode *decl, StatementNode *stmt, bool catchAny ) {
     172        std::list< Statement * > branches;
     173        buildMoveList< Statement, StatementNode >( stmt, branches );
     174        assert( branches.size() == 1 );
     175        return new CatchStmt( noLabels, maybeMoveBuild< Declaration >(decl), branches.front(), catchAny );
     176}
     177Statement *build_finally( StatementNode *stmt ) {
     178        std::list< Statement * > branches;
     179        buildMoveList< Statement, StatementNode >( stmt, branches );
     180        assert( branches.size() == 1 );
     181        return new FinallyStmt( noLabels, dynamic_cast< CompoundStmt * >( branches.front() ) );
     182}
     183
     184Statement *build_compound( StatementNode *first ) {
     185        CompoundStmt *cs = new CompoundStmt( noLabels );
     186        buildMoveList( first, cs->get_kids() );
    465187        return cs;
    466188}
    467189
    468 
    469 AsmStmtNode::AsmStmtNode( Type t, bool voltile, ConstantExpr *instruction, ExpressionNode *output, ExpressionNode *input, ExpressionNode *clobber, LabelNode *gotolabels ) :
    470         StatementNode( t ), voltile( voltile ), instruction( instruction ), output( output ), input( input ), clobber( clobber ) {
    471         if ( gotolabels ) {
    472                 this->gotolabels = gotolabels->get_labels();
    473                 delete gotolabels;
    474         } // if
    475 }
    476 
    477 AsmStmtNode::~AsmStmtNode() {
    478         delete output; delete input; delete clobber;
    479 }
    480 
    481 void AsmStmtNode::print( std::ostream &os, int indent ) const {
    482         StatementNode::print( os, indent );                                     // print statement labels
    483         os << string( indent + ParseNode::indent_by, ' ' ) << "volatile:" << voltile << endl;
    484         if ( instruction ) {
    485                 os << string( indent + ParseNode::indent_by, ' ' ) << "Instruction:" << endl;
    486 //              instruction->printList( os, indent + 2 * ParseNode::indent_by );
    487         } // if
    488         if ( output ) {
    489                 os << string( indent + ParseNode::indent_by, ' ' ) << "Output:" << endl;
    490                 output->printList( os, indent + 2 * ParseNode::indent_by );
    491         } // if
    492         if ( input ) {
    493                 os << string( indent + ParseNode::indent_by, ' ' ) << "Input:" << endl;
    494                 input->printList( os, indent + 2 * ParseNode::indent_by );
    495         } // if
    496         if ( clobber ) {
    497                 os << string( indent + ParseNode::indent_by, ' ' ) << "Clobber:" << endl;
    498 //              clobber->printList( os, indent + 2 * ParseNode::indent_by );
    499         } // if
    500         if ( ! gotolabels.empty() ) {
    501                 os << string( indent + ParseNode::indent_by, ' ' ) << "Goto Labels:" << endl;
    502                 os << string( indent + 2 * ParseNode::indent_by, ' ' );
    503                 for ( std::list<Label>::const_iterator i = gotolabels.begin();; ) {
    504                         os << *i;
    505                         i++;
    506                   if ( i == gotolabels.end() ) break;
    507                         os << ", ";
    508                 }
    509                 os << endl;
    510         } // if
    511 }
    512 
    513 Statement *AsmStmtNode::build() const {
    514         std::list<Label> labs;
    515 
    516         if ( ! get_labels().empty() ) {
    517                 std::back_insert_iterator< std::list<Label> > lab_it( labs );
    518                 copy( get_labels().begin(), get_labels().end(), lab_it );
    519         } // if
    520 
     190Statement *build_asmstmt( bool voltile, ConstantExpr *instruction, ExpressionNode *output, ExpressionNode *input, ExpressionNode *clobber, LabelNode *gotolabels ) {
    521191        std::list< Expression * > out, in;
    522192        std::list< ConstantExpr * > clob;
    523         buildList( output, out );
    524         buildList( input, in );
    525         buildList( clobber, clob );
    526         std::list< Label > gotolabs = gotolabels;
    527         return new AsmStmt( labs, voltile, instruction, out, in, clob, gotolabs );
     193
     194        buildMoveList( output, out );
     195        buildMoveList( input, in );
     196        buildMoveList( clobber, clob );
     197        return new AsmStmt( noLabels, voltile, instruction, out, in, clob, gotolabels ? gotolabels->labels : noLabels );
    528198}
    529199
  • src/Parser/TypeData.cc

    r79841be r6943a987  
    1010// Created On       : Sat May 16 15:12:51 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sun Aug  7 07:51:48 2016
    13 // Update Count     : 58
     12// Last Modified On : Sun Aug 28 18:28:58 2016
     13// Update Count     : 223
    1414//
    1515
     
    9494                break;
    9595        } // switch
    96 }
     96} // TypeData::TypeData
    9797
    9898TypeData::~TypeData() {
     
    163163                break;
    164164        } // switch
    165 }
    166 
    167 TypeData *TypeData::clone() const {
    168         TypeData *newtype = new TypeData( kind );
     165} // TypeData::~TypeData
     166
     167TypeData * TypeData::clone() const {
     168        TypeData * newtype = new TypeData( kind );
    169169        newtype->qualifiers = qualifiers;
    170170        newtype->base = maybeClone( base );
     
    182182                break;
    183183          case Array:
    184 //PAB           newtype->array->dimension = maybeClone( array->dimension );
    185                 newtype->array->dimension = array->dimension;
     184                newtype->array->dimension = maybeClone( array->dimension );
    186185                newtype->array->isVarLen = array->isVarLen;
    187186                newtype->array->isStatic = array->isStatic;
     
    239238        } // switch
    240239        return newtype;
    241 }
     240} // TypeData::clone
    242241
    243242void TypeData::print( std::ostream &os, int indent ) const {
     
    245244        using std::string;
    246245
    247         printEnums( qualifiers.begin(), qualifiers.end(), DeclarationNode::qualifierName, os );
     246        for ( int i = 0; i < DeclarationNode::NoOfQualifier; i += 1 ) {
     247                if ( qualifiers[i] ) os << DeclarationNode::qualifierName[ i ] << ' ';
     248        } // for
    248249
    249250        if ( forall ) {
     
    417418                assert( false );
    418419        } // switch
    419 }
    420 
    421 TypeData *TypeData::extractAggregate( bool toplevel ) const {
    422         TypeData *ret = 0;
    423 
    424         switch ( kind ) {
    425           case Aggregate:
    426                 if ( ! toplevel && aggregate->fields ) {
    427                         ret = clone();
    428                         ret->qualifiers.clear();
    429                 } // if
    430                 break;
    431           case Enum:
    432                 if ( ! toplevel && enumeration->constants ) {
    433                         ret = clone();
    434                         ret->qualifiers.clear();
    435                 } // if
    436                 break;
    437           case AggregateInst:
    438                 if ( aggInst->aggregate ) {
    439                         ret = aggInst->aggregate->extractAggregate( false );
    440                 } // if
    441                 break;
    442           default:
    443                 if ( base ) {
    444                         ret = base->extractAggregate( false );
    445                 } // if
    446         } // switch
    447         return ret;
    448 }
    449 
    450 void buildForall( const DeclarationNode *firstNode, std::list< TypeDecl* > &outputList ) {
     420} // TypeData::print
     421
     422void buildForall( const DeclarationNode * firstNode, std::list< TypeDecl* > &outputList ) {
    451423        buildList( firstNode, outputList );
    452424        for ( std::list< TypeDecl* >::iterator i = outputList.begin(); i != outputList.end(); ++i ) {
     
    454426                        // add assertion parameters to `type' tyvars in reverse order
    455427                        // add dtor:  void ^?{}(T *)
    456                         FunctionType *dtorType = new FunctionType( Type::Qualifiers(), false );
     428                        FunctionType * dtorType = new FunctionType( Type::Qualifiers(), false );
    457429                        dtorType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new TypeInstType( Type::Qualifiers(), (*i)->get_name(), *i ) ), 0 ) );
    458430                        (*i)->get_assertions().push_front( new FunctionDecl( "^?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, dtorType, 0, false, false ) );
    459431
    460432                        // add copy ctor:  void ?{}(T *, T)
    461                         FunctionType *copyCtorType = new FunctionType( Type::Qualifiers(), false );
     433                        FunctionType * copyCtorType = new FunctionType( Type::Qualifiers(), false );
    462434                        copyCtorType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new TypeInstType( Type::Qualifiers(), (*i)->get_name(), *i ) ), 0 ) );
    463435                        copyCtorType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new TypeInstType( Type::Qualifiers(), (*i)->get_name(), *i ), 0 ) );
     
    465437
    466438                        // add default ctor:  void ?{}(T *)
    467                         FunctionType *ctorType = new FunctionType( Type::Qualifiers(), false );
     439                        FunctionType * ctorType = new FunctionType( Type::Qualifiers(), false );
    468440                        ctorType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new TypeInstType( Type::Qualifiers(), (*i)->get_name(), *i ) ), 0 ) );
    469441                        (*i)->get_assertions().push_front( new FunctionDecl( "?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, ctorType, 0, false, false ) );
    470442
    471443                        // add assignment operator:  T * ?=?(T *, T)
    472                         FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
     444                        FunctionType * assignType = new FunctionType( Type::Qualifiers(), false );
    473445                        assignType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new TypeInstType( Type::Qualifiers(), (*i)->get_name(), *i ) ), 0 ) );
    474446                        assignType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new TypeInstType( Type::Qualifiers(), (*i)->get_name(), *i ), 0 ) );
     
    479451}
    480452
    481 Declaration *TypeData::buildDecl( std::string name, DeclarationNode::StorageClass sc, Expression *bitfieldWidth, bool isInline, bool isNoreturn, LinkageSpec::Type linkage, Initializer *init ) const {
    482         if ( kind == TypeData::Function ) {
    483                 FunctionDecl *decl;
    484                 if ( function->hasBody ) {
    485                         if ( function->body ) {
    486                                 Statement *stmt = function->body->build();
    487                                 CompoundStmt *body = dynamic_cast< CompoundStmt* >( stmt );
    488                                 assert( body );
    489                                 decl = new FunctionDecl( name, sc, linkage, buildFunction(), body, isInline, isNoreturn );
    490                         } else {
    491                                 // std::list<Label> ls;
    492                                 decl = new FunctionDecl( name, sc, linkage, buildFunction(), new CompoundStmt( std::list<Label>() ), isInline, isNoreturn );
    493                         } // if
    494                 } else {
    495                         decl = new FunctionDecl( name, sc, linkage, buildFunction(), 0, isInline, isNoreturn );
    496                 } // if
    497                 for ( DeclarationNode *cur = function->idList; cur != 0; cur = dynamic_cast< DeclarationNode* >( cur->get_link() ) ) {
    498                         if ( cur->get_name() != "" ) {
    499                                 decl->get_oldIdents().insert( decl->get_oldIdents().end(), cur->get_name() );
    500                         } // if
    501                 } // for
    502                 buildList( function->oldDeclList, decl->get_oldDecls() );
    503                 return decl;
    504         } else if ( kind == TypeData::Aggregate ) {
    505                 return buildAggregate();
    506         } else if ( kind == TypeData::Enum ) {
    507                 return buildEnum();
    508         } else if ( kind == TypeData::Symbolic ) {
    509                 return buildSymbolic( name, sc );
    510         } else if ( kind == TypeData::Variable ) {
    511                 return buildVariable();
    512         } else {
    513                 return new ObjectDecl( name, sc, linkage, bitfieldWidth, build(), init, std::list< Attribute * >(),  isInline, isNoreturn );
    514         } // if
    515         return 0;
    516 }
    517 
    518 Type *TypeData::build() const {
    519         switch ( kind ) {
    520           case Unknown:
     453Type * typebuild( const TypeData * td ) {
     454        assert( td );
     455        switch ( td->kind ) {
     456          case TypeData::Unknown:
    521457                // fill in implicit int
    522                 return new BasicType( buildQualifiers(), BasicType::SignedInt );
    523           case Basic:
    524                 return buildBasicType();
    525           case Pointer:
    526                 return buildPointer();
    527           case Array:
    528                 return buildArray();
    529           case Function:
    530                 return buildFunction();
    531           case AggregateInst:
    532                 return buildAggInst();
    533           case EnumConstant:
     458                return new BasicType( buildQualifiers( td ), BasicType::SignedInt );
     459          case TypeData::Basic:
     460                return buildBasicType( td );
     461          case TypeData::Pointer:
     462                return buildPointer( td );
     463          case TypeData::Array:
     464                return buildArray( td );
     465          case TypeData::Function:
     466                return buildFunction( td );
     467          case TypeData::AggregateInst:
     468                return buildAggInst( td );
     469          case TypeData::EnumConstant:
    534470                // the name gets filled in later -- by SymTab::Validate
    535                 return new EnumInstType( buildQualifiers(), "" );
    536           case SymbolicInst:
    537                 return buildSymbolicInst();;
    538           case Tuple:
    539                 return buildTuple();
    540           case Typeof:
    541                 return buildTypeof();
    542           case Builtin:
    543                 return new VarArgsType( buildQualifiers() );
    544           case Attr:
    545                 return buildAttr();
    546           case Symbolic:
    547           case Enum:
    548           case Aggregate:
    549           case Variable:
     471                return new EnumInstType( buildQualifiers( td ), "" );
     472          case TypeData::SymbolicInst:
     473                return buildSymbolicInst( td );;
     474          case TypeData::Tuple:
     475                return buildTuple( td );
     476          case TypeData::Typeof:
     477                return buildTypeof( td );
     478          case TypeData::Builtin:
     479                return new VarArgsType( buildQualifiers( td ) );
     480          case TypeData::Attr:
     481                return buildAttr( td );
     482          case TypeData::Symbolic:
     483          case TypeData::Enum:
     484          case TypeData::Aggregate:
     485          case TypeData::Variable:
    550486                assert( false );
    551487        } // switch
    552488        return 0;
    553 }
    554 
    555 Type::Qualifiers TypeData::buildQualifiers() const {
     489} // typebuild
     490
     491TypeData * typeextractAggregate( const TypeData * td, bool toplevel ) {
     492        TypeData * ret = 0;
     493
     494        switch ( td->kind ) {
     495          case TypeData::Aggregate:
     496                if ( ! toplevel && td->aggregate->fields ) {
     497                        ret = td->clone();
     498                } // if
     499                break;
     500          case TypeData::Enum:
     501                if ( ! toplevel && td->enumeration->constants ) {
     502                        ret = td->clone();
     503                } // if
     504                break;
     505          case TypeData::AggregateInst:
     506                if ( td->aggInst->aggregate ) {
     507                        ret = typeextractAggregate( td->aggInst->aggregate, false );
     508                } // if
     509                break;
     510          default:
     511                if ( td->base ) {
     512                        ret = typeextractAggregate( td->base, false );
     513                } // if
     514        } // switch
     515        return ret;
     516} // typeextractAggregate
     517
     518Type::Qualifiers buildQualifiers( const TypeData * td ) {
    556519        Type::Qualifiers q;
    557         for ( std::list< DeclarationNode::Qualifier >::const_iterator i = qualifiers.begin(); i != qualifiers.end(); ++i ) {
    558                 switch ( *i ) {
    559                   case DeclarationNode::Const:
    560                         q.isConst = true;
    561                         break;
    562                   case DeclarationNode::Volatile:
    563                         q.isVolatile = true;
    564                         break;
    565                   case DeclarationNode::Restrict:
    566                         q.isRestrict = true;
    567                         break;
    568                   case DeclarationNode::Lvalue:
    569                         q.isLvalue = true;
    570                         break;
    571                   case DeclarationNode::Atomic:
    572                         q.isAtomic = true;
    573                         break;
    574                 } // switch
    575         } // for
     520        q.isConst = td->qualifiers[ DeclarationNode::Const ];
     521        q.isVolatile = td->qualifiers[ DeclarationNode::Volatile ];
     522        q.isRestrict = td->qualifiers[ DeclarationNode::Restrict ];
     523        q.isLvalue = td->qualifiers[ DeclarationNode::Lvalue ];
     524        q.isAtomic = td->qualifiers[ DeclarationNode::Atomic ];;
    576525        return q;
    577 }
    578 
    579 Type *TypeData::buildBasicType() const {
     526} // buildQualifiers
     527
     528Type * buildBasicType( const TypeData * td ) {
    580529        static const BasicType::Kind kindMap[] = { BasicType::Char, BasicType::SignedInt, BasicType::Float, BasicType::Double,
    581530                                                                                           BasicType::Char /* void */, BasicType::Bool, BasicType::DoubleComplex,
     
    586535        BasicType::Kind ret;
    587536
    588         for ( std::list< DeclarationNode::BasicType >::const_iterator i = basic->typeSpec.begin(); i != basic->typeSpec.end(); ++i ) {
     537        for ( std::list< DeclarationNode::BasicType >::const_iterator i = td->basic->typeSpec.begin(); i != td->basic->typeSpec.end(); ++i ) {
    589538                if ( ! init ) {
    590539                        init = true;
    591540                        if ( *i == DeclarationNode::Void ) {
    592                                 if ( basic->typeSpec.size() != 1 || ! basic->modifiers.empty() ) {
    593                                         throw SemanticError( "invalid type specifier \"void\" in type: ", this );
     541                                if ( td->basic->typeSpec.size() != 1 || ! td->basic->modifiers.empty() ) {
     542                                        throw SemanticError( "invalid type specifier \"void\" in type: ", td );
    594543                                } else {
    595                                         return new VoidType( buildQualifiers() );
     544                                        return new VoidType( buildQualifiers( td ) );
    596545                                } // if
    597546                        } else {
     
    602551                          case DeclarationNode::Float:
    603552                                if ( sawDouble ) {
    604                                         throw SemanticError( "invalid type specifier \"float\" in type: ", this );
     553                                        throw SemanticError( "invalid type specifier \"float\" in type: ", td );
    605554                                } else {
    606555                                        switch ( ret ) {
     
    612561                                                break;
    613562                                          default:
    614                                                 throw SemanticError( "invalid type specifier \"float\" in type: ", this );
     563                                                throw SemanticError( "invalid type specifier \"float\" in type: ", td );
    615564                                        } // switch
    616565                                } // if
     
    618567                          case DeclarationNode::Double:
    619568                                if ( sawDouble ) {
    620                                         throw SemanticError( "duplicate type specifier \"double\" in type: ", this );
     569                                        throw SemanticError( "duplicate type specifier \"double\" in type: ", td );
    621570                                } else {
    622571                                        switch ( ret ) {
     
    625574                                                break;
    626575                                          default:
    627                                                 throw SemanticError( "invalid type specifier \"double\" in type: ", this );
     576                                                throw SemanticError( "invalid type specifier \"double\" in type: ", td );
    628577                                        } // switch
    629578                                } // if
     
    638587                                        break;
    639588                                  default:
    640                                         throw SemanticError( "invalid type specifier \"_Complex\" in type: ", this );
     589                                        throw SemanticError( "invalid type specifier \"_Complex\" in type: ", td );
    641590                                } // switch
    642591                                break;
     
    650599                                        break;
    651600                                  default:
    652                                         throw SemanticError( "invalid type specifier \"_Imaginary\" in type: ", this );
     601                                        throw SemanticError( "invalid type specifier \"_Imaginary\" in type: ", td );
    653602                                } // switch
    654603                                break;
    655604                          default:
    656                                 throw SemanticError( std::string( "invalid type specifier \"" ) + DeclarationNode::basicTypeName[ *i ] + "\" in type: ", this );
     605                                throw SemanticError( std::string( "invalid type specifier \"" ) + DeclarationNode::basicTypeName[ *i ] + "\" in type: ", td );
    657606                        } // switch
    658607                } // if
     
    662611        } // for
    663612
    664         for ( std::list< DeclarationNode::Modifier >::const_iterator i = basic->modifiers.begin(); i != basic->modifiers.end(); ++i ) {
     613        for ( std::list< DeclarationNode::Modifier >::const_iterator i = td->basic->modifiers.begin(); i != td->basic->modifiers.end(); ++i ) {
    665614                switch ( *i ) {
    666615                  case DeclarationNode::Long:
     
    692641                                        break;
    693642                                  default:
    694                                         throw SemanticError( "invalid type modifier \"long\" in type: ", this );
     643                                        throw SemanticError( "invalid type modifier \"long\" in type: ", td );
    695644                                } // switch
    696645                        } // if
     
    709658                                        break;
    710659                                  default:
    711                                         throw SemanticError( "invalid type modifier \"short\" in type: ", this );
     660                                        throw SemanticError( "invalid type modifier \"short\" in type: ", td );
    712661                                } // switch
    713662                        } // if
     
    718667                                ret = BasicType::SignedInt;
    719668                        } else if ( sawSigned ) {
    720                                 throw SemanticError( "duplicate type modifer \"signed\" in type: ", this );
     669                                throw SemanticError( "duplicate type modifer \"signed\" in type: ", td );
    721670                        } else {
    722671                                switch ( ret ) {
     
    734683                                        break;
    735684                                  default:
    736                                         throw SemanticError( "invalid type modifer \"signed\" in type: ", this );
     685                                        throw SemanticError( "invalid type modifer \"signed\" in type: ", td );
    737686                                } // switch
    738687                        } // if
     
    743692                                ret = BasicType::UnsignedInt;
    744693                        } else if ( sawSigned ) {
    745                                 throw SemanticError( "invalid type modifer \"unsigned\" in type: ", this );
     694                                throw SemanticError( "invalid type modifer \"unsigned\" in type: ", td );
    746695                        } else {
    747696                                switch ( ret ) {
     
    762711                                        break;
    763712                                  default:
    764                                         throw SemanticError( "invalid type modifer \"unsigned\" in type: ", this );
     713                                        throw SemanticError( "invalid type modifer \"unsigned\" in type: ", td );
    765714                                } // switch
    766715                        } // if
     
    773722        } // for
    774723
    775         BasicType *bt;
     724        BasicType * bt;
    776725        if ( ! init ) {
    777                 bt = new BasicType( buildQualifiers(), BasicType::SignedInt );
     726                bt = new BasicType( buildQualifiers( td ), BasicType::SignedInt );
    778727        } else {
    779                 bt = new BasicType( buildQualifiers(), ret );
     728                bt = new BasicType( buildQualifiers( td ), ret );
    780729        } // if
    781         buildForall( forall, bt->get_forall() );
     730        buildForall( td->forall, bt->get_forall() );
    782731        return bt;
    783 }
    784 
    785 
    786 PointerType *TypeData::buildPointer() const {
    787         PointerType *pt;
    788         if ( base ) {
    789                 pt = new PointerType( buildQualifiers(), base->build() );
     732} // buildBasicType
     733
     734PointerType * buildPointer( const TypeData * td ) {
     735        PointerType * pt;
     736        if ( td->base ) {
     737                pt = new PointerType( buildQualifiers( td ), typebuild( td->base ) );
    790738        } else {
    791                 pt = new PointerType( buildQualifiers(), new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
     739                pt = new PointerType( buildQualifiers( td ), new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
    792740        } // if
    793         buildForall( forall, pt->get_forall() );
     741        buildForall( td->forall, pt->get_forall() );
    794742        return pt;
    795 }
    796 
    797 ArrayType *TypeData::buildArray() const {
    798         ArrayType *at;
    799         if ( base ) {
    800                 at = new ArrayType( buildQualifiers(), base->build(), maybeBuild< Expression >( array->dimension ),
    801                                                         array->isVarLen, array->isStatic );
     743} // buildPointer
     744
     745ArrayType * buildArray( const TypeData * td ) {
     746        ArrayType * at;
     747        if ( td->base ) {
     748                at = new ArrayType( buildQualifiers( td ), typebuild( td->base ), maybeBuild< Expression >( td->array->dimension ),
     749                                                        td->array->isVarLen, td->array->isStatic );
    802750        } else {
    803                 at = new ArrayType( buildQualifiers(), new BasicType( Type::Qualifiers(), BasicType::SignedInt ),
    804                                                         maybeBuild< Expression >( array->dimension ), array->isVarLen, array->isStatic );
     751                at = new ArrayType( buildQualifiers( td ), new BasicType( Type::Qualifiers(), BasicType::SignedInt ),
     752                                                        maybeBuild< Expression >( td->array->dimension ), td->array->isVarLen, td->array->isStatic );
    805753        } // if
    806         buildForall( forall, at->get_forall() );
     754        buildForall( td->forall, at->get_forall() );
    807755        return at;
    808 }
    809 
    810 FunctionType *TypeData::buildFunction() const {
    811         assert( kind == Function );
    812         bool hasEllipsis = function->params ? function->params->get_hasEllipsis() : true;
    813         if ( ! function->params ) hasEllipsis = ! function->newStyle;
    814         FunctionType *ft = new FunctionType( buildQualifiers(), hasEllipsis );
    815         buildList( function->params, ft->get_parameters() );
    816         buildForall( forall, ft->get_forall() );
    817         if ( base ) {
    818                 switch ( base->kind ) {
    819                   case Tuple:
    820                         buildList( base->tuple->members, ft->get_returnVals() );
     756} // buildPointer
     757
     758AggregateDecl * buildAggregate( const TypeData * td ) {
     759        assert( td->kind == TypeData::Aggregate );
     760        AggregateDecl * at;
     761        switch ( td->aggregate->kind ) {
     762          case DeclarationNode::Struct:
     763                at = new StructDecl( td->aggregate->name );
     764                buildForall( td->aggregate->params, at->get_parameters() );
     765                break;
     766          case DeclarationNode::Union:
     767                at = new UnionDecl( td->aggregate->name );
     768                buildForall( td->aggregate->params, at->get_parameters() );
     769                break;
     770          case DeclarationNode::Trait:
     771                at = new TraitDecl( td->aggregate->name );
     772                buildList( td->aggregate->params, at->get_parameters() );
     773                break;
     774          default:
     775                assert( false );
     776        } // switch
     777
     778        buildList( td->aggregate->fields, at->get_members() );
     779        at-&