[comp.lang.misc] Macro-izing ELSEIFs

quiroz@rochester.UUCP (12/11/86)

Expires:
Sender:
Followup-To:


From article <1192@navajo.STANFORD.EDU> (billw@navajo.STANFORD.EDU (William E. Westfield)):
%Well, as long as it's under discussion anyway, does anyone have any
%hints as to how to implement ELSEIF as an assembler macro (specifically
%for the 8086 MASM v4)?
%

Eons ago I wrote something of the sort for the beloved IBM1130. I
don't know the 8*6  enough nor I am familiar with MASM, so I cannot
give concrete syntax, but the trick is rather simple.  If MASM is
smart, it might be even reentrant (exercise for the reader).

On seeing IF, advance your counter once and put the value on a place
you can retrieve it from later (call it "target").  This is the
target to be used by ENDIF.  Then generate the label for the first
branch, as per your posting.

On ELSEIF, you generate a JUMP to target (this indicates end of the
code for the previous clause), generate the label for the current
branch, advance the counter again.   On ELSE, again you generate a
branch to target, and a label for the current branch, but you don't
need to advance the counter anymore.  Finally, on ENDIF, you
generate the label for target (and pop target off the targets stack).

This will be independent of the number of branches. For, if the
current label is number 10, the exit point will be 11, the first
branch will be 12, next 13 and so on.  It might occur that you don't
need the pre-reserved branches after all, then your sequence of
labels will have holes, but I don't think you need to bother
collecting and reusing those labels.

Same strategy will give you other control structures that might
require more than one pre-reserved label (I did this for a
sort-of-ratfor preprocessor I hacked on, of all things, COBOL).

Obvious caveats.  Your ability to test for well-formedness of the
construct will depend on the smarts of the macro-processor.  Things
like IF ELSE ELSEIF ENDIF will be severely damaging, as we'll be to
have improper nesting.  Even doing nesting right will require some
ability to keep state, but I guess you already have it, if your
scheme for doing IFs works at all.  If you cannot 'push' reserved
labels, then you cannot use this scheme recursively.  Most
macro-processors allow you to have something like arrays of symbols,
you can use them to fake pushing over a bounded number of
recursions.  That lets you nest the constructs to a fixed level,
which should be good enough.

Good luck.  And do yourself a favor for Xmas: stop doing assembly.

=Cesar
-- 
Cesar Augusto  Quiroz Gonzalez
Department of Computer Science     {allegra|seismo}!rochester!quiroz
University of Rochester            or
Rochester,  NY 14627               quiroz@ROCHESTER