[xquery-talk] treat as

Michael Kay mike at saxonica.com
Mon Jan 21 10:59:26 PST 2013

David - I've run across them in a somewhat obscure context, I guess.  
I've written an XQuery processor that rewrites queries originally parsed 
by Saxon, basically serializing them in the process.  All I can tell you 
is that Saxon generates an internal expression (ItemChecker) that is 
documented as corresponding to "treat as" in some cases where there was 
no "treat as" in the original supplied expression.
> I think this happens, eg, if you declare a variable with a certain 
> type (so the type will be checked dynamically when the assignment is 
> done), but later references to the variable's value can be wrapped in 
> a "treat as" so that the compiler can assume that the variable has the 
> declared type and perform suitable automatic type inferencing.  But 
> that's just a guess :)
> -Mike
"treat as" is basically a dynamic type check. Saxon does optimistic 
static typing, which basically means that it automatically inserts 
"treat as" expressions into the expression tree whenever it finds a 
construct that isn't statically type safe. So if you write


and the type of $a isn't statically known, Saxon rewrites it as

($a treat as node()*)/child::node()

which is what you would have to write yourself in a system with 
pessimistic type checking (either that, or you would add a type 
declaration to the declaration of variable $a).

Michael Kay

More information about the talk mailing list