Changes in / [24d6572:62d62db]


Ignore:
Files:
2 deleted
52 edited

Legend:

Unmodified
Added
Removed
  • doc/papers/llheap/Paper.tex

    r24d6572 r62d62db  
    252252Dynamic code/data memory is managed by the dynamic loader for libraries loaded at runtime, which is complex especially in a multi-threaded program~\cite{Huang06}.
    253253However, changes to the dynamic code/data space are typically infrequent, many occurring at program startup, and are largely outside of a program's control.
    254 Stack memory is managed by the program call/return-mechanism using a simple LIFO technique, which works well for sequential programs.
    255 For stackful coroutines and user threads, a new stack is commonly created in dynamic-allocation memory.
     254Stack memory is managed by the program call/return-mechanism using a LIFO technique, which works well for sequential programs.
     255For stackful coroutines and user threads, a new stack is commonly created in the dynamic-allocation memory.
    256256This work focuses solely on management of the dynamic-allocation memory.
    257257
     
    293293\begin{enumerate}[leftmargin=*,itemsep=0pt]
    294294\item
    295 Implementation of a new stand-alone concurrent low-latency memory-allocator ($\approx$1,200 lines of code) for C/\CC programs using kernel threads (1:1 threading), and specialized versions of the allocator for the programming languages \uC and \CFA using user-level threads running on multiple kernel threads (M:N threading).
    296 
    297 \item
    298 Extend the standard C heap functionality by preserving with each allocation: its request size plus the amount allocated, whether an allocation is zero fill, and allocation alignment.
     295Implementation of a new stand-alone concurrent low-latency memory-allocator ($\approx$1,200 lines of code) for C/\CC programs using kernel threads (1:1 threading), and specialized versions of the allocator for the programming languages \uC~\cite{uC++} and \CFA~\cite{Moss18,Delisle21} using user-level threads running on multiple kernel threads (M:N threading).
     296
     297\item
     298Extend the standard C heap functionality by preserving with each allocation: its request size plus the amount allocated, whether an allocation is zero fill and/or allocation alignment.
    299299
    300300\item
     
    365365
    366366The following discussion is a quick overview of the moving-pieces that affect the design of a memory allocator and its performance.
    367 It is assumed that dynamic allocates and deallocates acquire storage for a program variable, referred to as an \newterm{object}, through calls such as @malloc@ and @free@ in C, and @new@ and @delete@ in \CC.
     367Dynamic acquires and releases obtain storage for a program variable, called an \newterm{object}, through calls such as @malloc@ and @free@ in C, and @new@ and @delete@ in \CC.
    368368Space for each allocated object comes from the dynamic-allocation zone.
    369369
     
    378378
    379379Figure~\ref{f:AllocatorComponents} shows the two important data components for a memory allocator, management and storage, collectively called the \newterm{heap}.
    380 The \newterm{management data} is a data structure located at a known memory address and contains all information necessary to manage the storage data.
    381 The management data starts with fixed-sized information in the static-data memory that references components in the dynamic-allocation memory.
     380The \newterm{management data} is a data structure located at a known memory address and contains fixed-sized information in the static-data memory that references components in the dynamic-allocation memory.
    382381For multi-threaded programs, additional management data may exist in \newterm{thread-local storage} (TLS) for each kernel thread executing the program.
    383382The \newterm{storage data} is composed of allocated and freed objects, and \newterm{reserved memory}.
     
    385384\ie only the program knows the location of allocated storage not the memory allocator.
    386385Freed objects (white) represent memory deallocated by the program, which are linked into one or more lists facilitating easy location of new allocations.
    387 Reserved memory (dark grey) is one or more blocks of memory obtained from the operating system but not yet allocated to the program;
    388 if there are multiple reserved blocks, they are also chained together, usually internally.
     386Reserved memory (dark grey) is one or more blocks of memory obtained from the \newterm{operating system} (OS) but not yet allocated to the program;
     387if there are multiple reserved blocks, they are also chained together.
    389388
    390389\begin{figure}
     
    395394\end{figure}
    396395
    397 In most allocator designs, allocated objects have management data embedded within them.
     396In many allocator designs, allocated objects and reserved blocks have management data embedded within them (see also Section~\ref{s:ObjectContainers}).
    398397Figure~\ref{f:AllocatedObject} shows an allocated object with a header, trailer, and optional spacing around the object.
    399398The header contains information about the object, \eg size, type, etc.
     
    404403When padding and spacing are necessary, neither can be used to satisfy a future allocation request while the current allocation exists.
    405404
    406 A free object also contains management data, \eg size, pointers, etc.
     405A free object often contains management data, \eg size, pointers, etc.
    407406Often the free list is chained internally so it does not consume additional storage, \ie the link fields are placed at known locations in the unused memory blocks.
    408407For internal chaining, the amount of management data for a free node defines the minimum allocation size, \eg if 16 bytes are needed for a free-list node, allocation requests less than 16 bytes are rounded up.
    409 The information in an allocated or freed object is overwritten when it transitions from allocated to freed and vice-versa by new management information and/or program data.
     408The information in an allocated or freed object is overwritten when it transitions from allocated to freed and vice-versa by new program data and/or management information.
    410409
    411410\begin{figure}
     
    428427\label{s:Fragmentation}
    429428
    430 Fragmentation is memory requested from the operating system but not used by the program;
     429Fragmentation is memory requested from the OS but not used by the program;
    431430hence, allocated objects are not fragmentation.
    432431Figure~\ref{f:InternalExternalFragmentation} shows fragmentation is divided into two forms: internal or external.
     
    443442An allocator should strive to keep internal management information to a minimum.
    444443
    445 \newterm{External fragmentation} is all memory space reserved from the operating system but not allocated to the program~\cite{Wilson95,Lim98,Siebert00}, which includes all external management data, freed objects, and reserved memory.
     444\newterm{External fragmentation} is all memory space reserved from the OS but not allocated to the program~\cite{Wilson95,Lim98,Siebert00}, which includes all external management data, freed objects, and reserved memory.
    446445This memory is problematic in two ways: heap blowup and highly fragmented memory.
    447446\newterm{Heap blowup} occurs when freed memory cannot be reused for future allocations leading to potentially unbounded external fragmentation growth~\cite{Berger00}.
    448 Memory can become \newterm{highly fragmented} after multiple allocations and deallocations of objects, resulting in a checkerboard of adjacent allocated and free areas, where the free blocks have become very small.
     447Memory can become \newterm{highly fragmented} after multiple allocations and deallocations of objects, resulting in a checkerboard of adjacent allocated and free areas, where the free blocks have become to small to service requests.
    449448% Figure~\ref{f:MemoryFragmentation} shows an example of how a small block of memory fragments as objects are allocated and deallocated over time.
    450449Heap blowup can occur due to allocator policies that are too restrictive in reusing freed memory (the allocated size cannot use a larger free block) and/or no coalescing of free storage.
     
    452451% Memory is highly fragmented when most free blocks are unusable because of their sizes.
    453452% For example, Figure~\ref{f:Contiguous} and Figure~\ref{f:HighlyFragmented} have the same quantity of external fragmentation, but Figure~\ref{f:HighlyFragmented} is highly fragmented.
    454 % If there is a request to allocate a large object, Figure~\ref{f:Contiguous} is more likely to be able to satisfy it with existing free memory, while Figure~\ref{f:HighlyFragmented} likely has to request more memory from the operating system.
     453% If there is a request to allocate a large object, Figure~\ref{f:Contiguous} is more likely to be able to satisfy it with existing free memory, while Figure~\ref{f:HighlyFragmented} likely has to request more memory from the OS.
    455454
    456455% \begin{figure}
     
    475474The first approach is a \newterm{sequential-fit algorithm} with one list of free objects that is searched for a block large enough to fit a requested object size.
    476475Different search policies determine the free object selected, \eg the first free object large enough or closest to the requested size.
    477 Any storage larger than the request can become spacing after the object or be split into a smaller free object.
     476Any storage larger than the request can become spacing after the object or split into a smaller free object.
    478477% The cost of the search depends on the shape and quality of the free list, \eg a linear versus a binary-tree free-list, a sorted versus unsorted free-list.
    479478
     
    489488
    490489The third approach is \newterm{splitting} and \newterm{coalescing algorithms}.
    491 When an object is allocated, if there are no free objects of the requested size, a larger free object may be split into two smaller objects to satisfy the allocation request without obtaining more memory from the operating system.
    492 For example, in the \newterm{buddy system}, a block of free memory is split into two equal chunks, one of those chunks is again split into two equal chunks, and so on until a block just large enough to fit the requested object is created.
    493 When an object is deallocated it is coalesced with the objects immediately before and after it in memory, if they are free, turning them into one larger object.
     490When an object is allocated, if there are no free objects of the requested size, a larger free object is split into two smaller objects to satisfy the allocation request rather than obtaining more memory from the OS.
     491For example, in the \newterm{buddy system}, a block of free memory is split into equal chunks, one of those chunks is again split, and so on until a minimal block is created that fits the requested object.
     492When an object is deallocated, it is coalesced with the objects immediately before and after it in memory, if they are free, turning them into one larger block.
    494493Coalescing can be done eagerly at each deallocation or lazily when an allocation cannot be fulfilled.
    495 In all cases, coalescing increases allocation latency, hence some allocations can cause unbounded delays during coalescing.
     494In all cases, coalescing increases allocation latency, hence some allocations can cause unbounded delays.
    496495While coalescing does not reduce external fragmentation, the coalesced blocks improve fragmentation quality so future allocations are less likely to cause heap blowup.
    497496% Splitting and coalescing can be used with other algorithms to avoid highly fragmented memory.
     
    501500\label{s:Locality}
    502501
    503 The principle of locality recognizes that programs tend to reference a small set of data, called a working set, for a certain period of time, where a working set is composed of temporal and spatial accesses~\cite{Denning05}.
     502The principle of locality recognizes that programs tend to reference a small set of data, called a \newterm{working set}, for a certain period of time, composed of temporal and spatial accesses~\cite{Denning05}.
    504503% Temporal clustering implies a group of objects are accessed repeatedly within a short time period, while spatial clustering implies a group of objects physically close together (nearby addresses) are accessed repeatedly within a short time period.
    505504% Temporal locality commonly occurs during an iterative computation with a fixed set of disjoint variables, while spatial locality commonly occurs when traversing an array.
    506 Hardware takes advantage of temporal and spatial locality through multiple levels of caching, \ie memory hierarchy.
     505Hardware takes advantage of the working set through multiple levels of caching, \ie memory hierarchy.
    507506% When an object is accessed, the memory physically located around the object is also cached with the expectation that the current and nearby objects will be referenced within a short period of time.
    508 For example, entire cache lines are transferred between memory and cache and entire virtual-memory pages are transferred between disk and memory.
     507For example, entire cache lines are transferred between cache and memory, and entire virtual-memory pages are transferred between memory and disk.
    509508% A program exhibiting good locality has better performance due to fewer cache misses and page faults\footnote{With the advent of large RAM memory, paging is becoming less of an issue in modern programming.}.
    510509
     
    532531\label{s:MutualExclusion}
    533532
    534 \newterm{Mutual exclusion} provides sequential access to the shared management data of the heap.
     533\newterm{Mutual exclusion} provides sequential access to the shared-management data of the heap.
    535534There are two performance issues for mutual exclusion.
    536535First is the overhead necessary to perform (at least) a hardware atomic operation every time a shared resource is accessed.
    537536Second is when multiple threads contend for a shared resource simultaneously, and hence, some threads must wait until the resource is released.
    538537Contention can be reduced in a number of ways:
    539 1) Using multiple fine-grained locks versus a single lock, spreading the contention across a number of locks.
     5381) Using multiple fine-grained locks versus a single lock to spread the contention across a number of locks.
    5405392) Using trylock and generating new storage if the lock is busy, yielding a classic space versus time tradeoff.
    5415403) Using one of the many lock-free approaches for reducing contention on basic data-structure operations~\cite{Oyama99}.
     
    551550a memory allocator can only affect the latter two.
    552551
    553 Assume two objects, object$_1$ and object$_2$, share a cache line.
    554 \newterm{Program-induced false-sharing} occurs when thread$_1$ passes a reference to object$_2$ to thread$_2$, and then threads$_1$ modifies object$_1$ while thread$_2$ modifies object$_2$.
     552Specifically, assume two objects, O$_1$ and O$_2$, share a cache line, with threads, T$_1$ and T$_2$.
     553\newterm{Program-induced false-sharing} occurs when T$_1$ passes a reference to O$_2$ to T$_2$, and then T$_1$ modifies O$_1$ while T$_2$ modifies O$_2$.
    555554% Figure~\ref{f:ProgramInducedFalseSharing} shows when Thread$_1$ passes Object$_2$ to Thread$_2$, a false-sharing situation forms when Thread$_1$ modifies Object$_1$ and Thread$_2$ modifies Object$_2$.
    556555% Changes to Object$_1$ invalidate CPU$_2$'s cache line, and changes to Object$_2$ invalidate CPU$_1$'s cache line.
     
    574573% \label{f:FalseSharing}
    575574% \end{figure}
    576 \newterm{Allocator-induced active false-sharing}\label{s:AllocatorInducedActiveFalseSharing} occurs when object$_1$ and object$_2$ are heap allocated and their references are passed to thread$_1$ and thread$_2$, which modify the objects.
     575\newterm{Allocator-induced active false-sharing}\label{s:AllocatorInducedActiveFalseSharing} occurs when O$_1$ and O$_2$ are heap allocated and their references are passed to T$_1$ and T$_2$, which modify the objects.
    577576% For example, in Figure~\ref{f:AllocatorInducedActiveFalseSharing}, each thread allocates an object and loads a cache-line of memory into its associated cache.
    578577% Again, changes to Object$_1$ invalidate CPU$_2$'s cache line, and changes to Object$_2$ invalidate CPU$_1$'s cache line.
     
    580579% is another form of allocator-induced false-sharing caused by program-induced false-sharing.
    581580% When an object in a program-induced false-sharing situation is deallocated, a future allocation of that object may cause passive false-sharing.
    582 when thread$_1$ passes object$_2$ to thread$_2$, and thread$_2$ subsequently deallocates object$_2$, and then object$_2$ is reallocated to thread$_2$ while thread$_1$ is still using object$_1$.
     581when T$_1$ passes O$_2$ to T$_2$, and T$_2$ subsequently deallocates O$_2$, and then O$_2$ is reallocated to T$_2$ while T$_1$ is still using O$_1$.
    583582
    584583
     
    593592\label{s:MultiThreadedMemoryAllocatorFeatures}
    594593
    595 The following features are used in the construction of multi-threaded memory-allocators:
    596 \begin{enumerate}[itemsep=0pt]
    597 \item multiple heaps: with or without a global heap, or with or without heap ownership.
    598 \item object containers: with or without ownership, fixed or variable sized, global or local free-lists.
    599 \item hybrid private/public heap
    600 \item allocation buffer
    601 \item lock-free operations
    602 \end{enumerate}
     594The following features are used in the construction of multi-threaded memory-allocators: multiple heaps, user-level threading, ownership, object containers, allocation buffer, lock-free operations.
    603595The first feature, multiple heaps, pertains to different kinds of heaps.
    604596The second feature, object containers, pertains to the organization of objects within the storage area.
     
    606598
    607599
    608 \subsection{Multiple Heaps}
     600\subsubsection{Multiple Heaps}
    609601\label{s:MultipleHeaps}
    610602
    611603A multi-threaded allocator has potentially multiple threads and heaps.
    612604The multiple threads cause complexity, and multiple heaps are a mechanism for dealing with the complexity.
    613 The spectrum ranges from multiple threads using a single heap, denoted as T:1 (see Figure~\ref{f:SingleHeap}), to multiple threads sharing multiple heaps, denoted as T:H (see Figure~\ref{f:SharedHeaps}), to one thread per heap, denoted as 1:1 (see Figure~\ref{f:PerThreadHeap}), which is almost back to a single-threaded allocator.
     605The spectrum ranges from multiple threads using a single heap, denoted as T:1, to multiple threads sharing multiple heaps, denoted as T:H, to one thread per heap, denoted as 1:1, which is almost back to a single-threaded allocator.
    614606
    615607\begin{figure}
     
    635627\end{figure}
    636628
    637 \paragraph{T:1 model} where all threads allocate and deallocate objects from one heap.
    638 Memory is obtained from the freed objects, or reserved memory in the heap, or from the operating system (OS);
    639 the heap may also return freed memory to the operating system.
     629\paragraph{T:1 model (see Figure~\ref{f:SingleHeap})} where all threads allocate and deallocate objects from one heap.
     630Memory is obtained from the freed objects, or reserved memory in the heap, or from the OS;
     631the heap may also return freed memory to the OS.
    640632The arrows indicate the direction memory conceptually moves for each kind of operation: allocation moves memory along the path from the heap/operating-system to the user application, while deallocation moves memory along the path from the application back to the heap/operating-system.
    641633To safely handle concurrency, a single lock may be used for all heap operations or fine-grained locking for different operations.
    642634Regardless, a single heap may be a significant source of contention for programs with a large amount of memory allocation.
    643635
    644 \paragraph{T:H model} where each thread allocates storage from several heaps depending on certain criteria, with the goal of reducing contention by spreading allocations/deallocations across the heaps.
     636\paragraph{T:H model (see Figure~\ref{f:SharedHeaps})} where each thread allocates storage from several heaps depending on certain criteria, with the goal of reducing contention by spreading allocations/deallocations across the heaps.
    645637The decision on when to create a new heap and which heap a thread allocates from depends on the allocator design.
    646638To determine which heap to access, each thread must point to its associated heap in some way.
     
    673665An alternative implementation is for all heaps to share one reserved memory, which requires a separate lock for the reserved storage to ensure mutual exclusion when acquiring new memory.
    674666Because multiple threads can allocate/free/reallocate adjacent storage, all forms of false sharing may occur.
    675 Other storage-management options are to use @mmap@ to set aside (large) areas of virtual memory for each heap and suballocate each heap's storage within that area, pushing part of the storage management complexity back to the operating system.
     667Other storage-management options are to use @mmap@ to set aside (large) areas of virtual memory for each heap and suballocate each heap's storage within that area, pushing part of the storage management complexity back to the OS.
    676668
    677669% \begin{figure}
     
    684676Multiple heaps increase external fragmentation as the ratio of heaps to threads increases, which can lead to heap blowup.
    685677The external fragmentation experienced by a program with a single heap is now multiplied by the number of heaps, since each heap manages its own free storage and allocates its own reserved memory.
    686 Additionally, objects freed by one heap cannot be reused by other threads without increasing the cost of the memory operations, except indirectly by returning free memory to the operating system, which can be expensive.
    687 Depending on how the operating system provides dynamic storage to an application, returning storage may be difficult or impossible, \eg the contiguous @sbrk@ area in Unix.
    688 In the worst case, a program in which objects are allocated from one heap but deallocated to another heap means these freed objects are never reused.
     678Additionally, objects freed by one heap cannot be reused by other threads without increasing the cost of the memory operations, except indirectly by returning free memory to the OS (see Section~\ref{s:Ownership}).
     679Returning storage to the OS may be difficult or impossible, \eg the contiguous @sbrk@ area in Unix.
     680% In the worst case, a program in which objects are allocated from one heap but deallocated to another heap means these freed objects are never reused.
    689681
    690682Adding a \newterm{global heap} (G) attempts to reduce the cost of obtaining/returning memory among heaps (sharing) by buffering storage within the application address-space.
    691 Now, each heap obtains and returns storage to/from the global heap rather than the operating system.
     683Now, each heap obtains and returns storage to/from the global heap rather than the OS.
    692684Storage is obtained from the global heap only when a heap allocation cannot be fulfilled, and returned to the global heap when a heap's free memory exceeds some threshold.
    693 Similarly, the global heap buffers this memory, obtaining and returning storage to/from the operating system as necessary.
     685Similarly, the global heap buffers this memory, obtaining and returning storage to/from the OS as necessary.
    694686The global heap does not have its own thread and makes no internal allocation requests;
    695687instead, it uses the application thread, which called one of the multiple heaps and then the global heap, to perform operations.
    696688Hence, the worst-case cost of a memory operation includes all these steps.
    697 With respect to heap blowup, the global heap provides an indirect mechanism to move free memory among heaps, which usually has a much lower cost than interacting with the operating system to achieve the same goal and is independent of the mechanism used by the operating system to present dynamic memory to an address space.
    698 
     689With respect to heap blowup, the global heap provides an indirect mechanism to move free memory among heaps, which usually has a much lower cost than interacting with the OS to achieve the same goal and is independent of the mechanism used by the OS to present dynamic memory to an address space.
    699690However, since any thread may indirectly perform a memory operation on the global heap, it is a shared resource that requires locking.
    700691A single lock can be used to protect the global heap or fine-grained locking can be used to reduce contention.
    701692In general, the cost is minimal since the majority of memory operations are completed without the use of the global heap.
    702693
    703 
    704 \paragraph{1:1 model (thread heaps)} where each thread has its own heap eliminating most contention and locking because threads seldom access another thread's heap (see ownership in Section~\ref{s:Ownership}).
     694\paragraph{1:1 model (see Figure~\ref{f:PerThreadHeap})} where each thread has its own heap eliminating most contention and locking because threads seldom access another thread's heap (see Section~\ref{s:Ownership}).
    705695An additional benefit of thread heaps is improved locality due to better memory layout.
    706696As each thread only allocates from its heap, all objects are consolidated in the storage area for that heap, better utilizing each CPUs cache and accessing fewer pages.
     
    708698Thread heaps can also eliminate allocator-induced active false-sharing, if memory is acquired so it does not overlap at crucial boundaries with memory for another thread's heap.
    709699For example, assume page boundaries coincide with cache line boundaries, if a thread heap always acquires pages of memory then no two threads share a page or cache line unless pointers are passed among them.
    710 Hence, allocator-induced active false-sharing cannot occur because the memory for thread heaps never overlaps.
     700% Hence, allocator-induced active false-sharing cannot occur because the memory for thread heaps never overlaps.
    711701
    712702When a thread terminates, there are two options for handling its thread heap.
     
    720710
    721711It is possible to use any of the heap models with user-level (M:N) threading.
    722 However, an important goal of user-level threading is for fast operations (creation/termination/context-switching) by not interacting with the operating system, which allows the ability to create large numbers of high-performance interacting threads ($>$ 10,000).
     712However, an important goal of user-level threading is for fast operations (creation/termination/context-switching) by not interacting with the OS, which allows the ability to create large numbers of high-performance interacting threads ($>$ 10,000).
    723713It is difficult to retain this goal, if the user-threading model is directly involved with the heap model.
    724714Figure~\ref{f:UserLevelKernelHeaps} shows that virtually all user-level threading systems use whatever kernel-level heap-model is provided by the language runtime.
     
    732722\end{figure}
    733723
    734 Adopting this model results in a subtle problem with shared heaps.
    735 With kernel threading, an operation that is started by a kernel thread is always completed by that thread.
    736 For example, if a kernel thread starts an allocation/deallocation on a shared heap, it always completes that operation with that heap even if preempted, \ie any locking correctness associated with the shared heap is preserved across preemption.
     724Adopting user threading results in a subtle problem with shared heaps.
     725With kernel threading, an operation started by a kernel thread is always completed by that thread.
     726For example, if a kernel thread starts an allocation/deallocation on a shared heap, it always completes that operation with that heap, even if preempted, \ie any locking correctness associated with the shared heap is preserved across preemption.
    737727However, this correctness property is not preserved for user-level threading.
    738728A user thread can start an allocation/deallocation on one kernel thread, be preempted (time slice), and continue running on a different kernel thread to complete the operation~\cite{Dice02}.
    739729When the user thread continues on the new kernel thread, it may have pointers into the previous kernel-thread's heap and hold locks associated with it.
    740730To get the same kernel-thread safety, time slicing must be disabled/\-enabled around these operations, so the user thread cannot jump to another kernel thread.
    741 However, eagerly disabling/enabling time-slicing on the allocation/deallocation fast path is expensive, because preemption does not happen that frequently.
     731However, eagerly disabling/enabling time-slicing on the allocation/deallocation fast path is expensive, because preemption is infrequent (milliseconds).
    742732Instead, techniques exist to lazily detect this case in the interrupt handler, abort the preemption, and return to the operation so it can complete atomically.
    743 Occasionally ignoring a preemption should be benign, but a persistent lack of preemption can result in both short and long term starvation;
    744 techniques like rollforward can be used to force an eventual preemption.
     733Occasional ignoring of a preemption should be benign, but a persistent lack of preemption can result in starvation;
     734techniques like rolling forward the preemption to the next context switch can be used.
    745735
    746736
     
    800790% For example, in Figure~\ref{f:AllocatorInducedPassiveFalseSharing}, Object$_2$ may be deallocated to Thread$_2$'s heap initially.
    801791% If Thread$_2$ reallocates Object$_2$ before it is returned to its owner heap, then passive false-sharing may occur.
     792
     793For thread heaps with ownership, it is possible to combine these approaches into a hybrid approach with both private and public heaps.% (see~Figure~\ref{f:HybridPrivatePublicHeap}).
     794The main goal of the hybrid approach is to eliminate locking on thread-local allocation/deallocation, while providing ownership to prevent heap blowup.
     795In the hybrid approach, a thread first allocates from its private heap and second from its public heap if no free memory exists in the private heap.
     796Similarly, a thread first deallocates an object to its private heap, and second to the public heap.
     797Both private and public heaps can allocate/deallocate to/from the global heap if there is no free memory or excess free memory, although an implementation may choose to funnel all interaction with the global heap through one of the heaps.
     798% Note, deallocation from the private to the public (dashed line) is unlikely because there is no obvious advantages unless the public heap provides the only interface to the global heap.
     799Finally, when a thread frees an object it does not own, the object is either freed immediately to its owner's public heap or put in the freeing thread's private heap for delayed ownership, which does allows the freeing thread to temporarily reuse an object before returning it to its owner or batch objects for an owner heap into a single return.
     800
     801% \begin{figure}
     802% \centering
     803% \input{PrivatePublicHeaps.pstex_t}
     804% \caption{Hybrid Private/Public Heap for Per-thread Heaps}
     805% \label{f:HybridPrivatePublicHeap}
     806% \vspace{10pt}
     807% \input{RemoteFreeList.pstex_t}
     808% \caption{Remote Free-List}
     809% \label{f:RemoteFreeList}
     810% \end{figure}
     811
     812% As mentioned, an implementation may have only one heap interact with the global heap, so the other heap can be simplified.
     813% For example, if only the private heap interacts with the global heap, the public heap can be reduced to a lock-protected free-list of objects deallocated by other threads due to ownership, called a \newterm{remote free-list}.
     814% To avoid heap blowup, the private heap allocates from the remote free-list when it reaches some threshold or it has no free storage.
     815% Since the remote free-list is occasionally cleared during an allocation, this adds to that cost.
     816% Clearing the remote free-list is $O(1)$ if the list can simply be added to the end of the private-heap's free-list, or $O(N)$ if some action must be performed for each freed object.
     817 
     818% If only the public heap interacts with other threads and the global heap, the private heap can handle thread-local allocations and deallocations without locking.
     819% In this scenario, the private heap must deallocate storage after reaching a certain threshold to the public heap (and then eventually to the global heap from the public heap) or heap blowup can occur.
     820% If the public heap does the major management, the private heap can be simplified to provide high-performance thread-local allocations and deallocations.
     821 
     822% The main disadvantage of each thread having both a private and public heap is the complexity of managing two heaps and their interactions in an allocator.
     823% Interestingly, heap implementations often focus on either a private or public heap, giving the impression a single versus a hybrid approach is being used.
     824% In many case, the hybrid approach is actually being used, but the simpler heap is just folded into the complex heap, even though the operations logically belong in separate heaps.
     825% For example, a remote free-list is actually a simple public-heap, but may be implemented as an integral component of the complex private-heap in an allocator, masking the presence of a hybrid approach.
    802826
    803827
     
    817841
    818842
    819 \subsection{Object Containers}
     843\subsubsection{Object Containers}
    820844\label{s:ObjectContainers}
    821845
     
    827851\eg an object is accessed by the program after it is allocated, while the header is accessed by the allocator after it is free.
    828852
    829 The alternative factors common header data to a separate location in memory and organizes associated free storage into blocks called \newterm{object containers} (\newterm{superblocks} in~\cite{Berger00}), as in Figure~\ref{f:ObjectContainer}.
     853An alternative approach factors common header data to a separate location in memory and organizes associated free storage into blocks called \newterm{object containers} (\newterm{superblocks}~\cite{Berger00}), as in Figure~\ref{f:ObjectContainer}.
    830854The header for the container holds information necessary for all objects in the container;
    831855a trailer may also be used at the end of the container.
     
    862886
    863887
    864 \subsubsection{Container Ownership}
     888\paragraph{Container Ownership}
    865889\label{s:ContainerOwnership}
    866890
     
    894918
    895919Additional restrictions may be applied to the movement of containers to prevent active false-sharing.
    896 For example, if a container changes ownership through the global heap, then when a thread allocates an object from the newly acquired container it is actively false-sharing even though no objects are passed among threads.
     920For example, if a container changes ownership through the global heap, then a thread allocating from the newly acquired container is actively false-sharing even though no objects are passed among threads.
    897921Note, once the thread frees the object, no more false sharing can occur until the container changes ownership again.
    898922To prevent this form of false sharing, container movement may be restricted to when all objects in the container are free.
    899 One implementation approach that increases the freedom to return a free container to the operating system involves allocating containers using a call like @mmap@, which allows memory at an arbitrary address to be returned versus only storage at the end of the contiguous @sbrk@ area, again pushing storage management complexity back to the operating system.
     923One implementation approach that increases the freedom to return a free container to the OS involves allocating containers using a call like @mmap@, which allows memory at an arbitrary address to be returned versus only storage at the end of the contiguous @sbrk@ area, again pushing storage management complexity back to the OS.
    900924
    901925% \begin{figure}
     
    930954
    931955
    932 \subsubsection{Container Size}
     956\paragraph{Container Size}
    933957\label{s:ContainerSize}
    934958
     
    941965However, with more objects in a container, there may be more objects that are unallocated, increasing external fragmentation.
    942966With smaller containers, not only are there more containers, but a second new problem arises where objects are larger than the container.
    943 In general, large objects, \eg greater than 64\,KB, are allocated directly from the operating system and are returned immediately to the operating system to reduce long-term external fragmentation.
     967In general, large objects, \eg greater than 64\,KB, are allocated directly from the OS and are returned immediately to the OS to reduce long-term external fragmentation.
    944968If the container size is small, \eg 1\,KB, then a 1.5\,KB object is treated as a large object, which is likely to be inappropriate.
    945969Ideally, it is best to use smaller containers for smaller objects, and larger containers for medium objects, which leads to the issue of locating the container header.
     
    970994
    971995
    972 \subsubsection{Container Free-Lists}
     996\paragraph{Container Free-Lists}
    973997\label{s:containersfreelists}
    974998
     
    10051029
    10061030
    1007 \subsubsection{Hybrid Private/Public Heap}
    1008 \label{s:HybridPrivatePublicHeap}
    1009 
    1010 Section~\ref{s:Ownership} discusses advantages and disadvantages of public heaps (T:H model and with ownership) and private heaps (thread heaps with ownership).
    1011 For thread heaps with ownership, it is possible to combine these approaches into a hybrid approach with both private and public heaps (see~Figure~\ref{f:HybridPrivatePublicHeap}).
    1012 The main goal of the hybrid approach is to eliminate locking on thread-local allocation/deallocation, while providing ownership to prevent heap blowup.
    1013 In the hybrid approach, a thread first allocates from its private heap and second from its public heap if no free memory exists in the private heap.
    1014 Similarly, a thread first deallocates an object to its private heap, and second to the public heap.
    1015 Both private and public heaps can allocate/deallocate to/from the global heap if there is no free memory or excess free memory, although an implementation may choose to funnel all interaction with the global heap through one of the heaps.
    1016 Note, deallocation from the private to the public (dashed line) is unlikely because there is no obvious advantages unless the public heap provides the only interface to the global heap.
    1017 Finally, when a thread frees an object it does not own, the object is either freed immediately to its owner's public heap or put in the freeing thread's private heap for delayed ownership, which allows the freeing thread to temporarily reuse an object before returning it to its owner or batch objects for an owner heap into a single return.
    1018 
    1019 \begin{figure}
    1020 \centering
    1021 \input{PrivatePublicHeaps.pstex_t}
    1022 \caption{Hybrid Private/Public Heap for Per-thread Heaps}
    1023 \label{f:HybridPrivatePublicHeap}
    1024 % \vspace{10pt}
    1025 % \input{RemoteFreeList.pstex_t}
    1026 % \caption{Remote Free-List}
    1027 % \label{f:RemoteFreeList}
    1028 \end{figure}
    1029 
    1030 As mentioned, an implementation may have only one heap interact with the global heap, so the other heap can be simplified.
    1031 For example, if only the private heap interacts with the global heap, the public heap can be reduced to a lock-protected free-list of objects deallocated by other threads due to ownership, called a \newterm{remote free-list}.
    1032 To avoid heap blowup, the private heap allocates from the remote free-list when it reaches some threshold or it has no free storage.
    1033 Since the remote free-list is occasionally cleared during an allocation, this adds to that cost.
    1034 Clearing the remote free-list is $O(1)$ if the list can simply be added to the end of the private-heap's free-list, or $O(N)$ if some action must be performed for each freed object.
    1035 
    1036 If only the public heap interacts with other threads and the global heap, the private heap can handle thread-local allocations and deallocations without locking.
    1037 In this scenario, the private heap must deallocate storage after reaching a certain threshold to the public heap (and then eventually to the global heap from the public heap) or heap blowup can occur.
    1038 If the public heap does the major management, the private heap can be simplified to provide high-performance thread-local allocations and deallocations.
    1039 
    1040 The main disadvantage of each thread having both a private and public heap is the complexity of managing two heaps and their interactions in an allocator.
    1041 Interestingly, heap implementations often focus on either a private or public heap, giving the impression a single versus a hybrid approach is being used.
    1042 In many case, the hybrid approach is actually being used, but the simpler heap is just folded into the complex heap, even though the operations logically belong in separate heaps.
    1043 For example, a remote free-list is actually a simple public-heap, but may be implemented as an integral component of the complex private-heap in an allocator, masking the presence of a hybrid approach.
    1044 
    1045 
    1046 \subsection{Allocation Buffer}
     1031\subsubsection{Allocation Buffer}
    10471032\label{s:AllocationBuffer}
    10481033
    10491034An allocation buffer is reserved memory (see Section~\ref{s:AllocatorComponents}) not yet allocated to the program, and is used for allocating objects when the free list is empty.
    10501035That is, rather than requesting new storage for a single object, an entire buffer is requested from which multiple objects are allocated later.
    1051 Any heap may use an allocation buffer, resulting in allocation from the buffer before requesting objects (containers) from the global heap or operating system, respectively.
     1036Any heap may use an allocation buffer, resulting in allocation from the buffer before requesting objects (containers) from the global heap or OS, respectively.
    10521037The allocation buffer reduces contention and the number of global/operating-system calls.
    10531038For coalescing, a buffer is split into smaller objects by allocations, and recomposed into larger buffer areas during deallocations.
     
    10621047
    10631048Allocation buffers may increase external fragmentation, since some memory in the allocation buffer may never be allocated.
    1064 A smaller allocation buffer reduces the amount of external fragmentation, but increases the number of calls to the global heap or operating system.
     1049A smaller allocation buffer reduces the amount of external fragmentation, but increases the number of calls to the global heap or OS.
    10651050The allocation buffer also slightly increases internal fragmentation, since a pointer is necessary to locate the next free object in the buffer.
    10661051
     
    10681053For example, when a container is created, rather than placing all objects within the container on the free list, the objects form an allocation buffer and are allocated from the buffer as allocation requests are made.
    10691054This lazy method of constructing objects is beneficial in terms of paging and caching.
    1070 For example, although an entire container, possibly spanning several pages, is allocated from the operating system, only a small part of the container is used in the working set of the allocator, reducing the number of pages and cache lines that are brought into higher levels of cache.
    1071 
    1072 
    1073 \subsection{Lock-Free Operations}
     1055For example, although an entire container, possibly spanning several pages, is allocated from the OS, only a small part of the container is used in the working set of the allocator, reducing the number of pages and cache lines that are brought into higher levels of cache.
     1056
     1057
     1058\subsubsection{Lock-Free Operations}
    10741059\label{s:LockFreeOperations}
    10751060
     
    11941179% A sequence of code that is guaranteed to run to completion before being invoked to accept another input is called serially-reusable code.~\cite{SeriallyReusable}\label{p:SeriallyReusable}
    11951180% \end{quote}
    1196 % If a KT is preempted during an allocation operation, the operating system can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.
     1181% If a KT is preempted during an allocation operation, the OS can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.
    11971182% Note, the serially-reusable problem can occur in sequential programs with preemption, if the signal handler calls the preempted function, unless the function is serially reusable.
    1198 % Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the operating system is providing the second thread via the signal handler.
     1183% Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the OS is providing the second thread via the signal handler.
    11991184%
    12001185% Library @librseq@~\cite{librseq} was used to perform a fast determination of the CPU and to ensure all memory operations complete on one CPU using @librseq@'s restartable sequences, which restart the critical subsection after undoing its writes, if the critical subsection is preempted.
     
    12561241A sequence of code that is guaranteed to run to completion before being invoked to accept another input is called serially-reusable code.~\cite{SeriallyReusable}\label{p:SeriallyReusable}
    12571242\end{quote}
    1258 If a KT is preempted during an allocation operation, the operating system can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.
     1243If a KT is preempted during an allocation operation, the OS can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.
    12591244Note, the serially-reusable problem can occur in sequential programs with preemption, if the signal handler calls the preempted function, unless the function is serially reusable.
    1260 Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the operating system is providing the second thread via the signal handler.
     1245Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the OS is providing the second thread via the signal handler.
    12611246
    12621247Library @librseq@~\cite{librseq} was used to perform a fast determination of the CPU and to ensure all memory operations complete on one CPU using @librseq@'s restartable sequences, which restart the critical subsection after undoing its writes, if the critical subsection is preempted.
     
    12731258For the T:H=CPU and 1:1 models, locking is eliminated along the allocation fastpath.
    12741259However, T:H=CPU has poor operating-system support to determine the CPU id (heap id) and prevent the serially-reusable problem for KTs.
    1275 More operating system support is required to make this model viable, but there is still the serially-reusable problem with user-level threading.
     1260More OS support is required to make this model viable, but there is still the serially-reusable problem with user-level threading.
    12761261So the 1:1 model had no atomic actions along the fastpath and no special operating-system support requirements.
    12771262The 1:1 model still has the serially-reusable problem with user-level threading, which is addressed in Section~\ref{s:UserlevelThreadingSupport}, and the greatest potential for heap blowup for certain allocation patterns.
     
    13081293A primary goal of llheap is low latency, hence the name low-latency heap (llheap).
    13091294Two forms of latency are internal and external.
    1310 Internal latency is the time to perform an allocation, while external latency is time to obtain/return storage from/to the operating system.
     1295Internal latency is the time to perform an allocation, while external latency is time to obtain/return storage from/to the OS.
    13111296Ideally latency is $O(1)$ with a small constant.
    13121297
     
    13141299The mitigating factor is that most programs have well behaved allocation patterns, where the majority of allocation operations can be $O(1)$, and heap blowup does not occur without coalescing (although the allocation footprint may be slightly larger).
    13151300
    1316 To obtain $O(1)$ external latency means obtaining one large storage area from the operating system and subdividing it across all program allocations, which requires a good guess at the program storage high-watermark and potential large external fragmentation.
     1301To obtain $O(1)$ external latency means obtaining one large storage area from the OS and subdividing it across all program allocations, which requires a good guess at the program storage high-watermark and potential large external fragmentation.
    13171302Excluding real-time operating-systems, operating-system operations are unbounded, and hence some external latency is unavoidable.
    13181303The mitigating factor is that operating-system calls can often be reduced if a programmer has a sense of the storage high-watermark and the allocator is capable of using this information (see @malloc_expansion@ \pageref{p:malloc_expansion}).
     
    13291314headers per allocation versus containers,
    13301315no coalescing to minimize latency,
    1331 global heap memory (pool) obtained from the operating system using @mmap@ to create and reuse heaps needed by threads,
     1316global heap memory (pool) obtained from the OS using @mmap@ to create and reuse heaps needed by threads,
    13321317local reserved memory (pool) per heap obtained from global pool,
    1333 global reserved memory (pool) obtained from the operating system using @sbrk@ call,
     1318global reserved memory (pool) obtained from the OS using @sbrk@ call,
    13341319optional fast-lookup table for converting allocation requests into bucket sizes,
    13351320optional statistic-counters table for accumulating counts of allocation operations.
     
    13581343Each heap uses segregated free-buckets that have free objects distributed across 91 different sizes from 16 to 4M.
    13591344All objects in a bucket are of the same size.
    1360 The number of buckets used is determined dynamically depending on the crossover point from @sbrk@ to @mmap@ allocation using @mallopt( M_MMAP_THRESHOLD )@, \ie small objects managed by the program and large objects managed by the operating system.
     1345The number of buckets used is determined dynamically depending on the crossover point from @sbrk@ to @mmap@ allocation using @mallopt( M_MMAP_THRESHOLD )@, \ie small objects managed by the program and large objects managed by the OS.
    13611346Each free bucket of a specific size has two lists.
    136213471) A free stack used solely by the KT heap-owner, so push/pop operations do not require locking.
     
    13671352Algorithm~\ref{alg:heapObjectAlloc} shows the allocation outline for an object of size $S$.
    13681353First, the allocation is divided into small (@sbrk@) or large (@mmap@).
    1369 For large allocations, the storage is mapped directly from the operating system.
     1354For large allocations, the storage is mapped directly from the OS.
    13701355For small allocations, $S$ is quantized into a bucket size.
    13711356Quantizing is performed using a binary search over the ordered bucket array.
     
    13781363heap's local pool,
    13791364global pool,
    1380 operating system (@sbrk@).
     1365OS (@sbrk@).
    13811366
    13821367\begin{algorithm}
     
    14431428Algorithm~\ref{alg:heapObjectFreeOwn} shows the de-allocation (free) outline for an object at address $A$ with ownership.
    14441429First, the address is divided into small (@sbrk@) or large (@mmap@).
    1445 For large allocations, the storage is unmapped back to the operating system.
     1430For large allocations, the storage is unmapped back to the OS.
    14461431For small allocations, the bucket associated with the request size is retrieved.
    14471432If the bucket is local to the thread, the allocation is pushed onto the thread's associated bucket.
     
    30443029
    30453030\textsf{pt3} is the only memory allocator where the total dynamic memory goes down in the second half of the program lifetime when the memory is freed by the benchmark program.
    3046 It makes pt3 the only memory allocator that gives memory back to the operating system as it is freed by the program.
     3031It makes pt3 the only memory allocator that gives memory back to the OS as it is freed by the program.
    30473032
    30483033% FOR 1 THREAD
  • doc/papers/llheap/figures/AllocatorComponents.fig

    r24d6572 r62d62db  
    88-2
    991200 2
    10 6 1275 2025 2700 2625
    11106 2400 2025 2700 2625
    12112 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
     
    14132 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
    1514         2700 2025 2700 2325 2400 2325 2400 2025 2700 2025
    16 -6
    17 4 2 0 50 -1 2 11 0.0000 2 165 1005 2325 2400 Management\001
    1815-6
    19162 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
     
    61582 2 0 1 0 7 60 -1 13 0.000 0 0 -1 0 0 5
    6259         3300 2700 6300 2700 6300 3000 3300 3000 3300 2700
    63 4 0 0 50 -1 2 11 0.0000 2 165 585 3300 1725 Storage\001
     604 0 0 50 -1 2 11 0.0000 2 165 1005 3300 1725 Storage Data\001
    64614 2 0 50 -1 0 11 0.0000 2 165 810 3000 1875 free objects\001
    65624 2 0 50 -1 0 11 0.0000 2 135 1140 3000 2850 reserve memory\001
    66634 1 0 50 -1 0 11 0.0000 2 120 795 2325 1500 Static Zone\001
    67644 1 0 50 -1 0 11 0.0000 2 165 1845 4800 1500 Dynamic-Allocation Zone\001
     654 2 0 50 -1 2 11 0.0000 2 165 1005 2325 2325 Management\001
     664 2 0 50 -1 2 11 0.0000 2 135 375 2325 2525 Data\001
  • doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/balance.cfa

    r24d6572 r62d62db  
    3131
    3232d_actor ** actor_arr;
    33 Allocation receive( d_actor & this, start_msg & msg ) with( this ) {
     33allocation receive( d_actor & this, start_msg & msg ) with( this ) {
    3434    for ( i; Set ) {
    3535        *actor_arr[i + gstart] << shared_msg;
     
    3838}
    3939
    40 Allocation receive( d_actor & this, d_msg & msg ) with( this ) {
     40allocation receive( d_actor & this, d_msg & msg ) with( this ) {
    4141    if ( recs == rounds ) return Delete;
    4242    if ( recs % Batch == 0 ) {
     
    5050}
    5151
    52 Allocation receive( filler & this, d_msg & msg ) { return Delete; }
     52allocation receive( filler & this, d_msg & msg ) { return Delete; }
    5353
    5454int main( int argc, char * argv[] ) {
  • doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/dynamic.cfa

    r24d6572 r62d62db  
    2424
    2525uint64_t start_time;
    26 Allocation receive( derived_actor & receiver, derived_msg & msg ) {
     26allocation receive( derived_actor & receiver, derived_msg & msg ) {
    2727    if ( msg.cnt >= Times ) {
    2828        printf("%.2f\n", ((double)(bench_time() - start_time)) / ((double)Times) ); // ns
  • doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/executor.cfa

    r24d6572 r62d62db  
    2525struct d_msg { inline message; } shared_msg;
    2626
    27 Allocation receive( d_actor & this, d_msg & msg ) with( this ) {
     27allocation receive( d_actor & this, d_msg & msg ) with( this ) {
    2828    if ( recs == rounds ) return Finished;
    2929    if ( recs % Batch == 0 ) {
  • doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/matrix.cfa

    r24d6572 r62d62db  
    2424}
    2525
    26 Allocation receive( derived_actor & receiver, derived_msg & msg ) {
     26allocation receive( derived_actor & receiver, derived_msg & msg ) {
    2727    for ( unsigned int i = 0; i < yc; i += 1 ) { // multiply X_row by Y_col and sum products
    2828        msg.Z[i] = 0;
  • doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/repeat.cfa

    r24d6572 r62d62db  
    4646
    4747Client * cl;
    48 Allocation receive( Server & this, IntMsg & msg ) { msg.val = 7; *cl << msg; return Nodelete; }
    49 Allocation receive( Server & this, CharMsg & msg ) { msg.val = 'x'; *cl << msg; return Nodelete; }
    50 Allocation receive( Server & this, StateMsg & msg ) { return Finished; }
     48allocation receive( Server & this, IntMsg & msg ) { msg.val = 7; *cl << msg; return Nodelete; }
     49allocation receive( Server & this, CharMsg & msg ) { msg.val = 'x'; *cl << msg; return Nodelete; }
     50allocation receive( Server & this, StateMsg & msg ) { return Finished; }
    5151
    5252void terminateServers( Client & this ) with(this) {
     
    5656}
    5757
    58 Allocation reset( Client & this ) with(this) {
     58allocation reset( Client & this ) with(this) {
    5959    times += 1;
    6060    if ( times == Times ) { terminateServers( this ); return Finished; }
     
    6464}
    6565
    66 Allocation process( Client & this ) with(this) {
     66allocation process( Client & this ) with(this) {
    6767    this.results++;
    6868    if ( results == 2 * Messages ) { return reset( this ); }
     
    7070}
    7171
    72 Allocation receive( Client & this, IntMsg & msg ) { return process( this ); }
    73 Allocation receive( Client & this, CharMsg & msg ) { return process( this ); }
    74 Allocation receive( Client & this, StateMsg & msg ) with(this) {
     72allocation receive( Client & this, IntMsg & msg ) { return process( this ); }
     73allocation receive( Client & this, CharMsg & msg ) { return process( this ); }
     74allocation receive( Client & this, StateMsg & msg ) with(this) {
    7575    for ( i; Messages ) {
    7676        servers[i] << intmsg[i];
  • doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/static.cfa

    r24d6572 r62d62db  
    2323
    2424uint64_t start_time;
    25 Allocation receive( derived_actor & receiver, derived_msg & msg ) {
     25allocation receive( derived_actor & receiver, derived_msg & msg ) {
    2626    if ( msg.cnt >= Times ) {
    2727        printf("%.2f\n", ((double)(bench_time() - start_time)) / ((double)Times) ); // ns
  • doc/theses/colby_parsons_MMAth/code/basic_actor_example.cfa

    r24d6572 r62d62db  
    1919}
    2020
    21 Allocation receive( derived_actor & receiver, derived_msg & msg ) {
     21allocation receive( derived_actor & receiver, derived_msg & msg ) {
    2222    printf("The message contained the string: %s\n", msg.word);
    2323    return Finished; // Return allocation status of Finished now that the actor is done work
  • doc/user/figures/EHMHierarchy.fig

    r24d6572 r62d62db  
    2929        1 1 1.00 60.00 90.00
    3030         4950 1950 4950 1725
    31 4 1 0 50 -1 0 13 0.0000 2 135 225 1950 1650 IO\001
    32 4 1 0 50 -1 0 13 0.0000 2 135 915 4950 1650 Arithmetic\001
    33 4 1 0 50 -1 0 13 0.0000 2 150 330 1350 2100 File\001
    34 4 1 0 50 -1 0 13 0.0000 2 135 735 2550 2100 Network\001
    35 4 1 0 50 -1 0 13 0.0000 2 180 1215 3750 2100 DivideByZero\001
    36 4 1 0 50 -1 0 13 0.0000 2 150 810 4950 2100 Overflow\001
    37 4 1 0 50 -1 0 13 0.0000 2 150 915 6000 2100 Underflow\001
    38 4 1 0 50 -1 0 13 0.0000 2 180 855 3450 1200 Exception\001
     314 1 0 50 -1 0 12 0.0000 2 135 225 1950 1650 IO\001
     324 1 0 50 -1 0 12 0.0000 2 135 915 4950 1650 Arithmetic\001
     334 1 0 50 -1 0 12 0.0000 2 150 330 1350 2100 File\001
     344 1 0 50 -1 0 12 0.0000 2 135 735 2550 2100 Network\001
     354 1 0 50 -1 0 12 0.0000 2 180 1215 3750 2100 DivideByZero\001
     364 1 0 50 -1 0 12 0.0000 2 150 810 4950 2100 Overflow\001
     374 1 0 50 -1 0 12 0.0000 2 150 915 6000 2100 Underflow\001
     384 1 0 50 -1 0 12 0.0000 2 180 855 3450 1200 Exception\001
  • doc/user/user.tex

    r24d6572 r62d62db  
    1111%% Created On       : Wed Apr  6 14:53:29 2016
    1212%% Last Modified By : Peter A. Buhr
    13 %% Last Modified On : Mon Aug 22 23:43:30 2022
    14 %% Update Count     : 5503
     13%% Last Modified On : Mon Jun  5 21:18:29 2023
     14%% Update Count     : 5521
    1515%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    1616
     
    108108\huge \CFA Team (past and present) \medskip \\
    109109\Large Andrew Beach, Richard Bilson, Michael Brooks, Peter A. Buhr, Thierry Delisle, \smallskip \\
    110 \Large Glen Ditchfield, Rodolfo G. Esteves, Aaron Moss, Colby Parsons, Rob Schluntz, \smallskip \\
    111 \Large Fangren Yu, Mubeen Zulfiqar
     110\Large Glen Ditchfield, Rodolfo G. Esteves, Jiada Liang, Aaron Moss, Colby Parsons \smallskip \\
     111\Large Rob Schluntz, Fangren Yu, Mubeen Zulfiqar
    112112}% author
    113113
     
    169169Like \Index*[C++]{\CC{}}, there may be both old and new ways to achieve the same effect.
    170170For example, the following programs compare the C, \CFA, and \CC I/O mechanisms, where the programs output the same result.
    171 \begin{flushleft}
    172 \begin{tabular}{@{}l@{\hspace{1em}}l@{\hspace{1em}}l@{}}
    173 \multicolumn{1}{@{}c@{\hspace{1em}}}{\textbf{C}}        & \multicolumn{1}{c}{\textbf{\CFA}}     & \multicolumn{1}{c@{}}{\textbf{\CC}}   \\
     171\begin{center}
     172\begin{tabular}{@{}lll@{}}
     173\multicolumn{1}{@{}c}{\textbf{C}}       & \multicolumn{1}{c}{\textbf{\CFA}}     & \multicolumn{1}{c@{}}{\textbf{\CC}}   \\
    174174\begin{cfa}[tabsize=3]
    175175#include <stdio.h>$\indexc{stdio.h}$
     
    199199\end{cfa}
    200200\end{tabular}
    201 \end{flushleft}
     201\end{center}
    202202While \CFA I/O \see{\VRef{s:StreamIOLibrary}} looks similar to \Index*[C++]{\CC{}}, there are important differences, such as automatic spacing between variables and an implicit newline at the end of the expression list, similar to \Index*{Python}~\cite{Python}.
    203203
     
    856856still works.
    857857Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments.
    858 Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called \Indexc{choose}, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword \Indexc{fallthrough}/\Indexc{fallthru}, \eg:
     858Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called \Indexc{choose}, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword \Indexc{fallthrough}/\-\Indexc{fallthru}, \eg:
    859859\begin{cfa}
    860860®choose® ( i ) {
     
    11671167\end{cfa}
    11681168\end{itemize}
    1169 \R{Warning}: specifying the down-to range maybe unexcepted because the loop control \emph{implicitly} switches the L and H values (and toggles the increment/decrement for I):
     1169\R{Warning}: specifying the down-to range maybe unexpected because the loop control \emph{implicitly} switches the L and H values (and toggles the increment/decrement for I):
    11701170\begin{cfa}
    11711171for ( i; 1 ~ 10 )       ${\C[1.5in]{// up range}$
     
    11731173for ( i; ®10 -~ 1® )    ${\C{// \R{WRONG down range!}}\CRT}$
    11741174\end{cfa}
    1175 The reason for this sematics is that the range direction can be toggled by adding/removing the minus, ©'-'©, versus interchanging the L and H expressions, which has a greater chance of introducing errors.
     1175The reason for this semantics is that the range direction can be toggled by adding/removing the minus, ©'-'©, versus interchanging the L and H expressions, which has a greater chance of introducing errors.
    11761176
    11771177
     
    22562256Days days = Mon; // enumeration type declaration and initialization
    22572257\end{cfa}
    2258 The set of enums are injected into the variable namespace at the definition scope.
    2259 Hence, enums may be overloaded with enum/variable/function names.
    2260 \begin{cfa}
     2258The set of enums is injected into the variable namespace at the definition scope.
     2259Hence, enums may be overloaded with variable, enum, and function names.
     2260\begin{cfa}
     2261int Foo;                        $\C{// type/variable separate namespaces}$
    22612262enum Foo { Bar };
    22622263enum Goo { Bar };       $\C[1.75in]{// overload Foo.Bar}$
    2263 int Foo;                        $\C{// type/variable separate namespace}$
    22642264double Bar;                     $\C{// overload Foo.Bar, Goo.Bar}\CRT$
    22652265\end{cfa}
     
    23012301Hence, the value of enum ©Mon© is 0, ©Tue© is 1, ...\,, ©Sun© is 6.
    23022302If an enum value is specified, numbering continues by one from that value for subsequent unnumbered enums.
    2303 If an enum value is an expression, the compiler performs constant-folding to obtain a constant value.
     2303If an enum value is a \emph{constant} expression, the compiler performs constant-folding to obtain a constant value.
    23042304
    23052305\CFA allows other integral types with associated values.
     
    23132313\begin{cfa}
    23142314// non-integral numeric
    2315 enum( ®double® ) Math { PI_2 = 1.570796, PI = 3.141597,  E = 2.718282 }
     2315enum( ®double® ) Math { PI_2 = 1.570796, PI = 3.141597, E = 2.718282 }
    23162316// pointer
    2317 enum( ®char *® ) Name { Fred = "Fred",  Mary = "Mary",  Jane = "Jane" };
     2317enum( ®char *® ) Name { Fred = "Fred",  Mary = "Mary", Jane = "Jane" };
    23182318int i, j, k;
    23192319enum( ®int *® ) ptr { I = &i,  J = &j,  K = &k };
    2320 enum( ®int &® ) ref { I = i,  J = j,  K = k };
     2320enum( ®int &® ) ref { I = i,   J = j,   K = k };
    23212321// tuple
    23222322enum( ®[int, int]® ) { T = [ 1, 2 ] };
     
    23612361\begin{cfa}
    23622362enum( char * ) Name2 { ®inline Name®, Jack = "Jack", Jill = "Jill" };
    2363 enum ®/* inferred */®  Name3 { ®inline Name2®, Sue = "Sue", Tom = "Tom" };
     2363enum ®/* inferred */® Name3 { ®inline Name2®, Sue = "Sue", Tom = "Tom" };
    23642364\end{cfa}
    23652365Enumeration ©Name2© inherits all the enums and their values from enumeration ©Name© by containment, and a ©Name© enumeration is a subtype of enumeration ©Name2©.
     
    38183818                                   "[ output-file (default stdout) ] ]";
    38193819                } // choose
    3820         } catch( ®Open_Failure® * ex; ex->istream == &in ) {
     3820        } catch( ®open_failure® * ex; ex->istream == &in ) { $\C{// input file errors}$
    38213821                ®exit® | "Unable to open input file" | argv[1];
    3822         } catch( ®Open_Failure® * ex; ex->ostream == &out ) {
     3822        } catch( ®open_failure® * ex; ex->ostream == &out ) { $\C{// output file errors}$
    38233823                ®close®( in );                                          $\C{// optional}$
    38243824                ®exit® | "Unable to open output file" | argv[2];
     
    40384038
    40394039\item
    4040 \Indexc{sepDisable}\index{manipulator!sepDisable@©sepDisable©} and \Indexc{sepEnable}\index{manipulator!sepEnable@©sepEnable©} toggle printing the separator.
     4040\Indexc{sepDisable}\index{manipulator!sepDisable@©sepDisable©} and \Indexc{sepEnable}\index{manipulator!sepEnable@©sepEnable©} globally toggle printing the separator.
    40414041\begin{cfa}[belowskip=0pt]
    40424042sout | sepDisable | 1 | 2 | 3; $\C{// turn off implicit separator}$
     
    40534053
    40544054\item
    4055 \Indexc{sepOn}\index{manipulator!sepOn@©sepOn©} and \Indexc{sepOff}\index{manipulator!sepOff@©sepOff©} toggle printing the separator with respect to the next printed item, and then return to the global separator setting.
     4055\Indexc{sepOn}\index{manipulator!sepOn@©sepOn©} and \Indexc{sepOff}\index{manipulator!sepOff@©sepOff©} locally toggle printing the separator with respect to the next printed item, and then return to the global separator setting.
    40564056\begin{cfa}[belowskip=0pt]
    40574057sout | 1 | sepOff | 2 | 3; $\C{// turn off implicit separator for the next item}$
     
    412941296
    41304130\end{cfa}
    4131 Note, a terminating ©nl© is merged (overrides) with the implicit newline at the end of the ©sout© expression, otherwise it is impossible to to print a single newline
     4131Note, a terminating ©nl© is merged (overrides) with the implicit newline at the end of the ©sout© expression, otherwise it is impossible to print a single newline
    41324132\item
    41334133\Indexc{nlOn}\index{manipulator!nlOn@©nlOn©} implicitly prints a newline at the end of each output expression.
  • driver/cc1.cc

    r24d6572 r62d62db  
    1010// Created On       : Fri Aug 26 14:23:51 2005
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Feb 17 18:04:23 2022
    13 // Update Count     : 422
     12// Last Modified On : Fri Jun  9 11:36:44 2023
     13// Update Count     : 423
    1414//
    1515
     
    385385                                // strip inappropriate flags with an argument
    386386
    387                         } else if ( arg == "-auxbase" || arg == "-auxbase-strip" || arg == "-dumpbase" || arg == "-dumpdir" ) {
     387                        } else if ( arg == "-auxbase" || arg == "-auxbase-strip" ||
     388                                                arg == "-dumpbase" || arg == "-dumpbase-ext" || arg == "-dumpdir" ) {
    388389                                i += 1;
    389390                                #ifdef __DEBUG_H__
  • libcfa/src/concurrency/actor.hfa

    r24d6572 r62d62db  
    1313#endif // CFA_DEBUG
    1414
     15#define DEBUG_ABORT( cond, string ) CFA_DEBUG( if ( cond ) abort( string ) )
     16
    1517// Define the default number of processors created in the executor. Must be greater than 0.
    1618#define __DEFAULT_EXECUTOR_PROCESSORS__ 2
     
    4244struct executor;
    4345
    44 enum Allocation { Nodelete, Delete, Destroy, Finished }; // allocation status
    45 
    46 typedef Allocation (*__receive_fn)(actor &, message &);
     46enum allocation { Nodelete, Delete, Destroy, Finished }; // allocation status
     47
     48typedef allocation (*__receive_fn)(actor &, message &);
    4749struct request {
    4850    actor * receiver;
     
    393395struct actor {
    394396    size_t ticket;                                          // executor-queue handle
    395     Allocation allocation_;                                         // allocation action
     397    allocation allocation_;                                         // allocation action
    396398    inline virtual_dtor;
    397399};
     
    400402    // Once an actor is allocated it must be sent a message or the actor system cannot stop. Hence, its receive
    401403    // member must be called to end it
    402     verifyf( __actor_executor_, "Creating actor before calling start_actor_system() can cause undefined behaviour.\n" );
     404    DEBUG_ABORT( __actor_executor_ == 0p, "Creating actor before calling start_actor_system() can cause undefined behaviour.\n" );
    403405    allocation_ = Nodelete;
    404406    ticket = __get_next_ticket( *__actor_executor_ );
     
    430432
    431433struct message {
    432     Allocation allocation_;                     // allocation action
     434    allocation allocation_;                     // allocation action
    433435    inline virtual_dtor;
    434436};
     
    437439    this.allocation_ = Nodelete;
    438440}
    439 static inline void ?{}( message & this, Allocation allocation ) {
    440     memcpy( &this.allocation_, &allocation, sizeof(allocation) ); // optimization to elide ctor
    441     verifyf( this.allocation_ != Finished, "The Finished Allocation status is not supported for message types.\n");
     441static inline void ?{}( message & this, allocation alloc ) {
     442    memcpy( &this.allocation_, &alloc, sizeof(allocation) ); // optimization to elide ctor
     443    DEBUG_ABORT( this.allocation_ == Finished, "The Finished allocation status is not supported for message types.\n" );
    442444}
    443445static inline void ^?{}( message & this ) with(this) {
     
    453455    } // switch
    454456}
    455 static inline void set_allocation( message & this, Allocation state ) {
     457static inline void set_allocation( message & this, allocation state ) {
    456458    this.allocation_ = state;
    457459}
    458460
    459461static inline void deliver_request( request & this ) {
     462    DEBUG_ABORT( this.receiver->ticket == (unsigned long int)MAX, "Attempted to send message to deleted/dead actor\n" );
    460463    this.receiver->allocation_ = this.fn( *this.receiver, *this.msg );
    461464    check_message( *this.msg );
     
    631634
    632635static inline void send( actor & this, request & req ) {
    633     verifyf( this.ticket != (unsigned long int)MAX, "Attempted to send message to deleted/dead actor\n" );
     636    DEBUG_ABORT( this.ticket == (unsigned long int)MAX, "Attempted to send message to deleted/dead actor\n" );
    634637    send( *__actor_executor_, req, this.ticket );
    635638}
     
    680683// assigned at creation to __base_msg_finished to avoid unused message warning
    681684message __base_msg_finished @= { .allocation_ : Finished };
    682 struct __DeleteMsg { inline message; } DeleteMsg = __base_msg_finished;
    683 struct __DestroyMsg { inline message; } DestroyMsg = __base_msg_finished;
    684 struct __FinishedMsg { inline message; } FinishedMsg = __base_msg_finished;
    685 
    686 Allocation receive( actor & this, __DeleteMsg & msg ) { return Delete; }
    687 Allocation receive( actor & this, __DestroyMsg & msg ) { return Destroy; }
    688 Allocation receive( actor & this, __FinishedMsg & msg ) { return Finished; }
    689 
     685struct __delete_msg_t { inline message; } delete_msg = __base_msg_finished;
     686struct __destroy_msg_t { inline message; } destroy_msg = __base_msg_finished;
     687struct __finished_msg_t { inline message; } finished_msg = __base_msg_finished;
     688
     689allocation receive( actor & this, __delete_msg_t & msg ) { return Delete; }
     690allocation receive( actor & this, __destroy_msg_t & msg ) { return Destroy; }
     691allocation receive( actor & this, __finished_msg_t & msg ) { return Finished; }
     692
  • libcfa/src/concurrency/atomic.hfa

    r24d6572 r62d62db  
    1010// Created On       : Thu May 25 15:22:46 2023
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu May 25 15:24:45 2023
    13 // Update Count     : 1
     12// Last Modified On : Fri Jun  9 13:36:47 2023
     13// Update Count     : 46
    1414//
    1515
    16 #define LOAD( lock ) (__atomic_load_n( &(lock), __ATOMIC_SEQ_CST ))
    17 #define LOADM( lock, memorder ) (__atomic_load_n( &(lock), memorder ))
    18 #define STORE( lock, assn ) (__atomic_store_n( &(lock), assn, __ATOMIC_SEQ_CST ))
    19 #define STOREM( lock, assn, memorder ) (__atomic_store_n( &(lock), assn, memorder ))
    20 #define CLR( lock ) (__atomic_clear( &(lock), __ATOMIC_RELEASE ))
    21 #define CLRM( lock, memorder ) (__atomic_clear( &(lock), memorder ))
    22 #define TAS( lock ) (__atomic_test_and_set( &(lock), __ATOMIC_ACQUIRE ))
    23 #define TASM( lock, memorder ) (__atomic_test_and_set( &(lock), memorder ))
    24 #define CAS( change, comp, assn ) ({typeof(comp) __temp = (comp); __atomic_compare_exchange_n( &(change), &(__temp), (assn), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ); })
    25 #define CASM( change, comp, assn, memorder... ) ({typeof(comp) * __temp = &(comp); __atomic_compare_exchange_n( &(change), &(__temp), (assn), false, memorder, memorder ); })
    26 #define CASV( change, comp, assn ) (__atomic_compare_exchange_n( &(change), &(comp), (assn), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ))
    27 #define CASVM( change, comp, assn, memorder... ) (__atomic_compare_exchange_n( &(change), &(comp), (assn), false, memorder, memorder ))
    28 #define FAS( change, assn ) (__atomic_exchange_n( &(change), (assn), __ATOMIC_SEQ_CST ))
    29 #define FASM( change, assn, memorder ) (__atomic_exchange_n( &(change), (assn), memorder ))
    30 #define FAI( change, Inc ) (__atomic_fetch_add( &(change), (Inc), __ATOMIC_SEQ_CST ))
    31 #define FAIM( change, Inc, memorder ) (__atomic_fetch_add( &(change), (Inc), memorder ))
     16#define LOAD( val ) (LOADM( val, __ATOMIC_SEQ_CST))
     17#define LOADM( val, memorder ) (__atomic_load_n( &(val), memorder))
     18
     19#define STORE( val, assn ) (STOREM( val, assn, __ATOMIC_SEQ_CST))
     20#define STOREM( val, assn, memorder ) (__atomic_store_n( &(val), assn, memorder))
     21
     22#define TAS( lock ) (TASM( lock, __ATOMIC_ACQUIRE))
     23#define TASM( lock, memorder ) (__atomic_test_and_set( &(lock), memorder))
     24
     25#define TASCLR( lock ) (TASCLRM( lock, __ATOMIC_RELEASE))
     26#define TASCLRM( lock, memorder ) (__atomic_clear( &(lock), memorder))
     27
     28#define FAS( assn, replace ) (FASM(assn, replace, __ATOMIC_SEQ_CST))
     29#define FASM( assn, replace, memorder ) (__atomic_exchange_n( &(assn), (replace), memorder))
     30
     31#define FAI( assn, Inc ) (__atomic_fetch_add( &(assn), (Inc), __ATOMIC_SEQ_CST))
     32#define FAIM( assn, Inc, memorder ) (__atomic_fetch_add( &(assn), (Inc), memorder))
     33
     34// Use __sync because __atomic with 128-bit CAA can result in calls to pthread_mutex_lock.
     35
     36// #define CAS( assn, comp, replace ) (CASM( assn, comp, replace, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
     37// #define CASM( assn, comp, replace, memorder... ) ({ \
     38//      typeof(comp) __temp = (comp); \
     39//      __atomic_compare_exchange_n( &(assn), &(__temp), (replace), false, memorder ); \
     40// })
     41#define CAS( assn, comp, replace ) (__sync_bool_compare_and_swap( &assn, comp, replace))
     42#define CASM( assn, comp, replace, memorder... ) _Static_assert( false, "memory order unsupported for CAS macro" );
     43
     44// #define CASV( assn, comp, replace ) (__atomic_compare_exchange_n( &(assn), &(comp), (replace), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ))
     45// #define CASVM( assn, comp, replace, memorder... ) (__atomic_compare_exchange_n( &(assn), &(comp), (replace), false, memorder, memorder ))
     46#define CASV( assn, comp, replace ) ({ \
     47        typeof(comp) temp = comp; \
     48        typeof(comp) old = __sync_val_compare_and_swap( &(assn), (comp), (replace) ); \
     49        old == temp ? true : (comp = old, false); \
     50})
     51#define CASVM( assn, comp, replace, memorder... ) _Static_assert( false, "memory order unsupported for CASV macro" );
  • libcfa/src/concurrency/channel.hfa

    r24d6572 r62d62db  
    5151vtable(channel_closed) channel_closed_vt;
    5252
    53 static inline bool is_insert( channel_closed & e ) { return elem != 0p; }
    54 static inline bool is_remove( channel_closed & e ) { return elem == 0p; }
     53static inline bool is_insert( channel_closed & e ) { return e.elem != 0p; }
     54static inline bool is_remove( channel_closed & e ) { return e.elem == 0p; }
    5555
    5656// #define CHAN_STATS // define this to get channel stats printed in dtor
  • libcfa/src/concurrency/locks.hfa

    r24d6572 r62d62db  
    3232#include "select.hfa"
    3333
    34 #include <fstream.hfa>
    35 
    3634// futex headers
    3735#include <linux/futex.h>      /* Definition of FUTEX_* constants */
  • libcfa/src/containers/lockfree.hfa

    r24d6572 r62d62db  
    199199
    200200forall( T & )
     201struct LinkData {
     202        T * volatile top;                                                               // pointer to stack top
     203        uintptr_t count;                                                                // count each push
     204};
     205
     206forall( T & )
    201207union Link {
    202         struct {                                                                                        // 32/64-bit x 2
    203                 T * volatile top;                                                               // pointer to stack top
    204                 uintptr_t count;                                                                // count each push
    205         };
     208        LinkData(T) data;
    206209        #if __SIZEOF_INT128__ == 16
    207210        __int128                                                                                        // gcc, 128-bit integer
     
    220223                void ?{}( StackLF(T) & this ) with(this) { stack.atom = 0; }
    221224
    222                 T * top( StackLF(T) & this ) with(this) { return stack.top; }
     225                T * top( StackLF(T) & this ) with(this) { return stack.data.top; }
    223226
    224227                void push( StackLF(T) & this, T & n ) with(this) {
    225228                        *( &n )`next = stack;                                           // atomic assignment unnecessary, or use CAA
    226229                        for () {                                                                        // busy wait
    227                           if ( __atomic_compare_exchange_n( &stack.atom, &( &n )`next->atom, (Link(T))@{ {&n, ( &n )`next->count + 1} }.atom, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) ) break; // attempt to update top node
     230                                if ( __atomic_compare_exchange_n( &stack.atom, &( &n )`next->atom, (Link(T))@{ (LinkData(T))@{ &n, ( &n )`next->data.count + 1} }.atom, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) ) break; // attempt to update top node
    228231                        } // for
    229232                } // push
     
    232235                        Link(T) t @= stack;                                                     // atomic assignment unnecessary, or use CAA
    233236                        for () {                                                                        // busy wait
    234                           if ( t.top == 0p ) return 0p;                         // empty stack ?
    235                           if ( __atomic_compare_exchange_n( &stack.atom, &t.atom, (Link(T))@{ {( t.top )`next->top, t.count} }.atom, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) ) return t.top; // attempt to update top node
     237                                if ( t.data.top == 0p ) return 0p;                              // empty stack ?
     238                                Link(T) * next = ( t.data.top )`next;
     239                                if ( __atomic_compare_exchange_n( &stack.atom, &t.atom, (Link(T))@{ (LinkData(T))@{ next->data.top, t.data.count } }.atom, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) ) return t.data.top; // attempt to update top node
    236240                        } // for
    237241                } // pop
     
    239243                bool unsafe_remove( StackLF(T) & this, T * node ) with(this) {
    240244                        Link(T) * link = &stack;
    241                         for() {
    242                                 T * next = link->top;
    243                                 if( next == node ) {
    244                                         link->top = ( node )`next->top;
     245                        for () {
     246                                // TODO: Avoiding some problems with double fields access.
     247                                LinkData(T) * data = &link->data;
     248                                T * next = (T *)&(*data).top;
     249                                if ( next == node ) {
     250                                        data->top = ( node )`next->data.top;
    245251                                        return true;
    246252                                }
    247                                 if( next == 0p ) return false;
     253                                if ( next == 0p ) return false;
    248254                                link = ( next )`next;
    249255                        }
  • libcfa/src/fstream.cfa

    r24d6572 r62d62db  
    1010// Created On       : Wed May 27 17:56:53 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sat Apr  9 14:55:54 2022
    13 // Update Count     : 515
     12// Last Modified On : Mon Jun  5 22:00:23 2023
     13// Update Count     : 518
    1414//
    1515
     
    117117    } // for
    118118        if ( file == 0p ) {
    119                 throw (Open_Failure){ os };
     119                throw (open_failure){ os };
    120120                // abort | IO_MSG "open output file \"" | name | "\"" | nl | strerror( errno );
    121121        } // if
     
    137137    } // for
    138138        if ( ret == EOF ) {
    139                 throw (Close_Failure){ os };
     139                throw (close_failure){ os };
    140140                // abort | IO_MSG "close output" | nl | strerror( errno );
    141141        } // if
     
    145145ofstream & write( ofstream & os, const char data[], size_t size ) {
    146146        if ( fail( os ) ) {
    147                 throw (Write_Failure){ os };
     147                throw (write_failure){ os };
    148148                // abort | IO_MSG "attempt write I/O on failed stream";
    149149        } // if
    150150
    151151        if ( fwrite( data, 1, size, (FILE *)(os.file$) ) != size ) {
    152                 throw (Write_Failure){ os };
     152                throw (write_failure){ os };
    153153                // abort | IO_MSG "write" | nl | strerror( errno );
    154154        } // if
     
    240240    } // for
    241241        if ( file == 0p ) {
    242                 throw (Open_Failure){ is };
     242                throw (open_failure){ is };
    243243                // abort | IO_MSG "open input file \"" | name | "\"" | nl | strerror( errno );
    244244        } // if
     
    260260    } // for
    261261        if ( ret == EOF ) {
    262                 throw (Close_Failure){ is };
     262                throw (close_failure){ is };
    263263                // abort | IO_MSG "close input" | nl | strerror( errno );
    264264        } // if
     
    268268ifstream & read( ifstream & is, char data[], size_t size ) {
    269269        if ( fail( is ) ) {
    270                 throw (Read_Failure){ is };
     270                throw (read_failure){ is };
    271271                // abort | IO_MSG "attempt read I/O on failed stream";
    272272        } // if
    273273
    274274        if ( fread( data, size, 1, (FILE *)(is.file$) ) == 0 ) {
    275                 throw (Read_Failure){ is };
     275                throw (read_failure){ is };
    276276                // abort | IO_MSG "read" | nl | strerror( errno );
    277277        } // if
     
    318318
    319319
    320 static vtable(Open_Failure) Open_Failure_vt;
     320static vtable(open_failure) open_failure_vt;
    321321
    322322// exception I/O constructors
    323 void ?{}( Open_Failure & ex, ofstream & ostream ) with(ex) {
    324         virtual_table = &Open_Failure_vt;
     323void ?{}( open_failure & ex, ofstream & ostream ) with(ex) {
     324        virtual_table = &open_failure_vt;
    325325        ostream = &ostream;
    326326        tag = 1;
    327327} // ?{}
    328328
    329 void ?{}( Open_Failure & ex, ifstream & istream ) with(ex) {
    330         virtual_table = &Open_Failure_vt;
     329void ?{}( open_failure & ex, ifstream & istream ) with(ex) {
     330        virtual_table = &open_failure_vt;
    331331        istream = &istream;
    332332        tag = 0;
     
    334334
    335335
    336 static vtable(Close_Failure) Close_Failure_vt;
     336static vtable(close_failure) close_failure_vt;
    337337
    338338// exception I/O constructors
    339 void ?{}( Close_Failure & ex, ofstream & ostream ) with(ex) {
    340         virtual_table = &Close_Failure_vt;
     339void ?{}( close_failure & ex, ofstream & ostream ) with(ex) {
     340        virtual_table = &close_failure_vt;
    341341        ostream = &ostream;
    342342        tag = 1;
    343343} // ?{}
    344344
    345 void ?{}( Close_Failure & ex, ifstream & istream ) with(ex) {
    346         virtual_table = &Close_Failure_vt;
     345void ?{}( close_failure & ex, ifstream & istream ) with(ex) {
     346        virtual_table = &close_failure_vt;
    347347        istream = &istream;
    348348        tag = 0;
     
    350350
    351351
    352 static vtable(Write_Failure) Write_Failure_vt;
     352static vtable(write_failure) write_failure_vt;
    353353
    354354// exception I/O constructors
    355 void ?{}( Write_Failure & ex, ofstream & ostream ) with(ex) {
    356         virtual_table = &Write_Failure_vt;
     355void ?{}( write_failure & ex, ofstream & ostream ) with(ex) {
     356        virtual_table = &write_failure_vt;
    357357        ostream = &ostream;
    358358        tag = 1;
    359359} // ?{}
    360360
    361 void ?{}( Write_Failure & ex, ifstream & istream ) with(ex) {
    362         virtual_table = &Write_Failure_vt;
     361void ?{}( write_failure & ex, ifstream & istream ) with(ex) {
     362        virtual_table = &write_failure_vt;
    363363        istream = &istream;
    364364        tag = 0;
     
    366366
    367367
    368 static vtable(Read_Failure) Read_Failure_vt;
     368static vtable(read_failure) read_failure_vt;
    369369
    370370// exception I/O constructors
    371 void ?{}( Read_Failure & ex, ofstream & ostream ) with(ex) {
    372         virtual_table = &Read_Failure_vt;
     371void ?{}( read_failure & ex, ofstream & ostream ) with(ex) {
     372        virtual_table = &read_failure_vt;
    373373        ostream = &ostream;
    374374        tag = 1;
    375375} // ?{}
    376376
    377 void ?{}( Read_Failure & ex, ifstream & istream ) with(ex) {
    378         virtual_table = &Read_Failure_vt;
     377void ?{}( read_failure & ex, ifstream & istream ) with(ex) {
     378        virtual_table = &read_failure_vt;
    379379        istream = &istream;
    380380        tag = 0;
    381381} // ?{}
    382382
    383 // void throwOpen_Failure( ofstream & ostream ) {
    384 //      Open_Failure exc = { ostream };
     383// void throwopen_failure( ofstream & ostream ) {
     384//      open_failure exc = { ostream };
    385385// }
    386386
    387 // void throwOpen_Failure( ifstream & istream ) {
    388 //      Open_Failure exc = { istream };
     387// void throwopen_failure( ifstream & istream ) {
     388//      open_failure exc = { istream };
    389389// }
    390390
  • libcfa/src/fstream.hfa

    r24d6572 r62d62db  
    1010// Created On       : Wed May 27 17:56:53 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sun Oct 10 09:37:32 2021
    13 // Update Count     : 243
     12// Last Modified On : Mon Jun  5 22:00:20 2023
     13// Update Count     : 246
    1414//
    1515
     
    137137
    138138
    139 exception Open_Failure {
     139exception open_failure {
    140140        union {
    141141                ofstream * ostream;
     
    146146};
    147147
    148 void ?{}( Open_Failure & this, ofstream & );
    149 void ?{}( Open_Failure & this, ifstream & );
     148void ?{}( open_failure & this, ofstream & );
     149void ?{}( open_failure & this, ifstream & );
    150150
    151 exception Close_Failure {
     151exception close_failure {
    152152        union {
    153153                ofstream * ostream;
     
    158158};
    159159
    160 void ?{}( Close_Failure & this, ofstream & );
    161 void ?{}( Close_Failure & this, ifstream & );
     160void ?{}( close_failure & this, ofstream & );
     161void ?{}( close_failure & this, ifstream & );
    162162
    163 exception Write_Failure {
     163exception write_failure {
    164164        union {
    165165                ofstream * ostream;
     
    170170};
    171171
    172 void ?{}( Write_Failure & this, ofstream & );
    173 void ?{}( Write_Failure & this, ifstream & );
     172void ?{}( write_failure & this, ofstream & );
     173void ?{}( write_failure & this, ifstream & );
    174174
    175 exception Read_Failure {
     175exception read_failure {
    176176        union {
    177177                ofstream * ostream;
     
    182182};
    183183
    184 void ?{}( Read_Failure & this, ofstream & );
    185 void ?{}( Read_Failure & this, ifstream & );
     184void ?{}( read_failure & this, ofstream & );
     185void ?{}( read_failure & this, ifstream & );
    186186
    187187// Local Variables: //
  • libcfa/src/math.trait.hfa

    r24d6572 r62d62db  
    1010// Created On       : Fri Jul 16 15:40:52 2021
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Feb  2 11:36:56 2023
    13 // Update Count     : 20
     12// Last Modified On : Tue Jun  6 07:59:17 2023
     13// Update Count     : 24
    1414//
    1515
     
    1717
    1818forall( U )
    19 trait Not {
     19trait not {
    2020        void ?{}( U &, zero_t );
    2121        int !?( U );
    22 }; // Not
     22}; // not
    2323
    24 forall( T | Not( T ) )
    25 trait Equality {
     24forall( T | not( T ) )
     25trait equality {
    2626        int ?==?( T, T );
    2727        int ?!=?( T, T );
    28 }; // Equality
     28}; // equality
    2929
    30 forall( U | Equality( U ) )
    31 trait Relational {
     30forall( U | equality( U ) )
     31trait relational {
    3232        int ?<?( U, U );
    3333        int ?<=?( U, U );
    3434        int ?>?( U, U );
    3535        int ?>=?( U, U );
    36 }; // Relational
     36}; // relational
    3737
    3838forall ( T )
    39 trait Signed {
     39trait Signed {  // must be capitalized, conflict with keyword signed
    4040        T +?( T );
    4141        T -?( T );
     
    4444
    4545forall( U | Signed( U ) )
    46 trait Additive {
     46trait additive {
    4747        U ?+?( U, U );
    4848        U ?-?( U, U );
    4949        U ?+=?( U &, U );
    5050        U ?-=?( U &, U );
    51 }; // Additive
     51}; // additive
    5252
    53 forall( T | Additive( T ) )
    54 trait Incdec {
     53forall( T | additive( T ) )
     54trait inc_dec {
    5555        void ?{}( T &, one_t );
    5656        // T ?++( T & );
     
    5858        // T ?--( T & );
    5959        // T --?( T & );
    60 }; // Incdec
     60}; // inc_dec
    6161
    62 forall( U | Incdec( U ) )
    63 trait Multiplicative {
     62forall( U | inc_dec( U ) )
     63trait multiplicative {
    6464        U ?*?( U, U );
    6565        U ?/?( U, U );
    6666        U ?%?( U, U );
    6767        U ?/=?( U &, U );
    68 }; // Multiplicative
     68}; // multiplicative
    6969
    70 forall( T | Relational( T ) | Multiplicative( T ) )
    71 trait Arithmetic {
    72 }; // Arithmetic
     70forall( T | relational( T ) | multiplicative( T ) )
     71trait arithmetic {
     72}; // arithmetic
    7373
    7474// Local Variables: //
  • libcfa/src/parseconfig.cfa

    r24d6572 r62d62db  
    144144                        in | nl;                                                                // ignore remainder of line
    145145                } // for
    146         } catch( Open_Failure * ex; ex->istream == &in ) {
     146        } catch( open_failure * ex; ex->istream == &in ) {
    147147                delete( kv_pairs );
    148148                throw *ex;
     
    203203
    204204
    205 forall(T | Relational( T ))
     205forall(T | relational( T ))
    206206[ bool ] is_nonnegative( & T value ) {
    207207        T zero_val = 0;
     
    209209}
    210210
    211 forall(T | Relational( T ))
     211forall(T | relational( T ))
    212212[ bool ] is_positive( & T value ) {
    213213        T zero_val = 0;
     
    215215}
    216216
    217 forall(T | Relational( T ))
     217forall(T | relational( T ))
    218218[ bool ] is_nonpositive( & T value ) {
    219219        T zero_val = 0;
     
    221221}
    222222
    223 forall(T | Relational( T ))
     223forall(T | relational( T ))
    224224[ bool ] is_negative( & T value ) {
    225225        T zero_val = 0;
  • libcfa/src/parseconfig.hfa

    r24d6572 r62d62db  
    107107
    108108
    109 forall(T | Relational( T ))
     109forall(T | relational( T ))
    110110[ bool ] is_nonnegative( & T );
    111111
    112 forall(T | Relational( T ))
     112forall(T | relational( T ))
    113113[ bool ] is_positive( & T );
    114114
    115 forall(T | Relational( T ))
     115forall(T | relational( T ))
    116116[ bool ] is_nonpositive( & T );
    117117
    118 forall(T | Relational( T ))
     118forall(T | relational( T ))
    119119[ bool ] is_negative( & T );
    120120
  • libcfa/src/rational.cfa

    r24d6572 r62d62db  
    1010// Created On       : Wed Apr  6 17:54:28 2016
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Aug 25 18:09:58 2022
    13 // Update Count     : 194
     12// Last Modified On : Mon Jun  5 22:49:06 2023
     13// Update Count     : 196
    1414//
    1515
     
    2020#pragma GCC visibility push(default)
    2121
    22 forall( T | Arithmetic( T ) ) {
     22forall( T | arithmetic( T ) ) {
    2323        // helper routines
    2424
     
    3939                        abort | "Invalid rational number construction: denominator cannot be equal to 0.";
    4040                } // exit
    41                 if ( d < (T){0} ) { d = -d; n = -n; } // move sign to numerator
     41                if ( d < (T){0} ) { d = -d; n = -n; }                   // move sign to numerator
    4242                return gcd( abs( n ), d );                                              // simplify
    43         } // Rationalnumber::simplify
     43        } // simplify
    4444
    4545        // constructors
    4646
    47         void ?{}( Rational(T) & r, zero_t ) {
     47        void ?{}( rational(T) & r, zero_t ) {
    4848                r{ (T){0}, (T){1} };
    4949        } // rational
    5050
    51         void ?{}( Rational(T) & r, one_t ) {
     51        void ?{}( rational(T) & r, one_t ) {
    5252                r{ (T){1}, (T){1} };
    5353        } // rational
    5454
    55         void ?{}( Rational(T) & r ) {
     55        void ?{}( rational(T) & r ) {
    5656                r{ (T){0}, (T){1} };
    5757        } // rational
    5858
    59         void ?{}( Rational(T) & r, T n ) {
     59        void ?{}( rational(T) & r, T n ) {
    6060                r{ n, (T){1} };
    6161        } // rational
    6262
    63         void ?{}( Rational(T) & r, T n, T d ) {
    64                 T t = simplify( n, d );                         // simplify
     63        void ?{}( rational(T) & r, T n, T d ) {
     64                T t = simplify( n, d );                                                 // simplify
    6565                r.[numerator, denominator] = [n / t, d / t];
    6666        } // rational
     
    6868        // getter for numerator/denominator
    6969
    70         T numerator( Rational(T) r ) {
     70        T numerator( rational(T) r ) {
    7171                return r.numerator;
    7272        } // numerator
    7373
    74         T denominator( Rational(T) r ) {
     74        T denominator( rational(T) r ) {
    7575                return r.denominator;
    7676        } // denominator
    7777
    78         [ T, T ] ?=?( & [ T, T ] dest, Rational(T) src ) {
     78        [ T, T ] ?=?( & [ T, T ] dest, rational(T) src ) {
    7979                return dest = src.[ numerator, denominator ];
    8080        } // ?=?
     
    8282        // setter for numerator/denominator
    8383
    84         T numerator( Rational(T) r, T n ) {
     84        T numerator( rational(T) r, T n ) {
    8585                T prev = r.numerator;
    86                 T t = gcd( abs( n ), r.denominator ); // simplify
     86                T t = gcd( abs( n ), r.denominator );                   // simplify
    8787                r.[numerator, denominator] = [n / t, r.denominator / t];
    8888                return prev;
    8989        } // numerator
    9090
    91         T denominator( Rational(T) r, T d ) {
     91        T denominator( rational(T) r, T d ) {
    9292                T prev = r.denominator;
    93                 T t = simplify( r.numerator, d );       // simplify
     93                T t = simplify( r.numerator, d );                               // simplify
    9494                r.[numerator, denominator] = [r.numerator / t, d / t];
    9595                return prev;
     
    9898        // comparison
    9999
    100         int ?==?( Rational(T) l, Rational(T) r ) {
     100        int ?==?( rational(T) l, rational(T) r ) {
    101101                return l.numerator * r.denominator == l.denominator * r.numerator;
    102102        } // ?==?
    103103
    104         int ?!=?( Rational(T) l, Rational(T) r ) {
     104        int ?!=?( rational(T) l, rational(T) r ) {
    105105                return ! ( l == r );
    106106        } // ?!=?
    107107
    108         int ?!=?( Rational(T) l, zero_t ) {
    109                 return ! ( l == (Rational(T)){ 0 } );
     108        int ?!=?( rational(T) l, zero_t ) {
     109                return ! ( l == (rational(T)){ 0 } );
    110110        } // ?!=?
    111111
    112         int ?<?( Rational(T) l, Rational(T) r ) {
     112        int ?<?( rational(T) l, rational(T) r ) {
    113113                return l.numerator * r.denominator < l.denominator * r.numerator;
    114114        } // ?<?
    115115
    116         int ?<=?( Rational(T) l, Rational(T) r ) {
     116        int ?<=?( rational(T) l, rational(T) r ) {
    117117                return l.numerator * r.denominator <= l.denominator * r.numerator;
    118118        } // ?<=?
    119119
    120         int ?>?( Rational(T) l, Rational(T) r ) {
     120        int ?>?( rational(T) l, rational(T) r ) {
    121121                return ! ( l <= r );
    122122        } // ?>?
    123123
    124         int ?>=?( Rational(T) l, Rational(T) r ) {
     124        int ?>=?( rational(T) l, rational(T) r ) {
    125125                return ! ( l < r );
    126126        } // ?>=?
     
    128128        // arithmetic
    129129
    130         Rational(T) +?( Rational(T) r ) {
    131                 return (Rational(T)){ r.numerator, r.denominator };
     130        rational(T) +?( rational(T) r ) {
     131                return (rational(T)){ r.numerator, r.denominator };
    132132        } // +?
    133133
    134         Rational(T) -?( Rational(T) r ) {
    135                 return (Rational(T)){ -r.numerator, r.denominator };
     134        rational(T) -?( rational(T) r ) {
     135                return (rational(T)){ -r.numerator, r.denominator };
    136136        } // -?
    137137
    138         Rational(T) ?+?( Rational(T) l, Rational(T) r ) {
     138        rational(T) ?+?( rational(T) l, rational(T) r ) {
    139139                if ( l.denominator == r.denominator ) {                 // special case
    140                         return (Rational(T)){ l.numerator + r.numerator, l.denominator };
     140                        return (rational(T)){ l.numerator + r.numerator, l.denominator };
    141141                } else {
    142                         return (Rational(T)){ l.numerator * r.denominator + l.denominator * r.numerator, l.denominator * r.denominator };
     142                        return (rational(T)){ l.numerator * r.denominator + l.denominator * r.numerator, l.denominator * r.denominator };
    143143                } // if
    144144        } // ?+?
    145145
    146         Rational(T) ?+=?( Rational(T) & l, Rational(T) r ) {
     146        rational(T) ?+=?( rational(T) & l, rational(T) r ) {
    147147                l = l + r;
    148148                return l;
    149149        } // ?+?
    150150
    151         Rational(T) ?+=?( Rational(T) & l, one_t ) {
    152                 l = l + (Rational(T)){ 1 };
     151        rational(T) ?+=?( rational(T) & l, one_t ) {
     152                l = l + (rational(T)){ 1 };
    153153                return l;
    154154        } // ?+?
    155155
    156         Rational(T) ?-?( Rational(T) l, Rational(T) r ) {
     156        rational(T) ?-?( rational(T) l, rational(T) r ) {
    157157                if ( l.denominator == r.denominator ) {                 // special case
    158                         return (Rational(T)){ l.numerator - r.numerator, l.denominator };
     158                        return (rational(T)){ l.numerator - r.numerator, l.denominator };
    159159                } else {
    160                         return (Rational(T)){ l.numerator * r.denominator - l.denominator * r.numerator, l.denominator * r.denominator };
     160                        return (rational(T)){ l.numerator * r.denominator - l.denominator * r.numerator, l.denominator * r.denominator };
    161161                } // if
    162162        } // ?-?
    163163
    164         Rational(T) ?-=?( Rational(T) & l, Rational(T) r ) {
     164        rational(T) ?-=?( rational(T) & l, rational(T) r ) {
    165165                l = l - r;
    166166                return l;
    167167        } // ?-?
    168168
    169         Rational(T) ?-=?( Rational(T) & l, one_t ) {
    170                 l = l - (Rational(T)){ 1 };
     169        rational(T) ?-=?( rational(T) & l, one_t ) {
     170                l = l - (rational(T)){ 1 };
    171171                return l;
    172172        } // ?-?
    173173
    174         Rational(T) ?*?( Rational(T) l, Rational(T) r ) {
    175                 return (Rational(T)){ l.numerator * r.numerator, l.denominator * r.denominator };
     174        rational(T) ?*?( rational(T) l, rational(T) r ) {
     175                return (rational(T)){ l.numerator * r.numerator, l.denominator * r.denominator };
    176176        } // ?*?
    177177
    178         Rational(T) ?*=?( Rational(T) & l, Rational(T) r ) {
     178        rational(T) ?*=?( rational(T) & l, rational(T) r ) {
    179179                return l = l * r;
    180180        } // ?*?
    181181
    182         Rational(T) ?/?( Rational(T) l, Rational(T) r ) {
     182        rational(T) ?/?( rational(T) l, rational(T) r ) {
    183183                if ( r.numerator < (T){0} ) {
    184184                        r.[numerator, denominator] = [-r.numerator, -r.denominator];
    185185                } // if
    186                 return (Rational(T)){ l.numerator * r.denominator, l.denominator * r.numerator };
     186                return (rational(T)){ l.numerator * r.denominator, l.denominator * r.numerator };
    187187        } // ?/?
    188188
    189         Rational(T) ?/=?( Rational(T) & l, Rational(T) r ) {
     189        rational(T) ?/=?( rational(T) & l, rational(T) r ) {
    190190                return l = l / r;
    191191        } // ?/?
     
    194194
    195195        forall( istype & | istream( istype ) | { istype & ?|?( istype &, T & ); } )
    196         istype & ?|?( istype & is, Rational(T) & r ) {
     196        istype & ?|?( istype & is, rational(T) & r ) {
    197197                is | r.numerator | r.denominator;
    198198                T t = simplify( r.numerator, r.denominator );
     
    203203
    204204        forall( ostype & | ostream( ostype ) | { ostype & ?|?( ostype &, T ); } ) {
    205                 ostype & ?|?( ostype & os, Rational(T) r ) {
     205                ostype & ?|?( ostype & os, rational(T) r ) {
    206206                        return os | r.numerator | '/' | r.denominator;
    207207                } // ?|?
    208208
    209                 void ?|?( ostype & os, Rational(T) r ) {
     209                void ?|?( ostype & os, rational(T) r ) {
    210210                        (ostype &)(os | r); ends( os );
    211211                } // ?|?
     
    213213} // distribution
    214214
    215 forall( T | Arithmetic( T ) | { T ?\?( T, unsigned long ); } ) {
    216         Rational(T) ?\?( Rational(T) x, long int y ) {
     215forall( T | arithmetic( T ) | { T ?\?( T, unsigned long ); } ) {
     216        rational(T) ?\?( rational(T) x, long int y ) {
    217217                if ( y < 0 ) {
    218                         return (Rational(T)){ x.denominator \ -y, x.numerator \ -y };
     218                        return (rational(T)){ x.denominator \ -y, x.numerator \ -y };
    219219                } else {
    220                         return (Rational(T)){ x.numerator \ y, x.denominator \ y };
     220                        return (rational(T)){ x.numerator \ y, x.denominator \ y };
    221221                } // if
    222222        } // ?\?
    223223
    224         Rational(T) ?\=?( Rational(T) & x, long int y ) {
     224        rational(T) ?\=?( rational(T) & x, long int y ) {
    225225                return x = x \ y;
    226226        } // ?\?
     
    229229// conversion
    230230
    231 forall( T | Arithmetic( T ) | { double convert( T ); } )
    232 double widen( Rational(T) r ) {
     231forall( T | arithmetic( T ) | { double convert( T ); } )
     232double widen( rational(T) r ) {
    233233        return convert( r.numerator ) / convert( r.denominator );
    234234} // widen
    235235
    236 forall( T | Arithmetic( T ) | { double convert( T ); T convert( double ); } )
    237 Rational(T) narrow( double f, T md ) {
     236forall( T | arithmetic( T ) | { double convert( T ); T convert( double ); } )
     237rational(T) narrow( double f, T md ) {
    238238        // http://www.ics.uci.edu/~eppstein/numth/frap.c
    239         if ( md <= (T){1} ) {                                   // maximum fractional digits too small?
    240                 return (Rational(T)){ convert( f ), (T){1}}; // truncate fraction
     239        if ( md <= (T){1} ) {                                                           // maximum fractional digits too small?
     240                return (rational(T)){ convert( f ), (T){1}};    // truncate fraction
    241241        } // if
    242242
     
    260260          if ( f > (double)0x7FFFFFFF ) break;                          // representation failure
    261261        } // for
    262         return (Rational(T)){ m00, m10 };
     262        return (rational(T)){ m00, m10 };
    263263} // narrow
    264264
  • libcfa/src/rational.hfa

    r24d6572 r62d62db  
    1212// Created On       : Wed Apr  6 17:56:25 2016
    1313// Last Modified By : Peter A. Buhr
    14 // Last Modified On : Tue Jul 20 17:45:29 2021
    15 // Update Count     : 118
     14// Last Modified On : Mon Jun  5 22:49:05 2023
     15// Update Count     : 119
    1616//
    1717
     
    1919
    2020#include "iostream.hfa"
    21 #include "math.trait.hfa"                                                               // Arithmetic
     21#include "math.trait.hfa"                                                               // arithmetic
    2222
    2323// implementation
    2424
    25 forall( T | Arithmetic( T ) ) {
    26         struct Rational {
     25forall( T | arithmetic( T ) ) {
     26        struct rational {
    2727                T numerator, denominator;                                               // invariant: denominator > 0
    28         }; // Rational
     28        }; // rational
    2929
    3030        // constructors
    3131
    32         void ?{}( Rational(T) & r );
    33         void ?{}( Rational(T) & r, zero_t );
    34         void ?{}( Rational(T) & r, one_t );
    35         void ?{}( Rational(T) & r, T n );
    36         void ?{}( Rational(T) & r, T n, T d );
     32        void ?{}( rational(T) & r );
     33        void ?{}( rational(T) & r, zero_t );
     34        void ?{}( rational(T) & r, one_t );
     35        void ?{}( rational(T) & r, T n );
     36        void ?{}( rational(T) & r, T n, T d );
    3737
    3838        // numerator/denominator getter
    3939
    40         T numerator( Rational(T) r );
    41         T denominator( Rational(T) r );
    42         [ T, T ] ?=?( & [ T, T ] dest, Rational(T) src );
     40        T numerator( rational(T) r );
     41        T denominator( rational(T) r );
     42        [ T, T ] ?=?( & [ T, T ] dest, rational(T) src );
    4343
    4444        // numerator/denominator setter
    4545
    46         T numerator( Rational(T) r, T n );
    47         T denominator( Rational(T) r, T d );
     46        T numerator( rational(T) r, T n );
     47        T denominator( rational(T) r, T d );
    4848
    4949        // comparison
    5050
    51         int ?==?( Rational(T) l, Rational(T) r );
    52         int ?!=?( Rational(T) l, Rational(T) r );
    53         int ?!=?( Rational(T) l, zero_t );                                      // => !
    54         int ?<?( Rational(T) l, Rational(T) r );
    55         int ?<=?( Rational(T) l, Rational(T) r );
    56         int ?>?( Rational(T) l, Rational(T) r );
    57         int ?>=?( Rational(T) l, Rational(T) r );
     51        int ?==?( rational(T) l, rational(T) r );
     52        int ?!=?( rational(T) l, rational(T) r );
     53        int ?!=?( rational(T) l, zero_t );                                      // => !
     54        int ?<?( rational(T) l, rational(T) r );
     55        int ?<=?( rational(T) l, rational(T) r );
     56        int ?>?( rational(T) l, rational(T) r );
     57        int ?>=?( rational(T) l, rational(T) r );
    5858
    5959        // arithmetic
    6060
    61         Rational(T) +?( Rational(T) r );
    62         Rational(T) -?( Rational(T) r );
    63         Rational(T) ?+?( Rational(T) l, Rational(T) r );
    64         Rational(T) ?+=?( Rational(T) & l, Rational(T) r );
    65         Rational(T) ?+=?( Rational(T) & l, one_t );                     // => ++?, ?++
    66         Rational(T) ?-?( Rational(T) l, Rational(T) r );
    67         Rational(T) ?-=?( Rational(T) & l, Rational(T) r );
    68         Rational(T) ?-=?( Rational(T) & l, one_t );                     // => --?, ?--
    69         Rational(T) ?*?( Rational(T) l, Rational(T) r );
    70         Rational(T) ?*=?( Rational(T) & l, Rational(T) r );
    71         Rational(T) ?/?( Rational(T) l, Rational(T) r );
    72         Rational(T) ?/=?( Rational(T) & l, Rational(T) r );
     61        rational(T) +?( rational(T) r );
     62        rational(T) -?( rational(T) r );
     63        rational(T) ?+?( rational(T) l, rational(T) r );
     64        rational(T) ?+=?( rational(T) & l, rational(T) r );
     65        rational(T) ?+=?( rational(T) & l, one_t );                     // => ++?, ?++
     66        rational(T) ?-?( rational(T) l, rational(T) r );
     67        rational(T) ?-=?( rational(T) & l, rational(T) r );
     68        rational(T) ?-=?( rational(T) & l, one_t );                     // => --?, ?--
     69        rational(T) ?*?( rational(T) l, rational(T) r );
     70        rational(T) ?*=?( rational(T) & l, rational(T) r );
     71        rational(T) ?/?( rational(T) l, rational(T) r );
     72        rational(T) ?/=?( rational(T) & l, rational(T) r );
    7373
    7474        // I/O
    7575        forall( istype & | istream( istype ) | { istype & ?|?( istype &, T & ); } )
    76         istype & ?|?( istype &, Rational(T) & );
     76        istype & ?|?( istype &, rational(T) & );
    7777
    7878        forall( ostype & | ostream( ostype ) | { ostype & ?|?( ostype &, T ); } ) {
    79                 ostype & ?|?( ostype &, Rational(T) );
    80                 void ?|?( ostype &, Rational(T) );
     79                ostype & ?|?( ostype &, rational(T) );
     80                void ?|?( ostype &, rational(T) );
    8181        } // distribution
    8282} // distribution
    8383
    84 forall( T | Arithmetic( T ) | { T ?\?( T, unsigned long ); } ) {
    85         Rational(T) ?\?( Rational(T) x, long int y );
    86         Rational(T) ?\=?( Rational(T) & x, long int y );
     84forall( T | arithmetic( T ) | { T ?\?( T, unsigned long ); } ) {
     85        rational(T) ?\?( rational(T) x, long int y );
     86        rational(T) ?\=?( rational(T) & x, long int y );
    8787} // distribution
    8888
    8989// conversion
    90 forall( T | Arithmetic( T ) | { double convert( T ); } )
    91 double widen( Rational(T) r );
    92 forall( T | Arithmetic( T ) | { double convert( T );  T convert( double );} )
    93 Rational(T) narrow( double f, T md );
     90forall( T | arithmetic( T ) | { double convert( T ); } )
     91double widen( rational(T) r );
     92forall( T | arithmetic( T ) | { double convert( T );  T convert( double );} )
     93rational(T) narrow( double f, T md );
    9494
    9595// Local Variables: //
  • src/AST/DeclReplacer.hpp

    r24d6572 r62d62db  
    1818#include <unordered_map>
    1919
    20 #include "Node.hpp"
     20namespace ast {
     21        class DeclWithType;
     22        class Expr;
     23        class Node;
     24        class TypeDecl;
     25}
    2126
    2227namespace ast {
    23         class DeclWithType;
    24         class TypeDecl;
    25         class Expr;
    2628
    27         namespace DeclReplacer {
    28                 using DeclMap = std::unordered_map< const DeclWithType *, const DeclWithType * >;
    29                 using TypeMap = std::unordered_map< const TypeDecl *, const TypeDecl * >;
    30                 using ExprMap = std::unordered_map< const DeclWithType *, const Expr * >;
     29namespace DeclReplacer {
    3130
    32                 const Node * replace( const Node * node, const DeclMap & declMap, bool debug = false );
    33                 const Node * replace( const Node * node, const TypeMap & typeMap, bool debug = false );
    34                 const Node * replace( const Node * node, const DeclMap & declMap, const TypeMap & typeMap, bool debug = false );
    35                 const Node * replace( const Node * node, const ExprMap & exprMap);
    36         }
     31using DeclMap = std::unordered_map< const DeclWithType *, const DeclWithType * >;
     32using TypeMap = std::unordered_map< const TypeDecl *, const TypeDecl * >;
     33using ExprMap = std::unordered_map< const DeclWithType *, const Expr * >;
     34
     35const Node * replace( const Node * node, const DeclMap & declMap, bool debug = false );
     36const Node * replace( const Node * node, const TypeMap & typeMap, bool debug = false );
     37const Node * replace( const Node * node, const DeclMap & declMap, const TypeMap & typeMap, bool debug = false );
     38const Node * replace( const Node * node, const ExprMap & exprMap);
     39
     40}
     41
    3742}
    3843
  • src/AST/Pass.hpp

    r24d6572 r62d62db  
    414414};
    415415
    416 /// Use when the templated visitor should update the symbol table
     416/// Use when the templated visitor should update the symbol table,
     417/// that is, when your pass core needs to query the symbol table.
     418/// Expected setups:
     419/// - For master passes that kick off at the compilation unit
     420///   - before resolver: extend WithSymbolTableX<IgnoreErrors>
     421///   - after resolver: extend WithSymbolTable and use defaults
     422///   - (FYI, for completeness, the resolver's main pass uses ValidateOnAdd when it kicks off)
     423/// - For helper passes that kick off at arbitrary points in the AST:
     424///   - take an existing symbol table as a parameter, extend WithSymbolTable,
     425///     and construct with WithSymbolTable(const SymbolTable &)
    417426struct WithSymbolTable {
    418         SymbolTable symtab;
     427        WithSymbolTable(const ast::SymbolTable & from) : symtab(from) {}
     428        WithSymbolTable(ast::SymbolTable::ErrorDetection errorMode = ast::SymbolTable::ErrorDetection::AssertClean) : symtab(errorMode) {}
     429        ast::SymbolTable symtab;
     430};
     431template <ast::SymbolTable::ErrorDetection errorMode>
     432struct WithSymbolTableX : WithSymbolTable {
     433        WithSymbolTableX() : WithSymbolTable(errorMode) {}
    419434};
    420435
  • src/AST/Pass.impl.hpp

    r24d6572 r62d62db  
    7272                template<typename it_t, template <class...> class container_t>
    7373                static inline void take_all( it_t it, container_t<ast::ptr<ast::Decl>> * decls, bool * mutated = nullptr ) {
    74                         if(empty(decls)) return;
     74                        if ( empty( decls ) ) return;
    7575
    7676                        std::transform(decls->begin(), decls->end(), it, [](const ast::Decl * decl) -> auto {
     
    7878                                });
    7979                        decls->clear();
    80                         if(mutated) *mutated = true;
     80                        if ( mutated ) *mutated = true;
    8181                }
    8282
    8383                template<typename it_t, template <class...> class container_t>
    8484                static inline void take_all( it_t it, container_t<ast::ptr<ast::Stmt>> * stmts, bool * mutated = nullptr ) {
    85                         if(empty(stmts)) return;
     85                        if ( empty( stmts ) ) return;
    8686
    8787                        std::move(stmts->begin(), stmts->end(), it);
    8888                        stmts->clear();
    89                         if(mutated) *mutated = true;
     89                        if ( mutated ) *mutated = true;
    9090                }
    9191
     
    9393                /// Check if should be skipped, different for pointers and containers
    9494                template<typename node_t>
    95                 bool skip( const ast::ptr<node_t> & val) {
     95                bool skip( const ast::ptr<node_t> & val ) {
    9696                        return !val;
    9797                }
     
    110110
    111111                template<typename node_t>
    112                 const node_t & get( const node_t & val, long) {
     112                const node_t & get( const node_t & val, long ) {
    113113                        return val;
    114114                }
     
    126126                }
    127127        }
    128 
    129         template< typename core_t >
    130         template< typename node_t >
    131         auto ast::Pass< core_t >::call_accept( const node_t * node )
    132                 -> typename ast::Pass< core_t >::template generic_call_accept_result<node_t>::type
    133         {
    134                 __pedantic_pass_assert( __visit_children() );
    135                 __pedantic_pass_assert( node );
    136 
    137                 static_assert( !std::is_base_of<ast::Expr, node_t>::value, "ERROR");
    138                 static_assert( !std::is_base_of<ast::Stmt, node_t>::value, "ERROR");
    139 
    140                 auto nval = node->accept( *this );
    141                 __pass::result1<
    142                         typename std::remove_pointer< decltype( node->accept(*this) ) >::type
    143                 > res;
    144                 res.differs = nval != node;
    145                 res.value = nval;
    146                 return res;
    147         }
    148 
    149         template< typename core_t >
    150         __pass::template result1<ast::Expr> ast::Pass< core_t >::call_accept( const ast::Expr * expr ) {
    151                 __pedantic_pass_assert( __visit_children() );
    152                 __pedantic_pass_assert( expr );
    153 
    154                 auto nval = expr->accept( *this );
    155                 return { nval != expr, nval };
    156         }
    157 
    158         template< typename core_t >
    159         __pass::template result1<ast::Stmt> ast::Pass< core_t >::call_accept( const ast::Stmt * stmt ) {
    160                 __pedantic_pass_assert( __visit_children() );
    161                 __pedantic_pass_assert( stmt );
    162 
    163                 const ast::Stmt * nval = stmt->accept( *this );
    164                 return { nval != stmt, nval };
    165         }
    166 
    167         template< typename core_t >
    168         __pass::template result1<ast::Expr> ast::Pass< core_t >::call_accept_top( const ast::Expr * expr ) {
    169                 __pedantic_pass_assert( __visit_children() );
    170                 __pedantic_pass_assert( expr );
    171 
    172                 const ast::TypeSubstitution ** typeSubs_ptr = __pass::typeSubs( core, 0 );
    173                 if ( typeSubs_ptr && expr->env ) {
    174                         *typeSubs_ptr = expr->env;
    175                 }
    176 
    177                 auto nval = expr->accept( *this );
    178                 return { nval != expr, nval };
    179         }
    180 
    181         template< typename core_t >
    182         __pass::template result1<ast::Stmt> ast::Pass< core_t >::call_accept_as_compound( const ast::Stmt * stmt ) {
    183                 __pedantic_pass_assert( __visit_children() );
    184                 __pedantic_pass_assert( stmt );
    185 
    186                 // add a few useful symbols to the scope
    187                 using __pass::empty;
    188 
    189                 // get the stmts/decls that will need to be spliced in
    190                 auto stmts_before = __pass::stmtsToAddBefore( core, 0 );
    191                 auto stmts_after  = __pass::stmtsToAddAfter ( core, 0 );
    192                 auto decls_before = __pass::declsToAddBefore( core, 0 );
    193                 auto decls_after  = __pass::declsToAddAfter ( core, 0 );
    194 
    195                 // These may be modified by subnode but most be restored once we exit this statemnet.
    196                 ValueGuardPtr< const ast::TypeSubstitution * > __old_env         ( __pass::typeSubs( core, 0 ) );
    197                 ValueGuardPtr< typename std::remove_pointer< decltype(stmts_before) >::type > __old_decls_before( stmts_before );
    198                 ValueGuardPtr< typename std::remove_pointer< decltype(stmts_after ) >::type > __old_decls_after ( stmts_after  );
    199                 ValueGuardPtr< typename std::remove_pointer< decltype(decls_before) >::type > __old_stmts_before( decls_before );
    200                 ValueGuardPtr< typename std::remove_pointer< decltype(decls_after ) >::type > __old_stmts_after ( decls_after  );
    201 
    202                 // Now is the time to actually visit the node
    203                 const ast::Stmt * nstmt = stmt->accept( *this );
    204 
    205                 // If the pass doesn't want to add anything then we are done
    206                 if( empty(stmts_before) && empty(stmts_after) && empty(decls_before) && empty(decls_after) ) {
    207                         return { nstmt != stmt, nstmt };
    208                 }
    209 
    210                 // Make sure that it is either adding statements or declartions but not both
    211                 // this is because otherwise the order would be awkward to predict
    212                 assert(( empty( stmts_before ) && empty( stmts_after ))
    213                     || ( empty( decls_before ) && empty( decls_after )) );
    214 
    215                 // Create a new Compound Statement to hold the new decls/stmts
    216                 ast::CompoundStmt * compound = new ast::CompoundStmt( stmt->location );
    217 
    218                 // Take all the declarations that go before
    219                 __pass::take_all( std::back_inserter( compound->kids ), decls_before );
    220                 __pass::take_all( std::back_inserter( compound->kids ), stmts_before );
    221 
    222                 // Insert the original declaration
    223                 compound->kids.emplace_back( nstmt );
    224 
    225                 // Insert all the declarations that go before
    226                 __pass::take_all( std::back_inserter( compound->kids ), decls_after );
    227                 __pass::take_all( std::back_inserter( compound->kids ), stmts_after );
    228 
    229                 return {true, compound};
    230         }
    231 
    232         template< typename core_t >
    233         template< template <class...> class container_t >
    234         __pass::template resultNstmt<container_t> ast::Pass< core_t >::call_accept( const container_t< ptr<Stmt> > & statements ) {
    235                 __pedantic_pass_assert( __visit_children() );
    236                 if( statements.empty() ) return {};
    237 
    238                 // We are going to aggregate errors for all these statements
    239                 SemanticErrorException errors;
    240 
    241                 // add a few useful symbols to the scope
    242                 using __pass::empty;
    243 
    244                 // get the stmts/decls that will need to be spliced in
    245                 auto stmts_before = __pass::stmtsToAddBefore( core, 0 );
    246                 auto stmts_after  = __pass::stmtsToAddAfter ( core, 0 );
    247                 auto decls_before = __pass::declsToAddBefore( core, 0 );
    248                 auto decls_after  = __pass::declsToAddAfter ( core, 0 );
    249 
    250                 // These may be modified by subnode but most be restored once we exit this statemnet.
    251                 ValueGuardPtr< typename std::remove_pointer< decltype(stmts_before) >::type > __old_decls_before( stmts_before );
    252                 ValueGuardPtr< typename std::remove_pointer< decltype(stmts_after ) >::type > __old_decls_after ( stmts_after  );
    253                 ValueGuardPtr< typename std::remove_pointer< decltype(decls_before) >::type > __old_stmts_before( decls_before );
    254                 ValueGuardPtr< typename std::remove_pointer< decltype(decls_after ) >::type > __old_stmts_after ( decls_after  );
    255 
    256                 // update pass statitistics
    257                 pass_visitor_stats.depth++;
    258                 pass_visitor_stats.max->push(pass_visitor_stats.depth);
    259                 pass_visitor_stats.avg->push(pass_visitor_stats.depth);
    260 
    261                 __pass::resultNstmt<container_t> new_kids;
    262                 for( auto value : enumerate( statements ) ) {
    263                         try {
    264                                 size_t i = value.idx;
    265                                 const Stmt * stmt = value.val;
    266                                 __pedantic_pass_assert( stmt );
    267                                 const ast::Stmt * new_stmt = stmt->accept( *this );
    268                                 assert( new_stmt );
    269                                 if(new_stmt != stmt ) { new_kids.differs = true; }
    270 
    271                                 // Make sure that it is either adding statements or declartions but not both
    272                                 // this is because otherwise the order would be awkward to predict
    273                                 assert(( empty( stmts_before ) && empty( stmts_after ))
    274                                     || ( empty( decls_before ) && empty( decls_after )) );
    275 
    276                                 // Take all the statements which should have gone after, N/A for first iteration
    277                                 new_kids.take_all( decls_before );
    278                                 new_kids.take_all( stmts_before );
    279 
    280                                 // Now add the statement if there is one
    281                                 if(new_stmt != stmt) {
    282                                         new_kids.values.emplace_back( new_stmt, i, false );
    283                                 } else {
    284                                         new_kids.values.emplace_back( nullptr, i, true );
    285                                 }
    286 
    287                                 // Take all the declarations that go before
    288                                 new_kids.take_all( decls_after );
    289                                 new_kids.take_all( stmts_after );
     128}
     129
     130template< typename core_t >
     131template< typename node_t >
     132auto ast::Pass< core_t >::call_accept( const node_t * node ) ->
     133        typename ast::Pass< core_t >::template generic_call_accept_result<node_t>::type
     134{
     135        __pedantic_pass_assert( __visit_children() );
     136        __pedantic_pass_assert( node );
     137
     138        static_assert( !std::is_base_of<ast::Expr, node_t>::value, "ERROR" );
     139        static_assert( !std::is_base_of<ast::Stmt, node_t>::value, "ERROR" );
     140
     141        auto nval = node->accept( *this );
     142        __pass::result1<
     143                typename std::remove_pointer< decltype( node->accept(*this) ) >::type
     144        > res;
     145        res.differs = nval != node;
     146        res.value = nval;
     147        return res;
     148}
     149
     150template< typename core_t >
     151ast::__pass::template result1<ast::Expr> ast::Pass< core_t >::call_accept( const ast::Expr * expr ) {
     152        __pedantic_pass_assert( __visit_children() );
     153        __pedantic_pass_assert( expr );
     154
     155        auto nval = expr->accept( *this );
     156        return { nval != expr, nval };
     157}
     158
     159template< typename core_t >
     160ast::__pass::template result1<ast::Stmt> ast::Pass< core_t >::call_accept( const ast::Stmt * stmt ) {
     161        __pedantic_pass_assert( __visit_children() );
     162        __pedantic_pass_assert( stmt );
     163
     164        const ast::Stmt * nval = stmt->accept( *this );
     165        return { nval != stmt, nval };
     166}
     167
     168template< typename core_t >
     169ast::__pass::template result1<ast::Expr> ast::Pass< core_t >::call_accept_top( const ast::Expr * expr ) {
     170        __pedantic_pass_assert( __visit_children() );
     171        __pedantic_pass_assert( expr );
     172
     173        const ast::TypeSubstitution ** typeSubs_ptr = __pass::typeSubs( core, 0 );
     174        if ( typeSubs_ptr && expr->env ) {
     175                *typeSubs_ptr = expr->env;
     176        }
     177
     178        auto nval = expr->accept( *this );
     179        return { nval != expr, nval };
     180}
     181
     182template< typename core_t >
     183ast::__pass::template result1<ast::Stmt> ast::Pass< core_t >::call_accept_as_compound( const ast::Stmt * stmt ) {
     184        __pedantic_pass_assert( __visit_children() );
     185        __pedantic_pass_assert( stmt );
     186
     187        // add a few useful symbols to the scope
     188        using __pass::empty;
     189
     190        // get the stmts/decls that will need to be spliced in
     191        auto stmts_before = __pass::stmtsToAddBefore( core, 0 );
     192        auto stmts_after  = __pass::stmtsToAddAfter ( core, 0 );
     193        auto decls_before = __pass::declsToAddBefore( core, 0 );
     194        auto decls_after  = __pass::declsToAddAfter ( core, 0 );
     195
     196        // These may be modified by subnode but most be restored once we exit this statemnet.
     197        ValueGuardPtr< const ast::TypeSubstitution * > __old_env         ( __pass::typeSubs( core, 0 ) );
     198        ValueGuardPtr< typename std::remove_pointer< decltype(stmts_before) >::type > __old_decls_before( stmts_before );
     199        ValueGuardPtr< typename std::remove_pointer< decltype(stmts_after ) >::type > __old_decls_after ( stmts_after  );
     200        ValueGuardPtr< typename std::remove_pointer< decltype(decls_before) >::type > __old_stmts_before( decls_before );
     201        ValueGuardPtr< typename std::remove_pointer< decltype(decls_after ) >::type > __old_stmts_after ( decls_after  );
     202
     203        // Now is the time to actually visit the node
     204        const ast::Stmt * nstmt = stmt->accept( *this );
     205
     206        // If the pass doesn't want to add anything then we are done
     207        if ( empty(stmts_before) && empty(stmts_after) && empty(decls_before) && empty(decls_after) ) {
     208                return { nstmt != stmt, nstmt };
     209        }
     210
     211        // Make sure that it is either adding statements or declartions but not both
     212        // this is because otherwise the order would be awkward to predict
     213        assert(( empty( stmts_before ) && empty( stmts_after ))
     214            || ( empty( decls_before ) && empty( decls_after )) );
     215
     216        // Create a new Compound Statement to hold the new decls/stmts
     217        ast::CompoundStmt * compound = new ast::CompoundStmt( stmt->location );
     218
     219        // Take all the declarations that go before
     220        __pass::take_all( std::back_inserter( compound->kids ), decls_before );
     221        __pass::take_all( std::back_inserter( compound->kids ), stmts_before );
     222
     223        // Insert the original declaration
     224        compound->kids.emplace_back( nstmt );
     225
     226        // Insert all the declarations that go before
     227        __pass::take_all( std::back_inserter( compound->kids ), decls_after );
     228        __pass::take_all( std::back_inserter( compound->kids ), stmts_after );
     229
     230        return { true, compound };
     231}
     232
     233template< typename core_t >
     234template< template <class...> class container_t >
     235ast::__pass::template resultNstmt<container_t> ast::Pass< core_t >::call_accept( const container_t< ptr<Stmt> > & statements ) {
     236        __pedantic_pass_assert( __visit_children() );
     237        if ( statements.empty() ) return {};
     238
     239        // We are going to aggregate errors for all these statements
     240        SemanticErrorException errors;
     241
     242        // add a few useful symbols to the scope
     243        using __pass::empty;
     244
     245        // get the stmts/decls that will need to be spliced in
     246        auto stmts_before = __pass::stmtsToAddBefore( core, 0 );
     247        auto stmts_after  = __pass::stmtsToAddAfter ( core, 0 );
     248        auto decls_before = __pass::declsToAddBefore( core, 0 );
     249        auto decls_after  = __pass::declsToAddAfter ( core, 0 );
     250
     251        // These may be modified by subnode but most be restored once we exit this statemnet.
     252        ValueGuardPtr< typename std::remove_pointer< decltype(stmts_before) >::type > __old_decls_before( stmts_before );
     253        ValueGuardPtr< typename std::remove_pointer< decltype(stmts_after ) >::type > __old_decls_after ( stmts_after  );
     254        ValueGuardPtr< typename std::remove_pointer< decltype(decls_before) >::type > __old_stmts_before( decls_before );
     255        ValueGuardPtr< typename std::remove_pointer< decltype(decls_after ) >::type > __old_stmts_after ( decls_after  );
     256
     257        // update pass statitistics
     258        pass_visitor_stats.depth++;
     259        pass_visitor_stats.max->push(pass_visitor_stats.depth);
     260        pass_visitor_stats.avg->push(pass_visitor_stats.depth);
     261
     262        __pass::resultNstmt<container_t> new_kids;
     263        for ( auto value : enumerate( statements ) ) {
     264                try {
     265                        size_t i = value.idx;
     266                        const Stmt * stmt = value.val;
     267                        __pedantic_pass_assert( stmt );
     268                        const ast::Stmt * new_stmt = stmt->accept( *this );
     269                        assert( new_stmt );
     270                        if ( new_stmt != stmt ) { new_kids.differs = true; }
     271
     272                        // Make sure that it is either adding statements or declartions but not both
     273                        // this is because otherwise the order would be awkward to predict
     274                        assert(( empty( stmts_before ) && empty( stmts_after ))
     275                            || ( empty( decls_before ) && empty( decls_after )) );
     276
     277                        // Take all the statements which should have gone after, N/A for first iteration
     278                        new_kids.take_all( decls_before );
     279                        new_kids.take_all( stmts_before );
     280
     281                        // Now add the statement if there is one
     282                        if ( new_stmt != stmt ) {
     283                                new_kids.values.emplace_back( new_stmt, i, false );
     284                        } else {
     285                                new_kids.values.emplace_back( nullptr, i, true );
    290286                        }
    291                         catch ( SemanticErrorException &e ) {
    292                                 errors.append( e );
     287
     288                        // Take all the declarations that go before
     289                        new_kids.take_all( decls_after );
     290                        new_kids.take_all( stmts_after );
     291                } catch ( SemanticErrorException &e ) {
     292                        errors.append( e );
     293                }
     294        }
     295        pass_visitor_stats.depth--;
     296        if ( !errors.isEmpty() ) { throw errors; }
     297
     298        return new_kids;
     299}
     300
     301template< typename core_t >
     302template< template <class...> class container_t, typename node_t >
     303ast::__pass::template resultN<container_t, node_t> ast::Pass< core_t >::call_accept( const container_t< ast::ptr<node_t> > & container ) {
     304        __pedantic_pass_assert( __visit_children() );
     305        if ( container.empty() ) return {};
     306        SemanticErrorException errors;
     307
     308        pass_visitor_stats.depth++;
     309        pass_visitor_stats.max->push(pass_visitor_stats.depth);
     310        pass_visitor_stats.avg->push(pass_visitor_stats.depth);
     311
     312        bool mutated = false;
     313        container_t<ptr<node_t>> new_kids;
     314        for ( const node_t * node : container ) {
     315                try {
     316                        __pedantic_pass_assert( node );
     317                        const node_t * new_stmt = strict_dynamic_cast< const node_t * >( node->accept( *this ) );
     318                        if ( new_stmt != node ) {
     319                                mutated = true;
     320                                new_kids.emplace_back( new_stmt );
     321                        } else {
     322                                new_kids.emplace_back( nullptr );
    293323                        }
    294                 }
    295                 pass_visitor_stats.depth--;
    296                 if ( !errors.isEmpty() ) { throw errors; }
    297 
    298                 return new_kids;
    299         }
    300 
    301         template< typename core_t >
    302         template< template <class...> class container_t, typename node_t >
    303         __pass::template resultN<container_t, node_t> ast::Pass< core_t >::call_accept( const container_t< ast::ptr<node_t> > & container ) {
    304                 __pedantic_pass_assert( __visit_children() );
    305                 if( container.empty() ) return {};
    306                 SemanticErrorException errors;
    307 
    308                 pass_visitor_stats.depth++;
    309                 pass_visitor_stats.max->push(pass_visitor_stats.depth);
    310                 pass_visitor_stats.avg->push(pass_visitor_stats.depth);
    311 
    312                 bool mutated = false;
    313                 container_t<ptr<node_t>> new_kids;
    314                 for ( const node_t * node : container ) {
    315                         try {
    316                                 __pedantic_pass_assert( node );
    317                                 const node_t * new_stmt = strict_dynamic_cast< const node_t * >( node->accept( *this ) );
    318                                 if(new_stmt != node ) {
    319                                         mutated = true;
    320                                         new_kids.emplace_back( new_stmt );
    321                                 } else {
    322                                         new_kids.emplace_back( nullptr );
    323                                 }
    324 
    325                         }
    326                         catch( SemanticErrorException &e ) {
    327                                 errors.append( e );
    328                         }
    329                 }
    330 
    331                 __pedantic_pass_assert( new_kids.size() == container.size() );
    332                 pass_visitor_stats.depth--;
    333                 if ( ! errors.isEmpty() ) { throw errors; }
    334 
    335                 return ast::__pass::resultN<container_t, node_t>{ mutated, new_kids };
    336         }
    337 
    338         template< typename core_t >
    339         template<typename node_t, typename super_t, typename field_t>
    340         void ast::Pass< core_t >::maybe_accept(
    341                 const node_t * & parent,
    342                 field_t super_t::*field
    343         ) {
    344                 static_assert( std::is_base_of<super_t, node_t>::value, "Error deducing member object" );
    345 
    346                 if(__pass::skip(parent->*field)) return;
    347                 const auto & old_val = __pass::get(parent->*field, 0);
    348 
    349                 static_assert( !std::is_same<const ast::Node * &, decltype(old_val)>::value, "ERROR");
    350 
    351                 auto new_val = call_accept( old_val );
    352 
    353                 static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value /* || std::is_same<int, decltype(old_val)>::value */, "ERROR");
    354 
    355                 if( new_val.differs ) {
    356                         auto new_parent = __pass::mutate<core_t>(parent);
    357                         new_val.apply(new_parent, field);
    358                         parent = new_parent;
    359                 }
    360         }
    361 
    362         template< typename core_t >
    363         template<typename node_t, typename super_t, typename field_t>
    364         void ast::Pass< core_t >::maybe_accept_top(
    365                 const node_t * & parent,
    366                 field_t super_t::*field
    367         ) {
    368                 static_assert( std::is_base_of<super_t, node_t>::value, "Error deducing member object" );
    369 
    370                 if(__pass::skip(parent->*field)) return;
    371                 const auto & old_val = __pass::get(parent->*field, 0);
    372 
    373                 static_assert( !std::is_same<const ast::Node * &, decltype(old_val)>::value, "ERROR");
    374 
    375                 auto new_val = call_accept_top( old_val );
    376 
    377                 static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value /* || std::is_same<int, decltype(old_val)>::value */, "ERROR");
    378 
    379                 if( new_val.differs ) {
    380                         auto new_parent = __pass::mutate<core_t>(parent);
    381                         new_val.apply(new_parent, field);
    382                         parent = new_parent;
    383                 }
    384         }
    385 
    386         template< typename core_t >
    387         template<typename node_t, typename super_t, typename field_t>
    388         void ast::Pass< core_t >::maybe_accept_as_compound(
    389                 const node_t * & parent,
    390                 field_t super_t::*child
    391         ) {
    392                 static_assert( std::is_base_of<super_t, node_t>::value, "Error deducing member object" );
    393 
    394                 if(__pass::skip(parent->*child)) return;
    395                 const auto & old_val = __pass::get(parent->*child, 0);
    396 
    397                 static_assert( !std::is_same<const ast::Node * &, decltype(old_val)>::value, "ERROR");
    398 
    399                 auto new_val = call_accept_as_compound( old_val );
    400 
    401                 static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value || std::is_same<int, decltype(old_val)>::value, "ERROR");
    402 
    403                 if( new_val.differs ) {
    404                         auto new_parent = __pass::mutate<core_t>(parent);
    405                         new_val.apply( new_parent, child );
    406                         parent = new_parent;
    407                 }
    408         }
    409 
     324                } catch ( SemanticErrorException &e ) {
     325                        errors.append( e );
     326                }
     327        }
     328
     329        __pedantic_pass_assert( new_kids.size() == container.size() );
     330        pass_visitor_stats.depth--;
     331        if ( !errors.isEmpty() ) { throw errors; }
     332
     333        return ast::__pass::resultN<container_t, node_t>{ mutated, new_kids };
     334}
     335
     336template< typename core_t >
     337template<typename node_t, typename super_t, typename field_t>
     338void ast::Pass< core_t >::maybe_accept(
     339        const node_t * & parent,
     340        field_t super_t::*field
     341) {
     342        static_assert( std::is_base_of<super_t, node_t>::value, "Error deducing member object" );
     343
     344        if ( __pass::skip( parent->*field ) ) return;
     345        const auto & old_val = __pass::get(parent->*field, 0);
     346
     347        static_assert( !std::is_same<const ast::Node * &, decltype(old_val)>::value, "ERROR" );
     348
     349        auto new_val = call_accept( old_val );
     350
     351        static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value /* || std::is_same<int, decltype(old_val)>::value */, "ERROR" );
     352
     353        if ( new_val.differs ) {
     354                auto new_parent = __pass::mutate<core_t>(parent);
     355                new_val.apply(new_parent, field);
     356                parent = new_parent;
     357        }
     358}
     359
     360template< typename core_t >
     361template<typename node_t, typename super_t, typename field_t>
     362void ast::Pass< core_t >::maybe_accept_top(
     363        const node_t * & parent,
     364        field_t super_t::*field
     365) {
     366        static_assert( std::is_base_of<super_t, node_t>::value, "Error deducing member object" );
     367
     368        if ( __pass::skip( parent->*field ) ) return;
     369        const auto & old_val = __pass::get(parent->*field, 0);
     370
     371        static_assert( !std::is_same<const ast::Node * &, decltype(old_val)>::value, "ERROR" );
     372
     373        auto new_val = call_accept_top( old_val );
     374
     375        static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value /* || std::is_same<int, decltype(old_val)>::value */, "ERROR" );
     376
     377        if ( new_val.differs ) {
     378                auto new_parent = __pass::mutate<core_t>(parent);
     379                new_val.apply(new_parent, field);
     380                parent = new_parent;
     381        }
     382}
     383
     384template< typename core_t >
     385template<typename node_t, typename super_t, typename field_t>
     386void ast::Pass< core_t >::maybe_accept_as_compound(
     387        const node_t * & parent,
     388        field_t super_t::*child
     389) {
     390        static_assert( std::is_base_of<super_t, node_t>::value, "Error deducing member object" );
     391
     392        if ( __pass::skip( parent->*child ) ) return;
     393        const auto & old_val = __pass::get(parent->*child, 0);
     394
     395        static_assert( !std::is_same<const ast::Node * &, decltype(old_val)>::value, "ERROR" );
     396
     397        auto new_val = call_accept_as_compound( old_val );
     398
     399        static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value || std::is_same<int, decltype(old_val)>::value, "ERROR" );
     400
     401        if ( new_val.differs ) {
     402                auto new_parent = __pass::mutate<core_t>(parent);
     403                new_val.apply( new_parent, child );
     404                parent = new_parent;
     405        }
    410406}
    411407
     
    761757
    762758        if ( __visit_children() ) {
    763                 // Do not enter (or leave) a new scope if atFunctionTop. Remember to save the result.
    764                 auto guard1 = makeFuncGuard( [this, enterScope = !this->atFunctionTop]() {
    765                         if ( enterScope ) {
    766                                 __pass::symtab::enter(core, 0);
    767                         }
    768                 }, [this, leaveScope = !this->atFunctionTop]() {
    769                         if ( leaveScope ) {
    770                                 __pass::symtab::leave(core, 0);
    771                         }
    772                 });
    773                 ValueGuard< bool > guard2( atFunctionTop );
    774                 atFunctionTop = false;
    775                 guard_scope guard3 { *this };
    776                 maybe_accept( node, &CompoundStmt::kids );
     759                // Do not enter (or leave) a new symbol table scope if atFunctionTop.
     760                // But always enter (and leave) a new general scope.
     761                if ( atFunctionTop ) {
     762                        ValueGuard< bool > guard1( atFunctionTop );
     763                        atFunctionTop = false;
     764                        guard_scope guard2( *this );
     765                        maybe_accept( node, &CompoundStmt::kids );
     766                } else {
     767                        guard_symtab guard1( *this );
     768                        guard_scope guard2( *this );
     769                        maybe_accept( node, &CompoundStmt::kids );
     770                }
    777771        }
    778772
  • src/AST/SymbolTable.cpp

    r24d6572 r62d62db  
    9191}
    9292
    93 SymbolTable::SymbolTable()
     93SymbolTable::SymbolTable( ErrorDetection errorMode )
    9494: idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable(),
    95   prevScope(), scope( 0 ), repScope( 0 ) { ++*stats().count; }
     95  prevScope(), scope( 0 ), repScope( 0 ), errorMode(errorMode) { ++*stats().count; }
    9696
    9797SymbolTable::~SymbolTable() { stats().size->push( idTable ? idTable->size() : 0 ); }
     98
     99void SymbolTable::OnFindError( CodeLocation location, std::string error ) const {
     100        assertf( errorMode != AssertClean, "Name collision/redefinition, found during a compilation phase where none should be possible.  Detail: %s", error.c_str() );
     101        if (errorMode == ValidateOnAdd) {
     102                SemanticError(location, error);
     103        }
     104        assertf( errorMode == IgnoreErrors, "Unrecognized symbol-table error mode %d", errorMode );
     105}
    98106
    99107void SymbolTable::enterScope() {
     
    274282}
    275283
    276 namespace {
    277         /// true if redeclaration conflict between two types
    278         bool addedTypeConflicts( const NamedTypeDecl * existing, const NamedTypeDecl * added ) {
    279                 if ( existing->base == nullptr ) {
    280                         return false;
    281                 } else if ( added->base == nullptr ) {
    282                         return true;
    283                 } else {
    284                         // typedef redeclarations are errors only if types are different
    285                         if ( ! ResolvExpr::typesCompatible( existing->base, added->base ) ) {
    286                                 SemanticError( added->location, "redeclaration of " + added->name );
    287                         }
    288                 }
    289                 // does not need to be added to the table if both existing and added have a base that are
    290                 // the same
     284bool SymbolTable::addedTypeConflicts(
     285                const NamedTypeDecl * existing, const NamedTypeDecl * added ) const {
     286        if ( existing->base == nullptr ) {
     287                return false;
     288        } else if ( added->base == nullptr ) {
    291289                return true;
    292         }
    293 
    294         /// true if redeclaration conflict between two aggregate declarations
    295         bool addedDeclConflicts( const AggregateDecl * existing, const AggregateDecl * added ) {
    296                 if ( ! existing->body ) {
    297                         return false;
    298                 } else if ( added->body ) {
    299                         SemanticError( added, "redeclaration of " );
    300                 }
    301                 return true;
    302         }
     290        } else {
     291                // typedef redeclarations are errors only if types are different
     292                if ( ! ResolvExpr::typesCompatible( existing->base, added->base ) ) {
     293                        OnFindError( added->location, "redeclaration of " + added->name );
     294                }
     295        }
     296        // does not need to be added to the table if both existing and added have a base that are
     297        // the same
     298        return true;
     299}
     300
     301bool SymbolTable::addedDeclConflicts(
     302                const AggregateDecl * existing, const AggregateDecl * added ) const {
     303        if ( ! existing->body ) {
     304                return false;
     305        } else if ( added->body ) {
     306                OnFindError( added, "redeclaration of " );
     307        }
     308        return true;
    303309}
    304310
     
    653659                if ( deleter && ! existing.deleter ) {
    654660                        if ( handleConflicts.mode == OnConflict::Error ) {
    655                                 SemanticError( added, "deletion of defined identifier " );
     661                                OnFindError( added, "deletion of defined identifier " );
    656662                        }
    657663                        return true;
    658664                } else if ( ! deleter && existing.deleter ) {
    659665                        if ( handleConflicts.mode == OnConflict::Error ) {
    660                                 SemanticError( added, "definition of deleted identifier " );
     666                                OnFindError( added, "definition of deleted identifier " );
    661667                        }
    662668                        return true;
     
    666672                if ( isDefinition( added ) && isDefinition( existing.id ) ) {
    667673                        if ( handleConflicts.mode == OnConflict::Error ) {
    668                                 SemanticError( added,
     674                                OnFindError( added,
    669675                                        isFunction( added ) ?
    670676                                                "duplicate function definition for " :
     
    675681        } else {
    676682                if ( handleConflicts.mode == OnConflict::Error ) {
    677                         SemanticError( added, "duplicate definition for " );
     683                        OnFindError( added, "duplicate definition for " );
    678684                }
    679685                return true;
     
    727733                // Check that a Cforall declaration doesn't override any C declaration
    728734                if ( hasCompatibleCDecl( name, mangleName ) ) {
    729                         SemanticError( decl, "Cforall declaration hides C function " );
     735                        OnFindError( decl, "Cforall declaration hides C function " );
    730736                }
    731737        } else {
     
    733739                // type-compatibility, which it may not be.
    734740                if ( hasIncompatibleCDecl( name, mangleName ) ) {
    735                         SemanticError( decl, "conflicting overload of C function " );
     741                        OnFindError( decl, "conflicting overload of C function " );
    736742                }
    737743        }
  • src/AST/SymbolTable.hpp

    r24d6572 r62d62db  
    9393
    9494public:
    95         SymbolTable();
     95
     96        /// Mode to control when (during which pass) user-caused name-declaration errors get reported.
     97        /// The default setting `AssertClean` supports, "I expect all user-caused errors to have been
     98        /// reported by now," or, "I wouldn't know what to do with an error; are there even any here?"
     99        enum ErrorDetection {
     100                AssertClean,               ///< invalid user decls => assert fails during addFoo (default)
     101                ValidateOnAdd,             ///< invalid user decls => calls SemanticError during addFoo
     102                IgnoreErrors               ///< acts as if unspecified decls were removed, forcing validity
     103        };
     104
     105        explicit SymbolTable(
     106                ErrorDetection             ///< mode for the lifetime of the symbol table (whole pass)
     107        );
     108        SymbolTable() : SymbolTable(AssertClean) {}
    96109        ~SymbolTable();
     110
     111        ErrorDetection getErrorMode() const {
     112                return errorMode;
     113        }
    97114
    98115        // when using an indexer manually (e.g., within a mutator traversal), it is necessary to
     
    158175
    159176private:
     177        void OnFindError( CodeLocation location, std::string error ) const;
     178
     179        template< typename T >
     180        void OnFindError( const T * obj, const std::string & error ) const {
     181                OnFindError( obj->location, toString( error, obj ) );
     182        }
     183
     184        template< typename T >
     185        void OnFindError( CodeLocation location, const T * obj, const std::string & error ) const {
     186                OnFindError( location, toString( error, obj ) );
     187        }
     188
    160189        /// Ensures that a proper backtracking scope exists before a mutation
    161190        void lazyInitScope();
     
    168197        bool removeSpecialOverrides( IdData & decl, MangleTable::Ptr & mangleTable );
    169198
    170         /// Options for handling identifier conflicts
     199        /// Error detection mode given at construction (pass-specific).
     200        /// Logically const, except that the symbol table's push-pop is achieved by autogenerated
     201        /// assignment onto self.  The feield is left motuable to keep this code-gen simple.
     202        /// Conceptual constness is preserved by all SymbolTable in a stack sharing the same mode.
     203        ErrorDetection errorMode;
     204
     205        /// Options for handling identifier conflicts.
     206        /// Varies according to AST location during traversal: captures semantics of the construct
     207        /// being visited as "would shadow" vs "must not collide."
     208        /// At a given AST location, is the same for every pass.
    171209        struct OnConflict {
    172210                enum {
    173                         Error,  ///< Throw a semantic error
     211                        Error,  ///< Follow the current pass's ErrorDetection mode (may throw a semantic error)
    174212                        Delete  ///< Delete the earlier version with the delete statement
    175213                } mode;
     
    191229                const Decl * deleter );
    192230
     231        /// true if redeclaration conflict between two types
     232        bool addedTypeConflicts( const NamedTypeDecl * existing, const NamedTypeDecl * added ) const;
     233
     234        /// true if redeclaration conflict between two aggregate declarations
     235        bool addedDeclConflicts( const AggregateDecl * existing, const AggregateDecl * added ) const;
     236
    193237        /// common code for addId, addDeletedId, etc.
    194238        void addIdCommon(
     
    213257}
    214258
     259
    215260// Local Variables: //
    216261// tab-width: 4 //
  • src/AST/Util.cpp

    r24d6572 r62d62db  
    8383}
    8484
     85/// Check that the MemberExpr has an aggregate type and matching member.
     86void memberMatchesAggregate( const MemberExpr * expr ) {
     87        const Type * aggrType = expr->aggregate->result->stripReferences();
     88        const AggregateDecl * decl = nullptr;
     89        if ( auto inst = dynamic_cast<const StructInstType *>( aggrType ) ) {
     90                decl = inst->base;
     91        } else if ( auto inst = dynamic_cast<const UnionInstType *>( aggrType ) ) {
     92                decl = inst->base;
     93        }
     94        assertf( decl, "Aggregate of member not correct type." );
     95
     96        for ( auto aggrMember : decl->members ) {
     97                if ( expr->member == aggrMember ) {
     98                        return;
     99                }
     100        }
     101        assertf( false, "Member not found." );
     102}
     103
    85104struct InvariantCore {
    86105        // To save on the number of visits: this is a kind of composed core.
     
    108127        }
    109128
     129        void previsit( const MemberExpr * node ) {
     130                previsit( (const ParseNode *)node );
     131                memberMatchesAggregate( node );
     132        }
     133
    110134        void postvisit( const Node * node ) {
    111135                no_strong_cycles.postvisit( node );
  • src/Concurrency/Actors.cpp

    r24d6572 r62d62db  
    3838    bool namedDecl = false;
    3939
    40     // finds and sets a ptr to the Allocation enum, which is needed in the next pass
     40    // finds and sets a ptr to the allocation enum, which is needed in the next pass
    4141    void previsit( const EnumDecl * decl ) {
    42         if( decl->name == "Allocation" ) *allocationDecl = decl;
     42        if( decl->name == "allocation" ) *allocationDecl = decl;
    4343    }
    4444
     
    227227                static inline derived_actor & ?|?( derived_actor & receiver, derived_msg & msg ) {
    228228                    request new_req;
    229                     Allocation (*my_work_fn)( derived_actor &, derived_msg & ) = receive;
     229                    allocation (*my_work_fn)( derived_actor &, derived_msg & ) = receive;
    230230                    __receive_fn fn = (__receive_fn)my_work_fn;
    231231                    new_req{ &receiver, &msg, fn };
     
    246246            ));
    247247           
    248             // Function type is: Allocation (*)( derived_actor &, derived_msg & )
     248            // Function type is: allocation (*)( derived_actor &, derived_msg & )
    249249            FunctionType * derivedReceive = new FunctionType();
    250250            derivedReceive->params.push_back( ast::deepCopy( derivedActorRef ) );
     
    252252            derivedReceive->returns.push_back( new EnumInstType( *allocationDecl ) );
    253253
    254             // Generates: Allocation (*my_work_fn)( derived_actor &, derived_msg & ) = receive;
     254            // Generates: allocation (*my_work_fn)( derived_actor &, derived_msg & ) = receive;
    255255            sendBody->push_back( new DeclStmt(
    256256                decl->location,
     
    263263            ));
    264264
    265             // Function type is: Allocation (*)( actor &, message & )
     265            // Function type is: allocation (*)( actor &, message & )
    266266            FunctionType * genericReceive = new FunctionType();
    267267            genericReceive->params.push_back( new ReferenceType( new StructInstType( *actorDecl ) ) );
     
    269269            genericReceive->returns.push_back( new EnumInstType( *allocationDecl ) );
    270270
    271             // Generates: Allocation (*fn)( actor &, message & ) = (Allocation (*)( actor &, message & ))my_work_fn;
     271            // Generates: allocation (*fn)( actor &, message & ) = (allocation (*)( actor &, message & ))my_work_fn;
    272272            // More readable synonymous code:
    273             //     typedef Allocation (*__receive_fn)(actor &, message &);
     273            //     typedef allocation (*__receive_fn)(actor &, message &);
    274274            //     __receive_fn fn = (__receive_fn)my_work_fn;
    275275            sendBody->push_back( new DeclStmt(
     
    422422    const StructDecl ** msgDecl = &msgDeclPtr;
    423423
    424     // first pass collects ptrs to Allocation enum, request type, and generic receive fn typedef
     424    // first pass collects ptrs to allocation enum, request type, and generic receive fn typedef
    425425    // also populates maps of all derived actors and messages
    426426    Pass<CollectactorStructDecls>::run( translationUnit, actorStructDecls, messageStructDecls, requestDecl,
  • src/Parser/lex.ll

    r24d6572 r62d62db  
    1010 * Created On       : Sat Sep 22 08:58:10 2001
    1111 * Last Modified By : Peter A. Buhr
    12  * Last Modified On : Tue May  2 08:45:21 2023
    13  * Update Count     : 769
     12 * Last Modified On : Fri Jun  9 10:04:00 2023
     13 * Update Count     : 770
    1414 */
    1515
     
    319319static                  { KEYWORD_RETURN(STATIC); }
    320320_Static_assert  { KEYWORD_RETURN(STATICASSERT); }               // C11
     321_static_assert  { KEYWORD_RETURN(STATICASSERT); }               // C23
    321322struct                  { KEYWORD_RETURN(STRUCT); }
    322323suspend                 { KEYWORD_RETURN(SUSPEND); }                    // CFA
  • src/Parser/parser.yy

    r24d6572 r62d62db  
    1010// Created On       : Sat Sep  1 20:22:55 2001
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Wed Apr 26 16:45:37 2023
    13 // Update Count     : 6330
     12// Last Modified On : Wed Jun  7 14:32:28 2023
     13// Update Count     : 6341
    1414//
    1515
     
    108108        assert( declList );
    109109        // printf( "distAttr1 typeSpec %p\n", typeSpec ); typeSpec->print( std::cout );
    110         DeclarationNode * cur = declList, * cl = (new DeclarationNode)->addType( typeSpec );
     110        DeclarationNode * cl = (new DeclarationNode)->addType( typeSpec );
    111111        // printf( "distAttr2 cl %p\n", cl ); cl->type->print( std::cout );
    112112        // cl->type->aggregate.name = cl->type->aggInst.aggregate->aggregate.name;
    113113
    114         for ( cur = dynamic_cast<DeclarationNode *>( cur->get_next() ); cur != nullptr; cur = dynamic_cast<DeclarationNode *>( cur->get_next() ) ) {
     114        for ( DeclarationNode * cur = dynamic_cast<DeclarationNode *>( declList->get_next() ); cur != nullptr; cur = dynamic_cast<DeclarationNode *>( cur->get_next() ) ) {
    115115                cl->cloneBaseType( cur );
    116116        } // for
     
    206206#define NEW_ONE  new ExpressionNode( build_constantInteger( yylloc, *new string( "1" ) ) )
    207207#define UPDOWN( compop, left, right ) (compop == OperKinds::LThan || compop == OperKinds::LEThan ? left : right)
    208 #define MISSING_ANON_FIELD "Missing loop fields with an anonymous loop index is meaningless as loop index is unavailable in loop body."
    209 #define MISSING_LOW "Missing low value for up-to range so index is uninitialized."
    210 #define MISSING_HIGH "Missing high value for down-to range so index is uninitialized."
     208#define MISSING_ANON_FIELD "syntax error, missing loop fields with an anonymous loop index is meaningless as loop index is unavailable in loop body."
     209#define MISSING_LOW "syntax error, missing low value for up-to range so index is uninitialized."
     210#define MISSING_HIGH "syntax error, missing high value for down-to range so index is uninitialized."
    211211
    212212static ForCtrl * makeForCtrl(
     
    232232ForCtrl * forCtrl( const CodeLocation & location, DeclarationNode * index, ExpressionNode * start, enum OperKinds compop, ExpressionNode * comp, ExpressionNode * inc ) {
    233233        if ( index->initializer ) {
    234                 SemanticError( yylloc, "Direct initialization disallowed. Use instead: type var; initialization ~ comparison ~ increment." );
     234                SemanticError( yylloc, "syntax error, direct initialization disallowed. Use instead: type var; initialization ~ comparison ~ increment." );
    235235        } // if
    236236        if ( index->next ) {
    237                 SemanticError( yylloc, "Multiple loop indexes disallowed in for-loop declaration." );
     237                SemanticError( yylloc, "syntax error, multiple loop indexes disallowed in for-loop declaration." );
    238238        } // if
    239239        DeclarationNode * initDecl = index->addInitializer( new InitializerNode( start ) );
     
    260260                        return forCtrl( location, type, new string( identifier->name ), start, compop, comp, inc );
    261261                } else {
    262                         SemanticError( yylloc, "Expression disallowed. Only loop-index name allowed." ); return nullptr;
     262                        SemanticError( yylloc, "syntax error, loop-index name missing. Expression disallowed." ); return nullptr;
    263263                } // if
    264264        } else {
    265                 SemanticError( yylloc, "Expression disallowed. Only loop-index name allowed." ); return nullptr;
     265                SemanticError( yylloc, "syntax error, loop-index name missing. Expression disallowed. ." ); return nullptr;
    266266        } // if
    267267} // forCtrl
    268268
    269269static void IdentifierBeforeIdentifier( string & identifier1, string & identifier2, const char * kind ) {
    270         SemanticError( yylloc, ::toString( "Adjacent identifiers \"", identifier1, "\" and \"", identifier2, "\" are not meaningful in a", kind, ".\n"
     270        SemanticError( yylloc, ::toString( "syntax error, adjacent identifiers \"", identifier1, "\" and \"", identifier2, "\" are not meaningful in a", kind, ".\n"
    271271                                   "Possible cause is misspelled type name or missing generic parameter." ) );
    272272} // IdentifierBeforeIdentifier
    273273
    274274static void IdentifierBeforeType( string & identifier, const char * kind ) {
    275         SemanticError( yylloc, ::toString( "Identifier \"", identifier, "\" cannot appear before a ", kind, ".\n"
     275        SemanticError( yylloc, ::toString( "syntax error, identifier \"", identifier, "\" cannot appear before a ", kind, ".\n"
    276276                                   "Possible cause is misspelled storage/CV qualifier, misspelled typename, or missing generic parameter." ) );
    277277} // IdentifierBeforeType
     
    689689        // | RESUME '(' comma_expression ')' compound_statement
    690690        //      { SemanticError( yylloc, "Resume expression is currently unimplemented." ); $$ = nullptr; }
    691         | IDENTIFIER IDENTIFIER                                                         // syntax error
     691        | IDENTIFIER IDENTIFIER                                                         // invalid syntax rules
    692692                { IdentifierBeforeIdentifier( *$1.str, *$2.str, "n expression" ); $$ = nullptr; }
    693         | IDENTIFIER type_qualifier                                                     // syntax error
     693        | IDENTIFIER type_qualifier                                                     // invalid syntax rules
    694694                { IdentifierBeforeType( *$1.str, "type qualifier" ); $$ = nullptr; }
    695         | IDENTIFIER storage_class                                                      // syntax error
     695        | IDENTIFIER storage_class                                                      // invalid syntax rules
    696696                { IdentifierBeforeType( *$1.str, "storage class" ); $$ = nullptr; }
    697         | IDENTIFIER basic_type_name                                            // syntax error
     697        | IDENTIFIER basic_type_name                                            // invalid syntax rules
    698698                { IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
    699         | IDENTIFIER TYPEDEFname                                                        // syntax error
     699        | IDENTIFIER TYPEDEFname                                                        // invalid syntax rules
    700700                { IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
    701         | IDENTIFIER TYPEGENname                                                        // syntax error
     701        | IDENTIFIER TYPEGENname                                                        // invalid syntax rules
    702702                { IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
    703703        ;
     
    11521152        identifier_or_type_name ':' attribute_list_opt statement
    11531153                { $$ = $4->add_label( yylloc, $1, $3 ); }
    1154         | identifier_or_type_name ':' attribute_list_opt error // syntax error
    1155                 {
    1156                         SemanticError( yylloc, ::toString( "Label \"", *$1.str, "\" must be associated with a statement, "
     1154        | identifier_or_type_name ':' attribute_list_opt error // invalid syntax rule
     1155                {
     1156                        SemanticError( yylloc, ::toString( "syntx error, label \"", *$1.str, "\" must be associated with a statement, "
    11571157                                                                                           "where a declaration, case, or default is not a statement. "
    11581158                                                                                           "Move the label or terminate with a semi-colon." ) );
     
    11931193        | statement_list_nodecl statement
    11941194                { assert( $1 ); $1->set_last( $2 ); $$ = $1; }
    1195         | statement_list_nodecl error                                           // syntax error
    1196                 { SemanticError( yylloc, "Declarations only allowed at the start of the switch body, i.e., after the '{'." ); $$ = nullptr; }
     1195        | statement_list_nodecl error                                           // invalid syntax rule
     1196                { SemanticError( yylloc, "syntax error, declarations only allowed at the start of the switch body, i.e., after the '{'." ); $$ = nullptr; }
    11971197        ;
    11981198
     
    12191219                        $$ = $7 ? new StatementNode( build_compound( yylloc, (StatementNode *)((new StatementNode( $7 ))->set_last( sw )) ) ) : sw;
    12201220                }
    1221         | SWITCH '(' comma_expression ')' '{' error '}'         // CFA, syntax error
    1222                 { SemanticError( yylloc, "Only declarations can appear before the list of case clauses." ); $$ = nullptr; }
     1221        | SWITCH '(' comma_expression ')' '{' error '}'         // CFA, invalid syntax rule error
     1222                { SemanticError( yylloc, "synatx error, declarations can only appear before the list of case clauses." ); $$ = nullptr; }
    12231223        | CHOOSE '(' comma_expression ')' case_clause           // CFA
    12241224                { $$ = new StatementNode( build_switch( yylloc, false, $3, $5 ) ); }
     
    12281228                        $$ = $7 ? new StatementNode( build_compound( yylloc, (StatementNode *)((new StatementNode( $7 ))->set_last( sw )) ) ) : sw;
    12291229                }
    1230         | CHOOSE '(' comma_expression ')' '{' error '}'         // CFA, syntax error
    1231                 { SemanticError( yylloc, "Only declarations can appear before the list of case clauses." ); $$ = nullptr; }
     1230        | CHOOSE '(' comma_expression ')' '{' error '}'         // CFA, invalid syntax rule
     1231                { SemanticError( yylloc, "syntax error, declarations can only appear before the list of case clauses." ); $$ = nullptr; }
    12321232        ;
    12331233
     
    12681268
    12691269case_label:                                                                                             // CFA
    1270         CASE error                                                                                      // syntax error
    1271                 { SemanticError( yylloc, "Missing case list after case." ); $$ = nullptr; }
     1270        CASE error                                                                                      // invalid syntax rule
     1271                { SemanticError( yylloc, "syntax error, case list missing after case." ); $$ = nullptr; }
    12721272        | CASE case_value_list ':'                                      { $$ = $2; }
    1273         | CASE case_value_list error                                            // syntax error
    1274                 { SemanticError( yylloc, "Missing colon after case list." ); $$ = nullptr; }
     1273        | CASE case_value_list error                                            // invalid syntax rule
     1274                { SemanticError( yylloc, "syntax error, colon missing after case list." ); $$ = nullptr; }
    12751275        | DEFAULT ':'                                                           { $$ = new ClauseNode( build_default( yylloc ) ); }
    12761276                // A semantic check is required to ensure only one default clause per switch/choose statement.
    1277         | DEFAULT error                                                                         //  syntax error
    1278                 { SemanticError( yylloc, "Missing colon after default." ); $$ = nullptr; }
     1277        | DEFAULT error                                                                         //  invalid syntax rules
     1278                { SemanticError( yylloc, "syntax error, colon missing after default." ); $$ = nullptr; }
    12791279        ;
    12801280
     
    14051405                        else { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
    14061406                }
    1407         | comma_expression updowneq comma_expression '~' '@' // CFA, error
     1407        | comma_expression updowneq comma_expression '~' '@' // CFA, invalid syntax rules
    14081408                { SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
    1409         | '@' updowneq '@'                                                                      // CFA, error
     1409        | '@' updowneq '@'                                                                      // CFA, invalid syntax rules
    14101410                { SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
    1411         | '@' updowneq comma_expression '~' '@'                         // CFA, error
     1411        | '@' updowneq comma_expression '~' '@'                         // CFA, invalid syntax rules
    14121412                { SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
    1413         | comma_expression updowneq '@' '~' '@'                         // CFA, error
     1413        | comma_expression updowneq '@' '~' '@'                         // CFA, invalid syntax rules
    14141414                { SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
    1415         | '@' updowneq '@' '~' '@'                                                      // CFA, error
     1415        | '@' updowneq '@' '~' '@'                                                      // CFA, invalid syntax rules
    14161416                { SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
    14171417
     
    14311431                {
    14321432                        if ( $4 == OperKinds::GThan || $4 == OperKinds::GEThan ) { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
    1433                         else if ( $4 == OperKinds::LEThan ) { SemanticError( yylloc, "Equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
     1433                        else if ( $4 == OperKinds::LEThan ) { SemanticError( yylloc, "syntax error, equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
    14341434                        else $$ = forCtrl( yylloc, $3, $1, $3->clone(), $4, nullptr, NEW_ONE );
    14351435                }
    1436         | comma_expression ';' '@' updowneq '@'                         // CFA, error
    1437                 { SemanticError( yylloc, "Missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
     1436        | comma_expression ';' '@' updowneq '@'                         // CFA, invalid syntax rules
     1437                { SemanticError( yylloc, "syntax error, missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
    14381438
    14391439        | comma_expression ';' comma_expression updowneq comma_expression '~' comma_expression // CFA
    14401440                { $$ = forCtrl( yylloc, $3, $1, UPDOWN( $4, $3->clone(), $5 ), $4, UPDOWN( $4, $5->clone(), $3->clone() ), $7 ); }
    1441         | comma_expression ';' '@' updowneq comma_expression '~' comma_expression // CFA, error
     1441        | comma_expression ';' '@' updowneq comma_expression '~' comma_expression // CFA, invalid syntax rules
    14421442                {
    14431443                        if ( $4 == OperKinds::LThan || $4 == OperKinds::LEThan ) { SemanticError( yylloc, MISSING_LOW ); $$ = nullptr; }
     
    14471447                {
    14481448                        if ( $4 == OperKinds::GThan || $4 == OperKinds::GEThan ) { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
    1449                         else if ( $4 == OperKinds::LEThan ) { SemanticError( yylloc, "Equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
     1449                        else if ( $4 == OperKinds::LEThan ) { SemanticError( yylloc, "syntax error, equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
    14501450                        else $$ = forCtrl( yylloc, $3, $1, $3->clone(), $4, nullptr, $7 );
    14511451                }
    14521452        | comma_expression ';' comma_expression updowneq comma_expression '~' '@' // CFA
    14531453                { $$ = forCtrl( yylloc, $3, $1, UPDOWN( $4, $3->clone(), $5 ), $4, UPDOWN( $4, $5->clone(), $3->clone() ), nullptr ); }
    1454         | comma_expression ';' '@' updowneq comma_expression '~' '@' // CFA, error
     1454        | comma_expression ';' '@' updowneq comma_expression '~' '@' // CFA, invalid syntax rules
    14551455                {
    14561456                        if ( $4 == OperKinds::LThan || $4 == OperKinds::LEThan ) { SemanticError( yylloc, MISSING_LOW ); $$ = nullptr; }
     
    14601460                {
    14611461                        if ( $4 == OperKinds::GThan || $4 == OperKinds::GEThan ) { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
    1462                         else if ( $4 == OperKinds::LEThan ) { SemanticError( yylloc, "Equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
     1462                        else if ( $4 == OperKinds::LEThan ) { SemanticError( yylloc, "syntax error, equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
    14631463                        else $$ = forCtrl( yylloc, $3, $1, $3->clone(), $4, nullptr, nullptr );
    14641464                }
    14651465        | comma_expression ';' '@' updowneq '@' '~' '@' // CFA
    1466                 { SemanticError( yylloc, "Missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
     1466                { SemanticError( yylloc, "syntax error, missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
    14671467
    14681468        | declaration comma_expression                                          // CFA
     
    14811481                {
    14821482                        if ( $3 == OperKinds::GThan || $3 == OperKinds::GEThan ) { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
    1483                         else if ( $3 == OperKinds::LEThan ) { SemanticError( yylloc, "Equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
     1483                        else if ( $3 == OperKinds::LEThan ) { SemanticError( yylloc, "syntax error, equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
    14841484                        else $$ = forCtrl( yylloc, $1, $2, $3, nullptr, NEW_ONE );
    14851485                }
     
    14951495                {
    14961496                        if ( $3 == OperKinds::GThan || $3 == OperKinds::GEThan ) { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
    1497                         else if ( $3 == OperKinds::LEThan ) { SemanticError( yylloc, "Equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
     1497                        else if ( $3 == OperKinds::LEThan ) { SemanticError( yylloc, "syntax error, equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
    14981498                        else $$ = forCtrl( yylloc, $1, $2, $3, nullptr, $6 );
    14991499                }
     
    15081508                {
    15091509                        if ( $3 == OperKinds::GThan || $3 == OperKinds::GEThan ) { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
    1510                         else if ( $3 == OperKinds::LEThan ) { SemanticError( yylloc, "Equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
     1510                        else if ( $3 == OperKinds::LEThan ) { SemanticError( yylloc, "syntax error, equality with missing high value is meaningless. Use \"~\"." ); $$ = nullptr; }
    15111511                        else $$ = forCtrl( yylloc, $1, $2, $3, nullptr, nullptr );
    15121512                }
    1513         | declaration '@' updowneq '@' '~' '@'                          // CFA, error
    1514                 { SemanticError( yylloc, "Missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
     1513        | declaration '@' updowneq '@' '~' '@'                          // CFA, invalid syntax rules
     1514                { SemanticError( yylloc, "syntax error, missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
    15151515
    15161516        | comma_expression ';' TYPEDEFname                                      // CFA, array type
     
    15211521        | comma_expression ';' downupdowneq TYPEDEFname         // CFA, array type
    15221522                {
    1523                         if ( $3 == OperKinds::LEThan || $3 == OperKinds::GEThan ) { SemanticError( yylloc, "All enumation ranges are equal (all values). Remove \"=~\"." ); $$ = nullptr; }
     1523                        if ( $3 == OperKinds::LEThan || $3 == OperKinds::GEThan ) {
     1524                                SemanticError( yylloc, "syntax error, all enumeration ranges are equal (all values). Remove \"=~\"." ); $$ = nullptr;
     1525                        }
    15241526                        SemanticError( yylloc, "Type iterator is currently unimplemented." ); $$ = nullptr;
    15251527                }
     
    16161618        MUTEX '(' argument_expression_list_opt ')' statement
    16171619                {
    1618                         if ( ! $3 ) { SemanticError( yylloc, "mutex argument list cannot be empty." ); $$ = nullptr; }
     1620                        if ( ! $3 ) { SemanticError( yylloc, "syntax error, mutex argument list cannot be empty." ); $$ = nullptr; }
    16191621                        $$ = new StatementNode( build_mutex( yylloc, $3, $5 ) );
    16201622                }
     
    16641666                { $$ = build_waitfor_timeout( yylloc, $1, $3, $4, maybe_build_compound( yylloc, $5 ) ); }
    16651667        // "else" must be conditional after timeout or timeout is never triggered (i.e., it is meaningless)
    1666         | wor_waitfor_clause wor when_clause_opt timeout statement wor ELSE statement // syntax error
    1667                 { SemanticError( yylloc, "else clause must be conditional after timeout or timeout never triggered." ); $$ = nullptr; }
     1668        | wor_waitfor_clause wor when_clause_opt timeout statement wor ELSE statement // invalid syntax rules
     1669                { SemanticError( yylloc, "syntax error, else clause must be conditional after timeout or timeout never triggered." ); $$ = nullptr; }
    16681670        | wor_waitfor_clause wor when_clause_opt timeout statement wor when_clause ELSE statement
    16691671                { $$ = build_waitfor_else( yylloc, build_waitfor_timeout( yylloc, $1, $3, $4, maybe_build_compound( yylloc, $5 ) ), $7, maybe_build_compound( yylloc, $9 ) ); }
     
    17091711                { $$ = new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::LEFT_OR, $1, build_waituntil_timeout( yylloc, $3, $4, maybe_build_compound( yylloc, $5 ) ) ); }
    17101712        // "else" must be conditional after timeout or timeout is never triggered (i.e., it is meaningless)
    1711         | wor_waituntil_clause wor when_clause_opt timeout statement wor ELSE statement // syntax error
    1712                 { SemanticError( yylloc, "else clause must be conditional after timeout or timeout never triggered." ); $$ = nullptr; }
     1713        | wor_waituntil_clause wor when_clause_opt timeout statement wor ELSE statement // invalid syntax rules
     1714                { SemanticError( yylloc, "syntax error, else clause must be conditional after timeout or timeout never triggered." ); $$ = nullptr; }
    17131715        | wor_waituntil_clause wor when_clause_opt timeout statement wor when_clause ELSE statement
    17141716                { $$ = new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::LEFT_OR, $1,
     
    20652067                        assert( $1->type );
    20662068                        if ( $1->type->qualifiers.any() ) {                     // CV qualifiers ?
    2067                                 SemanticError( yylloc, "Useless type qualifier(s) in empty declaration." ); $$ = nullptr;
     2069                                SemanticError( yylloc, "syntax error, useless type qualifier(s) in empty declaration." ); $$ = nullptr;
    20682070                        }
    20692071                        // enums are never empty declarations because there must have at least one enumeration.
    20702072                        if ( $1->type->kind == TypeData::AggregateInst && $1->storageClasses.any() ) { // storage class ?
    2071                                 SemanticError( yylloc, "Useless storage qualifier(s) in empty aggregate declaration." ); $$ = nullptr;
     2073                                SemanticError( yylloc, "syntax error, useless storage qualifier(s) in empty aggregate declaration." ); $$ = nullptr;
    20722074                        }
    20732075                }
     
    21002102        | type_declaration_specifier
    21012103        | sue_declaration_specifier
    2102         | sue_declaration_specifier invalid_types
    2103                 {
    2104                         SemanticError( yylloc, ::toString( "Missing ';' after end of ",
     2104        | sue_declaration_specifier invalid_types                       // invalid syntax rule
     2105                {
     2106                        SemanticError( yylloc, ::toString( "syntax error, expecting ';' at end of ",
    21052107                                $1->type->enumeration.name ? "enum" : ast::AggregateDecl::aggrString( $1->type->aggregate.kind ),
    2106                                 " declaration" ) );
     2108                                " declaration." ) );
    21072109                        $$ = nullptr;
    21082110                }
     
    25842586                        // } // for
    25852587                }
     2588        | type_specifier field_declaring_list_opt '}'           // invalid syntax rule
     2589                {
     2590                        SemanticError( yylloc, ::toString( "syntax error, expecting ';' at end of previous declaration." ) );
     2591                        $$ = nullptr;
     2592                }
    25862593        | EXTENSION type_specifier field_declaring_list_opt ';' // GCC
    25872594                { $$ = fieldDecl( $2, $3 ); distExt( $$ ); }
     
    26822689        | ENUM '(' cfa_abstract_parameter_declaration ')' attribute_list_opt '{' enumerator_list comma_opt '}'
    26832690                {
    2684                         if ( $3->storageClasses.val != 0 || $3->type->qualifiers.any() )
    2685                         { SemanticError( yylloc, "storage-class and CV qualifiers are not meaningful for enumeration constants, which are const." ); }
    2686 
     2691                        if ( $3->storageClasses.val != 0 || $3->type->qualifiers.any() ) {
     2692                                SemanticError( yylloc, "syntax error, storage-class and CV qualifiers are not meaningful for enumeration constants, which are const." );
     2693                        }
    26872694                        $$ = DeclarationNode::newEnum( nullptr, $7, true, true, $3 )->addQualifiers( $5 );
    26882695                }
     
    26932700        | ENUM '(' cfa_abstract_parameter_declaration ')' attribute_list_opt identifier attribute_list_opt
    26942701                {
    2695                         if ( $3->storageClasses.any() || $3->type->qualifiers.val != 0 ) { SemanticError( yylloc, "storage-class and CV qualifiers are not meaningful for enumeration constants, which are const." ); }
     2702                        if ( $3->storageClasses.any() || $3->type->qualifiers.val != 0 ) {
     2703                                SemanticError( yylloc, "syntax error, storage-class and CV qualifiers are not meaningful for enumeration constants, which are const." );
     2704                        }
    26962705                        typedefTable.makeTypedef( *$6 );
    26972706                }
     
    31663175        | IDENTIFIER IDENTIFIER
    31673176                { IdentifierBeforeIdentifier( *$1.str, *$2.str, " declaration" ); $$ = nullptr; }
    3168         | IDENTIFIER type_qualifier                                                     // syntax error
     3177        | IDENTIFIER type_qualifier                                                     // invalid syntax rules
    31693178                { IdentifierBeforeType( *$1.str, "type qualifier" ); $$ = nullptr; }
    3170         | IDENTIFIER storage_class                                                      // syntax error
     3179        | IDENTIFIER storage_class                                                      // invalid syntax rules
    31713180                { IdentifierBeforeType( *$1.str, "storage class" ); $$ = nullptr; }
    3172         | IDENTIFIER basic_type_name                                            // syntax error
     3181        | IDENTIFIER basic_type_name                                            // invalid syntax rules
    31733182                { IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
    3174         | IDENTIFIER TYPEDEFname                                                        // syntax error
     3183        | IDENTIFIER TYPEDEFname                                                        // invalid syntax rules
    31753184                { IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
    3176         | IDENTIFIER TYPEGENname                                                        // syntax error
     3185        | IDENTIFIER TYPEGENname                                                        // invalid syntax rules
    31773186                { IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
    31783187        | external_function_definition
     
    32093218        | type_qualifier_list
    32103219                {
    3211                         if ( $1->type->qualifiers.any() ) { SemanticError( yylloc, "CV qualifiers cannot be distributed; only storage-class and forall qualifiers." ); }
     3220                        if ( $1->type->qualifiers.any() ) {
     3221                                SemanticError( yylloc, "syntax error, CV qualifiers cannot be distributed; only storage-class and forall qualifiers." );
     3222                        }
    32123223                        if ( $1->type->forall ) forall = true;          // remember generic type
    32133224                }
     
    32203231        | declaration_qualifier_list
    32213232                {
    3222                         if ( $1->type && $1->type->qualifiers.any() ) { SemanticError( yylloc, "CV qualifiers cannot be distributed; only storage-class and forall qualifiers." ); }
     3233                        if ( $1->type && $1->type->qualifiers.any() ) {
     3234                                SemanticError( yylloc, "syntax error, CV qualifiers cannot be distributed; only storage-class and forall qualifiers." );
     3235                        }
    32233236                        if ( $1->type && $1->type->forall ) forall = true; // remember generic type
    32243237                }
     
    32313244        | declaration_qualifier_list type_qualifier_list
    32323245                {
    3233                         if ( ($1->type && $1->type->qualifiers.any()) || ($2->type && $2->type->qualifiers.any()) ) { SemanticError( yylloc, "CV qualifiers cannot be distributed; only storage-class and forall qualifiers." ); }
     3246                        if ( ($1->type && $1->type->qualifiers.any()) || ($2->type && $2->type->qualifiers.any()) ) {
     3247                                SemanticError( yylloc, "syntax error, CV qualifiers cannot be distributed; only storage-class and forall qualifiers." );
     3248                        }
    32343249                        if ( ($1->type && $1->type->forall) || ($2->type && $2->type->forall) ) forall = true; // remember generic type
    32353250                }
     
    32623277                        $$ = $3; forall = false;
    32633278                        if ( $5 ) {
    3264                                 SemanticError( yylloc, "Attributes cannot be associated with function body. Move attribute(s) before \"with\" clause." );
     3279                                SemanticError( yylloc, "syntax error, attributes cannot be associated with function body. Move attribute(s) before \"with\" clause." );
    32653280                                $$ = nullptr;
    32663281                        } // if
  • src/ResolvExpr/CommonType.cc

    r24d6572 r62d62db  
    10351035                void postvisit( const ast::TraitInstType * ) {}
    10361036
    1037                 void postvisit( const ast::TypeInstType * inst ) {}
    1038 
    1039                 void postvisit( const ast::TupleType * tuple) {
     1037                void postvisit( const ast::TypeInstType * ) {}
     1038
     1039                void postvisit( const ast::TupleType * tuple ) {
    10401040                        tryResolveWithTypedEnum( tuple );
    10411041                }
  • src/ResolvExpr/Resolver.cc

    r24d6572 r62d62db  
    11071107
    11081108                /// Removes cast to type of argument (unlike StripCasts, also handles non-generated casts)
    1109                 void removeExtraneousCast( ast::ptr<ast::Expr> & expr, const ast::SymbolTable & symtab ) {
     1109                void removeExtraneousCast( ast::ptr<ast::Expr> & expr ) {
    11101110                        if ( const ast::CastExpr * castExpr = expr.as< ast::CastExpr >() ) {
    11111111                                if ( typesCompatible( castExpr->arg->result, castExpr->result ) ) {
     
    11971197                ast::ptr< ast::Expr > castExpr = new ast::CastExpr{ untyped, type };
    11981198                ast::ptr< ast::Expr > newExpr = findSingleExpression( castExpr, context );
    1199                 removeExtraneousCast( newExpr, context.symtab );
     1199                removeExtraneousCast( newExpr );
    12001200                return newExpr;
    12011201        }
     
    12621262                static size_t traceId;
    12631263                Resolver_new( const ast::TranslationGlobal & global ) :
     1264                        ast::WithSymbolTable(ast::SymbolTable::ErrorDetection::ValidateOnAdd),
    12641265                        context{ symtab, global } {}
    12651266                Resolver_new( const ResolveContext & context ) :
     
    20412042                const ast::Type * initContext = currentObject.getCurrentType();
    20422043
    2043                 removeExtraneousCast( newExpr, symtab );
     2044                removeExtraneousCast( newExpr );
    20442045
    20452046                // check if actual object's type is char[]
  • src/Validate/HoistStruct.cpp

    r24d6572 r62d62db  
    1818#include <sstream>
    1919
     20#include "AST/DeclReplacer.hpp"
    2021#include "AST/Pass.hpp"
    2122#include "AST/TranslationUnit.hpp"
     23#include "AST/Vector.hpp"
    2224
    2325namespace Validate {
     
    5153        template<typename AggrDecl>
    5254        AggrDecl const * postAggregate( AggrDecl const * );
     55        template<typename InstType>
     56        InstType const * preCollectionInstType( InstType const * type );
    5357
    5458        ast::AggregateDecl const * parent = nullptr;
     
    6670        qualifiedName( decl, ss );
    6771        return ss.str();
     72}
     73
     74void extendParams( ast::vector<ast::TypeDecl> & dstParams,
     75                ast::vector<ast::TypeDecl> const & srcParams ) {
     76        if ( srcParams.empty() ) return;
     77
     78        ast::DeclReplacer::TypeMap newToOld;
     79        ast::vector<ast::TypeDecl> params;
     80        for ( ast::ptr<ast::TypeDecl> const & srcParam : srcParams ) {
     81                ast::TypeDecl * dstParam = ast::deepCopy( srcParam.get() );
     82                dstParam->init = nullptr;
     83                newToOld.emplace( srcParam, dstParam );
     84                for ( auto assertion : dstParam->assertions ) {
     85                        assertion = ast::DeclReplacer::replace( assertion, newToOld );
     86                }
     87                params.emplace_back( dstParam );
     88        }
     89        spliceBegin( dstParams, params );
    6890}
    6991
     
    7496                mut->parent = parent;
    7597                mut->name = qualifiedName( mut );
    76                 return mut;
    77         } else {
    78                 GuardValue( parent ) = decl;
    79                 return decl;
    80         }
     98                extendParams( mut->params, parent->params );
     99                decl = mut;
     100        }
     101        GuardValue( parent ) = decl;
     102        return decl;
    81103}
    82104
     
    112134}
    113135
     136ast::AggregateDecl const * commonParent(
     137                ast::AggregateDecl const * lhs, ast::AggregateDecl const * rhs ) {
     138        for ( auto outer = lhs ; outer ; outer = outer->parent ) {
     139                for ( auto inner = rhs ; inner ; inner = inner->parent ) {
     140                        if ( outer == inner ) {
     141                                return outer;
     142                        }
     143                }
     144        }
     145        return nullptr;
     146}
     147
     148template<typename InstType>
     149InstType const * HoistStructCore::preCollectionInstType( InstType const * type ) {
     150    if ( !type->base->parent ) return type;
     151    if ( type->base->params.empty() ) return type;
     152
     153    InstType * mut = ast::mutate( type );
     154    ast::AggregateDecl const * parent =
     155        commonParent( this->parent, mut->base->parent );
     156    assert( parent );
     157
     158    std::vector<ast::ptr<ast::Expr>> args;
     159    for ( const ast::ptr<ast::TypeDecl> & param : parent->params ) {
     160        args.emplace_back( new ast::TypeExpr( param->location,
     161            new ast::TypeInstType( param )
     162        ) );
     163    }
     164    spliceBegin( mut->params, args );
     165    return mut;
     166}
     167
    114168template<typename InstType>
    115169InstType const * preInstType( InstType const * type ) {
     
    121175
    122176ast::StructInstType const * HoistStructCore::previsit( ast::StructInstType const * type ) {
    123         return preInstType( type );
     177        return preInstType( preCollectionInstType( type ) );
    124178}
    125179
    126180ast::UnionInstType const * HoistStructCore::previsit( ast::UnionInstType const * type ) {
    127         return preInstType( type );
     181        return preInstType( preCollectionInstType( type ) );
    128182}
    129183
  • tests/.expect/copyfile.txt

    r24d6572 r62d62db  
    1010// Created On       : Fri Jun 19 13:44:05 2020
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Fri Jun 19 17:58:03 2020
    13 // Update Count     : 4
     12// Last Modified On : Mon Jun  5 21:20:07 2023
     13// Update Count     : 5
    1414//
    1515
     
    3030                        exit | "Usage" | argv[0] | "[ input-file (default stdin) [ output-file (default stdout) ] ]";
    3131                } // choose
    32         } catch( Open_Failure * ex ; ex->istream == &in ) {
     32        } catch( open_failure * ex ; ex->istream == &in ) {
    3333                exit | "Unable to open input file" | argv[1];
    34         } catch( Open_Failure * ex ; ex->ostream == &out ) {
     34        } catch( open_failure * ex ; ex->ostream == &out ) {
    3535                close( in );                                                                    // optional
    3636                exit | "Unable to open output file" | argv[2];
  • tests/.in/copyfile.txt

    r24d6572 r62d62db  
    1010// Created On       : Fri Jun 19 13:44:05 2020
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Fri Jun 19 17:58:03 2020
    13 // Update Count     : 4
     12// Last Modified On : Mon Jun  5 21:20:07 2023
     13// Update Count     : 5
    1414//
    1515
     
    3030                        exit | "Usage" | argv[0] | "[ input-file (default stdin) [ output-file (default stdout) ] ]";
    3131                } // choose
    32         } catch( Open_Failure * ex ; ex->istream == &in ) {
     32        } catch( open_failure * ex ; ex->istream == &in ) {
    3333                exit | "Unable to open input file" | argv[1];
    34         } catch( Open_Failure * ex ; ex->ostream == &out ) {
     34        } catch( open_failure * ex ; ex->ostream == &out ) {
    3535                close( in );                                                                    // optional
    3636                exit | "Unable to open output file" | argv[2];
  • tests/concurrency/actors/dynamic.cfa

    r24d6572 r62d62db  
    1919void ?{}( derived_msg & this ) { ((derived_msg &)this){ 0 }; }
    2020
    21 Allocation receive( derived_actor & receiver, derived_msg & msg ) {
     21allocation receive( derived_actor & receiver, derived_msg & msg ) {
    2222    if ( msg.cnt >= Times ) {
    2323        sout | "Done";
  • tests/concurrency/actors/executor.cfa

    r24d6572 r62d62db  
    2424struct d_msg { inline message; } shared_msg;
    2525
    26 Allocation receive( d_actor & this, d_msg & msg ) with( this ) {
     26allocation receive( d_actor & this, d_msg & msg ) with( this ) {
    2727    if ( recs == rounds ) return Finished;
    2828    if ( recs % Batch == 0 ) {
  • tests/concurrency/actors/inherit.cfa

    r24d6572 r62d62db  
    1515void ^?{}( D_msg & this ) { mutex(sout) sout | 'A'; }
    1616
    17 Allocation handle() {
     17allocation handle() {
    1818    return Finished;
    1919}
    2020
    21 Allocation receive( Server & receiver, D_msg & msg ) { return handle(); }
    22 Allocation receive( Server & receiver, D_msg2 & msg ) { return handle(); }
    23 Allocation receive( Server2 & receiver, D_msg & msg ) { return Delete; }
    24 Allocation receive( Server2 & receiver, D_msg2 & msg ) { return Delete; }
     21allocation receive( Server & receiver, D_msg & msg ) { return handle(); }
     22allocation receive( Server & receiver, D_msg2 & msg ) { return handle(); }
     23allocation receive( Server2 & receiver, D_msg & msg ) { return Delete; }
     24allocation receive( Server2 & receiver, D_msg2 & msg ) { return Delete; }
    2525
    2626int main() {
  • tests/concurrency/actors/matrix.cfa

    r24d6572 r62d62db  
    2424}
    2525
    26 Allocation receive( derived_actor & receiver, derived_msg & msg ) {
     26allocation receive( derived_actor & receiver, derived_msg & msg ) {
    2727    for ( unsigned int i = 0; i < yc; i += 1 ) { // multiply X_row by Y_col and sum products
    2828        msg.Z[i] = 0;
  • tests/concurrency/actors/pingpong.cfa

    r24d6572 r62d62db  
    1919size_t times = 100000;
    2020
    21 Allocation receive( ping & receiver, p_msg & msg ) {
     21allocation receive( ping & receiver, p_msg & msg ) {
    2222    msg.count++;
    2323    if ( msg.count > times ) return Finished;
    2424
    25     Allocation retval = Nodelete;
     25    allocation retval = Nodelete;
    2626    if ( msg.count == times ) retval = Finished;
    2727    *po << msg;
     
    2929}
    3030
    31 Allocation receive( pong & receiver, p_msg & msg ) {
     31allocation receive( pong & receiver, p_msg & msg ) {
    3232    msg.count++;
    3333    if ( msg.count > times ) return Finished;
    3434   
    35     Allocation retval = Nodelete;
     35    allocation retval = Nodelete;
    3636    if ( msg.count == times ) retval = Finished;
    3737    *pi << msg;
  • tests/concurrency/actors/poison.cfa

    r24d6572 r62d62db  
    1818        Server s[10];
    1919        for ( i; 10 ) {
    20             s[i] << FinishedMsg;
     20            s[i] << finished_msg;
    2121        }
    2222        stop_actor_system();
     
    2929            Server * s = alloc();
    3030            (*s){};
    31             (*s) << DeleteMsg;
     31            (*s) << delete_msg;
    3232        }
    3333        stop_actor_system();
     
    3939        Server s[10];
    4040        for ( i; 10 )
    41             s[i] << DestroyMsg;
     41            s[i] << destroy_msg;
    4242        stop_actor_system();
    4343        for ( i; 10 )
  • tests/concurrency/actors/static.cfa

    r24d6572 r62d62db  
    1919void ?{}( derived_msg & this ) { ((derived_msg &)this){ 0 }; }
    2020
    21 Allocation receive( derived_actor & receiver, derived_msg & msg ) {
     21allocation receive( derived_actor & receiver, derived_msg & msg ) {
    2222    if ( msg.cnt >= Times ) {
    2323        sout | "Done";
  • tests/concurrency/actors/types.cfa

    r24d6572 r62d62db  
    2020
    2121// this isn't a valid receive routine since int is not a message type
    22 Allocation receive( derived_actor & receiver, int i ) with( receiver ) {
     22allocation receive( derived_actor & receiver, int i ) with( receiver ) {
    2323    mutex(sout) sout | i;
    2424    counter++;
     
    2727}
    2828
    29 Allocation receive( derived_actor & receiver, d_msg & msg ) {
     29allocation receive( derived_actor & receiver, d_msg & msg ) {
    3030    return receive( receiver, msg.num );
    3131}
     
    3636};
    3737
    38 Allocation receive( derived_actor2 & receiver, d_msg & msg ) {
     38allocation receive( derived_actor2 & receiver, d_msg & msg ) {
    3939    mutex(sout) sout | msg.num;
    4040    return Finished;
     
    4848};
    4949
    50 Allocation receive( derived_actor3 & receiver, d_msg & msg ) {
     50allocation receive( derived_actor3 & receiver, d_msg & msg ) {
    5151    mutex(sout) sout | msg.num;
    5252    if ( msg.num == -1 ) return Nodelete;
     
    5454}
    5555
    56 Allocation receive( derived_actor3 & receiver, d_msg2 & msg ) {
     56allocation receive( derived_actor3 & receiver, d_msg2 & msg ) {
    5757    mutex(sout) sout | msg.num;
    5858    return Finished;
  • tests/concurrency/lockfree_stack.cfa

    r24d6572 r62d62db  
    1010// Created On       : Thu May 25 15:36:50 2023
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue May 30 19:02:32 2023
    13 // Update Count     : 18
     12// Last Modified On : Fri Jun  9 14:01:07 2023
     13// Update Count     : 68
    1414//
    1515
     
    2929        int64_t atom;
    3030        #endif // __SIZEOF_INT128__
    31 } __attribute__(( aligned( 16 ) ));
     31};
    3232
    3333struct Node {
     
    4242        n.next = stack;                                                                         // atomic assignment unnecessary
    4343        for () {                                                                                        // busy wait
    44                 if ( CASV( stack.atom, n.next.atom, ((Link){ &n, n.next.count + 1 }.atom) ) ) break; // attempt to update top node
     44                Link temp{ &n, n.next.count + 1 };
     45                if ( CASV( s.stack.atom, n.next.atom, temp.atom ) ) break; // attempt to update top node
    4546        }
    4647}
     
    5051        for () {                                                                                        // busy wait
    5152                if ( t.top == NULL ) return NULL;                               // empty stack ?
    52                 if ( CASV( stack.atom, t.atom, ((Link){ t.top->next.top, t.count }.atom) ) ) return t.top; // attempt to update top node
     53                Link temp{ t.top->next.top, t.count };
     54                if ( CASV( stack.atom, t.atom, temp.atom ) ) return t.top; // attempt to update top node
    5355        }
    5456}
     
    5759Stack stack;                                                                                    // global stack
    5860
    59 enum { Times =
    60         #if defined( __ARM_ARCH )                                                       // ARM CASV is very slow
    61         10_000
    62         #else
    63         1_000_000
    64         #endif // __arm_64__
    65 };
     61enum { Times = 2_000_000 };
    6662
    6763thread Worker {};
     
    8278
    8379        for ( i; N ) {                                                                          // push N values on stack
    84                 // storage must be 16-bytes aligned for cmpxchg16b
    85                 push( stack, *(Node *)memalign( 16, sizeof( Node ) ) );
     80                push( stack, *(Node *)new() );                                  // must be 16-byte aligned
    8681        }
    8782        {
  • tests/concurrency/waituntil/locks.cfa

    r24d6572 r62d62db  
    22#include <thread.hfa>
    33#include <locks.hfa>
     4#include <fstream.hfa>
    45#include <mutex_stmt.hfa>
    56
  • tests/configs/.expect/parseconfig.txt

    r24d6572 r62d62db  
    1212Maximum student trips: 3
    1313
    14 Open_Failure thrown when config file does not exist
     14open_failure thrown when config file does not exist
    1515Failed to open the config file
    1616
  • tests/configs/parseconfig.cfa

    r24d6572 r62d62db  
    6666
    6767
    68         sout | "Open_Failure thrown when config file does not exist";
     68        sout | "open_failure thrown when config file does not exist";
    6969        try {
    7070                parse_config( xstr(IN_DIR) "doesnt-exist.txt", entries, NUM_ENTRIES, parse_tabular_config_format );
    71         } catch( Open_Failure * ex ) {
     71        } catch( open_failure * ex ) {
    7272                sout | "Failed to open the config file";
    7373        }
  • tests/copyfile.cfa

    r24d6572 r62d62db  
    1010// Created On       : Fri Jun 19 13:44:05 2020
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sat Aug 15 15:00:48 2020
    13 // Update Count     : 6
     12// Last Modified On : Mon Jun  5 21:20:19 2023
     13// Update Count     : 7
    1414//
    1515
     
    3030                        exit | "Usage" | argv[0] | "[ input-file (default stdin) [ output-file (default stdout) ] ]";
    3131                } // choose
    32         } catch( Open_Failure * ex ; ex->istream == &in ) {
     32        } catch( open_failure * ex ; ex->istream == &in ) {
    3333                exit | "Unable to open input file" | argv[1];
    34         } catch( Open_Failure * ex ; ex->ostream == &out ) {
     34        } catch( open_failure * ex ; ex->ostream == &out ) {
    3535                close( in );                                                                    // optional
    3636                exit | "Unable to open output file" | argv[2];
  • tests/rational.cfa

    r24d6572 r62d62db  
    1010// Created On       : Mon Mar 28 08:43:12 2016
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue Jul 20 18:13:40 2021
    13 // Update Count     : 107
     12// Last Modified On : Mon Jun  5 22:58:09 2023
     13// Update Count     : 108
    1414//
    1515
     
    1919#include <fstream.hfa>
    2020
    21 typedef Rational(int) RatInt;
     21typedef rational(int) rat_int;
    2222double convert( int i ) { return (double)i; }                   // used by narrow/widen
    2323int convert( double d ) { return (int)d; }
     
    2525int main() {
    2626        sout | "constructor";
    27         RatInt a = { 3 }, b = { 4 }, c, d = 0, e = 1;
     27        rat_int a = { 3 }, b = { 4 }, c, d = 0, e = 1;
    2828        sout | "a : " | a | "b : " | b | "c : " | c | "d : " | d | "e : " | e;
    2929
    30         a = (RatInt){ 4, 8 };
    31         b = (RatInt){ 5, 7 };
     30        a = (rat_int){ 4, 8 };
     31        b = (rat_int){ 5, 7 };
    3232        sout | "a : " | a | "b : " | b;
    33         a = (RatInt){ -2, -3 };
    34         b = (RatInt){ 3, -2 };
     33        a = (rat_int){ -2, -3 };
     34        b = (rat_int){ 3, -2 };
    3535        sout | "a : " | a | "b : " | b;
    36         a = (RatInt){ -2, 3 };
    37         b = (RatInt){ 3, 2 };
     36        a = (rat_int){ -2, 3 };
     37        b = (rat_int){ 3, 2 };
    3838        sout | "a : " | a | "b : " | b;
    3939        sout | nl;
    4040
    4141        sout | "comparison";
    42         a = (RatInt){ -2 };
    43         b = (RatInt){ -3, 2 };
     42        a = (rat_int){ -2 };
     43        b = (rat_int){ -3, 2 };
    4444        sout | "a : " | a | "b : " | b;
    45         sout | "a == 0 : " | a == (Rational(int)){0}; // FIX ME
    46         sout | "a == 1 : " | a == (Rational(int)){1}; // FIX ME
     45        sout | "a == 0 : " | a == (rational(int)){0}; // FIX ME
     46        sout | "a == 1 : " | a == (rational(int)){1}; // FIX ME
    4747        sout | "a != 0 : " | a != 0;
    4848        sout | "! a : " | ! a;
     
    7373
    7474        sout | "conversion";
    75         a = (RatInt){ 3, 4 };
     75        a = (rat_int){ 3, 4 };
    7676        sout | widen( a );
    77         a = (RatInt){ 1, 7 };
     77        a = (rat_int){ 1, 7 };
    7878        sout | widen( a );
    79         a = (RatInt){ 355, 113 };
     79        a = (rat_int){ 355, 113 };
    8080        sout | widen( a );
    8181        sout | narrow( 0.75, 4 );
     
    9090
    9191        sout | "more tests";
    92         RatInt x = { 1, 2 }, y = { 2 };
     92        rat_int x = { 1, 2 }, y = { 2 };
    9393        sout | x - y;
    9494        sout | x > y;
     
    9696        sout | y | denominator( y, -2 ) | y;
    9797
    98         RatInt z = { 0, 5 };
     98        rat_int z = { 0, 5 };
    9999        sout | z;
    100100
    101101        sout | x | numerator( x, 0 ) | x;
    102102
    103         x = (RatInt){ 1, MAX } + (RatInt){ 1, MAX };
     103        x = (rat_int){ 1, MAX } + (rat_int){ 1, MAX };
    104104        sout | x;
    105         x = (RatInt){ 3, MAX } + (RatInt){ 2, MAX };
     105        x = (rat_int){ 3, MAX } + (rat_int){ 2, MAX };
    106106        sout | x;
    107107
Note: See TracChangeset for help on using the changeset viewer.