Re: Reification of local names

Kamil Skalski <[email protected]>
Newsgroups gmane.comp.lang.haskell.template
Message-ID <[email protected]>
Monday 21 June 2004 18:52, Simon Peyton-Jones wrote:
>
>
> The "right place" to find the type info for a given syntax tree is in
> the syntax tree.  The type checker has processed your fragment
> 	[| let f = \x -> x + 2 in f |]
> You just want to see the types.   Currently there is no way to do that,
> but people often ask for it.
>
> One idea: add (Maybe Type) fields to many TH syntax forms, where the
> type checker can record types.  That's simple and direct.

This is actually the way how we implemented it in Nemerle. Our syntax trees 
has elements like E_typed { body : Typedtree.Expr } in Parsetree.Expr or 
T_typed { body : Typedtree.Type } in Parsetree.Type, so we can store typed 
parts in our ASTs. 
Our quotations support this with 
<[  $(e : typed) ]>  where `e' is a variable holding typed tree of expression

We can also build typed trees for types with quotation like
<[ ttype: int ]>

For example our `if' expression is a macro checking type of condition to 
supply special error message:

 macro @if (cond, e1, e2)
  syntax ("if", "(", cond, ")", e1, Optional (";"), "else", e2) 
  {
    def tcond = ty_expr (Nemerle.Macros.ImplicitCTX (), cond);
    def bool_ty = <[ ttype: bool ]>;
    expect_type ("if condition", tcond, bool_ty);
    
    <[ 
      match ($(tcond : typed)) { 
        | true => $e1 
        | _ => $e2
      } 
    ]>
  }

>
> A general question to TH aficionados: would this be useful?  Remember
> that the type may not be fully precise, because it's the result of
> type-checking an as-yet-unspliced fragment.

This is right, but when one has access to what compiler know about program, 
then this case can be handled inside meta code.
And usefulness of this feature can be really impressive. For example, take a 
look at typed version of SelectFromTuple - it can take one integer and tuple, 
then generate pattern matching for tuple of size reified form type of given 
object and selection of specified element. No need to specify size of tuple 
manually.
And this is just a simple example. In practice, we use this feature in some 
more interesting places, but too complex for a short example here.


Kamil Skalski
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.