The Northern Spy: Modula-2 R10 Templates
TweetFollow Us on Twitter

The Northern Spy: Modula-2 R10 Templates

By Rick Sutcliffe

Modula-2 R10 has been the Spy's meat and potatoes in this space for a few months now. It is the fully modern dialect of Niklaus Wirth's Modula-2 that he and Telecom engineer Benjamin Kowarsch have developed to address serious software engineering issues of safety, security, reliability, and extensibility. This month we consider the use of Generic templates to reach toward the software engineering grail of reusable code.

Modern programming practice first saw Generics in Modula-3, C++, and Java. The Modula-3 technique was then modified somewhat by the Spy as part of a proposal to the ISO committee for Modula-2 and this became a supplementary standard to that work, subsequently implemented by most vendors.

Generic facilities address two common situations with a lightweight solution for which using class types and their objects is overkill. These are:

1. the implementation of algorithms whose expression is essentially identical across many the data types on which it is used. The classic example is a sorting algorithm, which, once implemented, can be re-used for a new data type by modifying only the way that comparisons and swops are done.

2. the implementation of data structures whose maintenance code is essentially identical across the many data types that may be stored in it. Examples include linked lists, various tree structures, and so on.

In both cases, rather than implement once, then modify to suit alternate data types, it makes sense to have a facility that allows the code to be expressed in a manner that is generic, that is, with a dummy data type present in the code, and a provision to "refine" this generic code for a specified data type by the expedient of passing to a refining utility a pseudo-parameter naming that data type.

ISO Modula-2 generics achieved this by employing a parameterized Generic module pair as compilation units, which could be refined any number of times by the compiler, whenever it was presented with a refining module pair that supplied the actual parameters. One wrote, for instance:

GENERIC DEFINITION MODULE Sorts (Item : TYPE; GenCompare : CompareProc);

FROM Comparisons IMPORT
CompareResults;

TYPE
CompareProc = PROCEDURE (Item, Item) : CompareResults;

PROCEDURE Quick (VAR data : ARRAY OF Item);

(* Other procedures and functions would be included as well. *)
END Sorts.

and then wrote the corresponding implementation module, where comparisons for the purpose of sorting were done naming the formal "GenCompare" name, whose actual value would be passed in as parameter on refinement. One could also name, say, a "GenSwop" routine and refine that as well, although this is unnecessary, as it could be hidden in the generic implementation and be written to swop using the generic type name. Only type parameters and constant value parameters (which includes specific procedure names) were allowed as formal generic module parameters. Note that the type of a formal parameter could be defined in the generic definition itself as the compiler has access to the entire contents of such a definition, and this is a trivial forward reference.
A refining module pair would have:

DEFINITION MODULE CardQuickSort = Sorts (CARDINAL);
END CardStack.

and likewise for the refining implementation, with the identical actual parameter(s) required.
It was up to implementors to determine the mechanics of template refinement, but the semantics were to be as if a new separate library module were created from the template with the substitutions per the module parameters.

In R10
we determined that since all that was in view was textual substitution, we might as well be explicit and assume the presence of a utility to handle such substitutions. After all, it could be used for other purposes than template refinement. Thus, we dispense with refining definition and implementation modules, and with module parameters. moreover, since, for instance, comparison can be handled by binding to operators, the sorting example can be simplified. Mo compareProc is needed. Just write the code using the standard comparison operator(s), bind to the operator when defining the ADT, and the correct comparison code will be automatically called.
All items that must be replaced by substitution are enclosed in a double hash. Indeed, R10 specifies a language for templates, illustrated in portions of a template module for static arrays:

DEFINITION MODULE ##ModuleIdent## [ProtoStaticArray];

/* Modula-2 R10 Static Array Type Template */
/*
* All parameters are marked (A) automatic, (M) mandatory or (D) default.
*
* This template expands the following parameters:
*
* TemplateVersion (A) -- The date and time stamp of this template,
* automatically set by the template engine utility.
*
* ModuleIdent (A) -- The library's identifier,
* automatically supplied by the GENLIB directive.
*
* IndexType (M) -- The index type must be an ordinal type. Compilation of
* the generated library will fail if it is not an ordinal type.
*
* ValueType (M) -- The value type of the array, THERE IS NO DEFAULT.
* Template expansion will fail if the parameter is omitted.
*
* LowerBound (D) and UpperBound (D) -- If omitted, the values of TMIN (Inde Type and TMAX(IndexType) will be used.
/* ---------------------------------------------------------------------------
* Placeholder Verification and Defaults
* ------------------------------------------------------------------------ */

/* Define placeholder ADT as an alias of ModuleIdent */
<#DEFINE ADT = @@ModuleIdent@@#>

/* Verify IndexType holds a mixed or uppercase identifier, else fail */
<#VERIFY IndexType [Aa|AA] FAIL#>

/* Verify ValueType holds a mixed or uppercase identifier, else fail */
<#VERIFY ValueType [Aa|AA] FAIL#>

/* If LowerBound is omitted, use TMIN(IndexType) */
<#DEFIF UNDEFINED(LowerBound) : LowerBound = "TMIN(##IndexType##)" #>

/* If UpperBound is omitted, use TMAX(IndexType) */
<#DEFIF UNDEFINED(UpperBound) : LowerBound = "TMAX)(##IndexType##)" #>

IMPORT ##IndexType##
IMPORT ##ValueType##

CONST isOrdered = TRUE;
CONST componentCount = ##UpperBound## - ##LowerBound## + 1;

TYPE ##ADT## = OPAQUE RECORD
entry : ARRAY componentCount OF ValueType
END; (* ##ADT## *)

TYPE ValueType = ALIAS OF ##ValueType##;

PROCEDURE [:=] assignStructuredValue
( array : ##ADT##; value : ARGLIST componentCount OF ValueType );

PROCEDURE [COPY] copy
( CONST source : ##ADT##; VAR target : ##ADT## );

PROCEDURE [STORE] storeValueAtIndex
( array : ##ADT##;
index : ##IndexType##; value : ##ValueType## );

PROCEDURE [RETRIEVE] valueAtIndex
( array : ##ADT##; index : ##IndexType## );

PROCEDURE [COUNT] count ( array : ##ADT## ) : LONGCARD;

TYPE ForLoopBodyProc = PROCEDURE ( (* index : *) CONST ##IndexType## );

PROCEDURE [FOR] forIterator
( assocArray : ##ADT##;
forLoopBody : ForLoopBodyProc; ascending : BOOLEAN );

PROCEDURE [=] isEqual
( array1, array2 : ##ADT## ) : BOOLEAN;

/* General IO library */
<#EXPAND "StaticArrays" :
ModuleIdent = @@ADT@@"IO";
ValueType = @@ValueType@@
GenIO = "TRUE"#>

END ##ModuleIdent##.

<#IF GenIO#>
/* Generate the ADT's IO Library */
DEFINITION MODULE ##IOLibrary## [ProtoIO] FOR ##ADT##;

PROCEDURE [READ] Read ( file : File; VAR array : ##ADT## );

PROCEDURE [WRITE] Write ( file : File; array : ##ADT## );
PROCEDURE [WRITEF] WriteF
( file : File; fmtStr : ARRAY OF CHAR;
items : VARIADIC OF ##ADT## );

END ##IOLibrary##.
<#ENDIF#>

This template is expanded by the M2 R10 template engine utility. Expansion may be invoked within a compiling source file using the GENLIB directive.

GENLIB FooArray FROM GenStaticArrays FOR
IndexType = "Barbaz";
ValueType = "Bamboo"
END;

and thereafter, the newly generated library may be simply imported into the current or some other scope.

IMPORT FooArray;

During template expansion, any occurrences of ##ModuleIdent## are replaced by the identifier following GENLIB, and any occurences of ##ValueType## are replaced by the quoted value given for ValueType in the GENLIB directive. Template comments (like this one) are removed during template expansion.
In this instance (and likely in many others) the template itself depends on a blueprint. as it contains bindings. Moreover, this template generate two libraries--one for the data structure itself, and a second for its I/O.

This is just a taste of what can be done using templates. But, as we said last month with respect to blueprints, it ought to give the reader some idea of how Modula-2 R10 enforces the discipline of planning to assist in producing sound well-thought-out code, and provides the means to re-use tried and true code frameworks with a variety of other data types.

What about OO?

Wirth's original Modula-2 notation lacked OO. The ISO committee added two object oriented variants in an extension--one garbage collected, the other not. At this point, R10 is a base notation and has no object types. However, this is planned as part of a second phase, likely using the Objective-C philosophy, and for this purpose a few words have been reserved sequestered as probable future reserved words and standard identifiers. We do contend, however, that OO is not the best technique for everything, and at least some tasks often performed using it can be expressed more simply without.

That's all folks so for more information consult the repository site. Next month the Spy returns to his usual perambulations about the technical world, complete with observations on related social, economic, and political issues. Stay tuned, and remember you read it here first.

--The Northern Spy

Opinions expressed here are entirely the author's own, and no endorsement is implied by any community or organization to which he may be attached. Rick Sutcliffe, (a. k. a. The Northern Spy) is professor of Computing Science and Mathematics at Canada's Trinity Western University. He has been involved as a member or consultant with the boards of several community and organizations, and participated in developing industry standards at the national and international level. He is a co-author of the Modula-2 programming language R10 dialect. He is a long time technology author and has written two textbooks and nine alternate history SF novels, one named best ePublished SF novel for 2003. His columns have appeared in numerous magazines and newspapers (paper and online), and he's a regular speaker at churches, schools, academic meetings, and conferences. He and his wife Joyce have lived in the Aldergrove/Bradner area of BC since 1972.

Want to discuss this and other Northern Spy columns? Surf on over to ArjayBB. com. Participate and you could win free web hosting from the WebNameHost. net subsidiary of Arjay Web Services. Rick Sutcliffe's fiction can be purchased in various eBook formats from Fictionwise, and in dead tree form from Amazon's Booksurge.

URLs for Rick Sutcliffe's Arjay Enterprises:

The Northern Spy Home Page: http: //www. TheNorthernSpy. com
opundo : http: //opundo. com
Sheaves Christian Resources : http: //sheaves. org
WebNameHost : http: //www. WebNameHost. net
WebNameSource : http: //www. WebNameSource. net
nameman : http: //nameman. net

General URLs for Rick Sutcliffe's Books:
Author Site: http: //www. arjay. ca
Publisher's Site: http: //www. writers-exchange. com/Richard-Sutcliffe. html
The Fourth Civilization--Ethics, Society, and Technology (4th 2003 ed. ): http: //www. arjay. bc. ca/EthTech/Text/index. html
Sites for Modula-2 resources
Modula-2 FAQ and ISO-based introductory text: http://www.modula-2.com
R10 Repository and source code: https://bitbucket.org/trijezdci/m2r10/src
The Supplied Blueprint Hierarchy: https://bitbucket.org/trijezdci/m2r10/src/27876b7e71b7e04befe1687e27a3fc...

More links, Wiki: http://www.modula-2.net
p1 ISO Modula-2 for the Mac: http://modula2.awiedemann.de/

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Six fantastic ways to spend National Vid...
As if anyone needed an excuse to play games today, I am about to give you one: it is National Video Games Day. A day for us to play games, like we no doubt do every day. Let’s not look a gift horse in the mouth. Instead, feast your eyes on this... | Read more »
Old School RuneScape players turn out in...
The sheer leap in technological advancements in our lifetime has been mind-blowing. We went from Commodore 64s to VR glasses in what feels like a heartbeat, but more importantly, the internet. It can be a dark mess, but it also brought hundreds of... | Read more »
Today's Best Mobile Game Discounts...
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Nintendo and The Pokémon Company's...
Unless you have been living under a rock, you know that Nintendo has been locked in an epic battle with Pocketpair, creator of the obvious Pokémon rip-off Palworld. Nintendo often resorts to legal retaliation at the drop of a hat, but it seems this... | Read more »
Apple exclusive mobile games don’t make...
If you are a gamer on phones, no doubt you have been as distressed as I am on one huge sticking point: exclusivity. For years, Xbox and PlayStation have done battle, and before this was the Sega Genesis and the Nintendo NES. On console, it makes... | Read more »
Regionally exclusive events make no sens...
Last week, over on our sister site AppSpy, I babbled excitedly about the Pokémon GO Safari Days event. You can get nine Eevees with an explorer hat per day. Or, can you? Specifically, you, reader. Do you have the time or funds to possibly fly for... | Read more »
As Jon Bellamy defends his choice to can...
Back in March, Jagex announced the appointment of a new CEO, Jon Bellamy. Mr Bellamy then decided to almost immediately paint a huge target on his back by cancelling the Runescapes Pride event. This led to widespread condemnation about his perceived... | Read more »
Marvel Contest of Champions adds two mor...
When I saw the latest two Marvel Contest of Champions characters, I scoffed. Mr Knight and Silver Samurai, thought I, they are running out of good choices. Then I realised no, I was being far too cynical. This is one of the things that games do best... | Read more »
Grass is green, and water is wet: Pokémo...
It must be a day that ends in Y, because Pokémon Trading Card Game Pocket has kicked off its Zoroark Drop Event. Here you can get a promo version of another card, and look forward to the next Wonder Pick Event and the next Mass Outbreak that will be... | Read more »
Enter the Gungeon review
It took me a minute to get around to reviewing this game for a couple of very good reasons. The first is that Enter the Gungeon's style of roguelike bullet-hell action is teetering on the edge of being straight-up malicious, which made getting... | Read more »

Price Scanner via MacPrices.net

Take $150 off every Apple 11-inch M3 iPad Air
Amazon is offering a $150 discount on 11-inch M3 WiFi iPad Airs right now. Shipping is free: – 11″ 128GB M3 WiFi iPad Air: $449, $150 off – 11″ 256GB M3 WiFi iPad Air: $549, $150 off – 11″ 512GB M3... Read more
Apple iPad minis back on sale for $100 off MS...
Amazon is offering $100 discounts (up to 20% off) on Apple’s newest 2024 WiFi iPad minis, each with free shipping. These are the lowest prices available for new minis among the Apple retailers we... Read more
Apple’s 16-inch M4 Max MacBook Pros are on sa...
Amazon has 16-inch M4 Max MacBook Pros (Silver and Black colors) on sale for up to $410 off Apple’s MSRP right now. Shipping is free. Be sure to select Amazon as the seller, rather than a third-party... Read more
Red Pocket Mobile is offering a $150 rebate o...
Red Pocket Mobile has new Apple iPhone 17’s on sale for $150 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Switch to Verizon, and get any iPhone 16 for...
With yesterday’s introduction of the new iPhone 17 models, Verizon responded by running “on us” promos across much of the iPhone 16 lineup: iPhone 16 and 16 Plus show as $0/mo for 36 months with bill... Read more
Here is a summary of the new features in Appl...
Apple’s September 2025 event introduced major updates across its most popular product lines, focusing on health, performance, and design breakthroughs. The AirPods Pro 3 now feature best-in-class... Read more
Apple’s Smartphone Lineup Could Use A Touch o...
COMMENTARY – Whatever happened to the old adage, “less is more”? Apple’s smartphone lineup. — which is due for its annual refresh either this month or next (possibly at an Apple Event on September 9... Read more
Take $50 off every 11th-generation A16 WiFi i...
Amazon has Apple’s 11th-generation A16 WiFi iPads in stock on sale for $50 off MSRP right now. Shipping is free: – 11″ 11th-generation 128GB WiFi iPads: $299 $50 off MSRP – 11″ 11th-generation 256GB... Read more
Sunday Sale: 14-inch M4 MacBook Pros for up t...
Don’t pay full price! Amazon has Apple’s 14-inch M4 MacBook Pros (Silver and Black colors) on sale for up to $220 off MSRP right now. Shipping is free. Be sure to select Amazon as the seller, rather... Read more
Mac mini with M4 Pro CPU back on sale for $12...
B&H Photo has Apple’s Mac mini with the M4 Pro CPU back on sale for $1259, $140 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – Mac mini M4 Pro CPU (24GB/512GB): $1259, $... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.