How Unknown Values Work in the Titanium Code Processor

This post has been a long time coming, sorry for the delay (work has been really busy lately)! In a previous post I discussed the basic concepts behind how I do dynamic offline analysis of JavaScript in the Titanium Code Processor. Today I want to follow up on this post and talk a little more about unknown values.

An unknown value is its own data type. Technically, it has no type and represents all types at the same time. An unknown value is generated whenever it is not possible to evaluate an expression. There are many ways that these values can be generated, but we'll start with a simple example:

var d = Date.now();  

Obviously we don't know what the time will be when the app is run, so the code processor simply returns unknown in this instance. Date is significant because it is the only part of the ECMAScript spec that generates an unknown value from all known values. There are other ways to generate unknown values though; most references to the Titanium API generate unknown values for instance. Once we have our unknown value, the next question is then "how does this affect everything else?"

The rules are really quite simple: any expression involving an unknown value produces an unknown value. For example, all of these expressions produce unknown values:

var d = Date.now();  
d++;  
d + 10;  
d * 10;  
/[a-z]/.test(d);
typeof d;  
!!d;

The last two are significant in that the expected behavior does not apply. typeof is supposed to always return a string, but in this case it returns the value unknown. Similarly, !!d is often used to cast a value to a boolean, but in this case it also returns the value unknown.

This behavior makes unknown values "viral" in the sense that once something becomes unknown, it tends to make everything it touches unknown as well. This can have especially profound effects on conditionals, which I'll talk about in my next post.