Implementing forward refs in monadic assembler and interpreter

Glynn Clements glynn.clements@virgin.net
Fri, 15 Nov 2002 10:04:19 +0000


Mike Gunter wrote:

> However, forward branches make things harder.  I'd like to be able to
> write something along the lines of:

[snip]

> but it's not clear to me how to implement it.  I'd be willing to
> accept a somewhat less clean version (for instance, with more
> cumbersome forward references.)
> 
> Any help would be greatly appreciated.

What is the structure of the data which is produced by the assembler?

If it roughly corresponds to conventional machine code (e.g. a list of
opcodes with parameters), then you can use similar techniques to those
used by a "real" assembler.

If you are assembling into a list, the simplest approach is to perform
the assembly phase twice. The first phase generates the list of
label/address pairs. The second phase, which has the complete list of
label addresses available, performs the complete assembly process.

Both phases could use identical code; you just need to ensure that the
first phase can assemble a branch instruction for which the label is
unknown.

Alternatively, you could perform one pass plus a post-processing phase
which "fixes" any forward references. This would require either that
you can store a label in an assembled branch instructions in place of
an actual address, or that you generate a list incomplete branch
instructions so that you can go back and fix them.

OTOH, if you're actually interpreting the "assembly language"
directly, then a forward branch would have to store the label in a
"variable" to indicates that instructions are just to be skipped until
that label is reached.

-- 
Glynn Clements <glynn.clements@virgin.net>