[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Type checking!

Hi Fidel.

I'll try to sketch the solution at a high level.

Let's assume a "multiple pass" compiler.  Every pass is encoded using a class
that extends DepthFirstAdapter (or
another tree walker class).

In a first pass, you use a hashtable to relate every identifier with its
declaration node.  Make sure you can
identify the "type" of the identifier using the declaration node, possibly
using another hashtable.  This is
usually required if you allow the declaration of multiple identifiers with a
single type. (e.g.: int a,b,c;)

In the second pass, you do the type checking "bottom-up".  You achieve this by
overriding the outAxxx() methods of

For every expression, term, factor alternative, you compute and store the
resulting type in a hashtable.  e.g.:

... types = new Hashtable();

... outACharFactor(... node)
  types.put(node, --charType--);

... outAPlusExpression(... node)
  --type-- exp_type = (--type--) types.remove(node.getExpression());
  --type-- term_type = (--type--) types.remove(node.getTerm());
  types.put(node, common(exp_type, term_type));

You get to decide what --type-- is, depending on your compiler.  "common()"
would probably throw an exception if
you try to add values of incompatible types.

I hope this helps.

Etienne M. Gagnon, M.Sc.                     e-mail: egagnon@j-meg.com
Author of SableCC:                 http://www.sable.mcgill.ca/sablecc/