/[jscoverage]/trunk/instrument-js.c
ViewVC logotype

Diff of /trunk/instrument-js.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 90 by siliconforks, Tue May 6 14:05:12 2008 UTC revision 339 by siliconforks, Fri Oct 24 16:13:57 2008 UTC
# Line 17  Line 17 
17      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */  */
19    
20    #include <config.h>
21    
22  #include "instrument-js.h"  #include "instrument-js.h"
23    
24  #include <assert.h>  #include <assert.h>
# Line 24  Line 26 
26  #include <string.h>  #include <string.h>
27    
28  #include <jsapi.h>  #include <jsapi.h>
29    #include <jsarena.h>
30  #include <jsatom.h>  #include <jsatom.h>
31    #include <jsexn.h>
32  #include <jsfun.h>  #include <jsfun.h>
33  #include <jsinterp.h>  #include <jsinterp.h>
34    #include <jsiter.h>
35  #include <jsparse.h>  #include <jsparse.h>
36  #include <jsregexp.h>  #include <jsregexp.h>
37  #include <jsscope.h>  #include <jsscope.h>
38  #include <jsstr.h>  #include <jsstr.h>
39    
40    #include "encoding.h"
41    #include "global.h"
42    #include "highlight.h"
43    #include "resource-manager.h"
44  #include "util.h"  #include "util.h"
45    
46    struct IfDirective {
47      const jschar * condition_start;
48      const jschar * condition_end;
49      uint16_t start_line;
50      uint16_t end_line;
51      struct IfDirective * next;
52    };
53    
54    static bool * exclusive_directives = NULL;
55    
56  static JSRuntime * runtime = NULL;  static JSRuntime * runtime = NULL;
57  static JSContext * context = NULL;  static JSContext * context = NULL;
58  static JSObject * global = NULL;  static JSObject * global = NULL;
59    static JSVersion js_version = JSVERSION_ECMA_3;
60    
61  /*  /*
62  JSParseNode objects store line numbers starting from 1.  JSParseNode objects store line numbers starting from 1.
# Line 44  Line 64 
64  */  */
65  static const char * file_id = NULL;  static const char * file_id = NULL;
66  static char * lines = NULL;  static char * lines = NULL;
67    static uint16_t num_lines = 0;
68    
69    void jscoverage_set_js_version(const char * version) {
70      js_version = atoi(version);
71    }
72    
73  void jscoverage_init(void) {  void jscoverage_init(void) {
74    runtime = JS_NewRuntime(8L * 1024L * 1024L);    runtime = JS_NewRuntime(8L * 1024L * 1024L);
# Line 56  Line 81 
81      fatal("cannot create context");      fatal("cannot create context");
82    }    }
83    
84      JS_SetVersion(context, js_version);
85    
86    global = JS_NewObject(context, NULL, NULL, NULL);    global = JS_NewObject(context, NULL, NULL, NULL);
87    if (global == NULL) {    if (global == NULL) {
88      fatal("cannot create global object");      fatal("cannot create global object");
# Line 71  Line 98 
98    JS_DestroyRuntime(runtime);    JS_DestroyRuntime(runtime);
99  }  }
100    
101  static void print_string(JSString * s, FILE * f) {  static void print_javascript(const jschar * characters, size_t num_characters, Stream * f) {
102    for (int i = 0; i < s->length; i++) {    for (size_t i = 0; i < num_characters; i++) {
103      char c = s->chars[i];      jschar c = characters[i];
104      fputc(c, f);      /*
105        XXX does not handle no-break space, other unicode "space separator"
106        */
107        switch (c) {
108        case 0x9:
109        case 0xB:
110        case 0xC:
111          Stream_write_char(f, c);
112          break;
113        default:
114          if (32 <= c && c <= 126) {
115            Stream_write_char(f, c);
116          }
117          else {
118            Stream_printf(f, "\\u%04x", c);
119          }
120          break;
121        }
122      }
123    }
124    
125    static void print_string(JSString * s, Stream * f) {
126      size_t length = JSSTRING_LENGTH(s);
127      jschar * characters = JSSTRING_CHARS(s);
128      for (size_t i = 0; i < length; i++) {
129        jschar c = characters[i];
130        if (32 <= c && c <= 126) {
131          switch (c) {
132          case '"':
133            Stream_write_string(f, "\\\"");
134            break;
135    /*
136          case '\'':
137            Stream_write_string(f, "\\'");
138            break;
139    */
140          case '\\':
141            Stream_write_string(f, "\\\\");
142            break;
143          default:
144            Stream_write_char(f, c);
145            break;
146          }
147        }
148        else {
149          switch (c) {
150          case 0x8:
151            Stream_write_string(f, "\\b");
152            break;
153          case 0x9:
154            Stream_write_string(f, "\\t");
155            break;
156          case 0xa:
157            Stream_write_string(f, "\\n");
158            break;
159          /* IE doesn't support this */
160          /*
161          case 0xb:
162            Stream_write_string(f, "\\v");
163            break;
164          */
165          case 0xc:
166            Stream_write_string(f, "\\f");
167            break;
168          case 0xd:
169            Stream_write_string(f, "\\r");
170            break;
171          default:
172            Stream_printf(f, "\\u%04x", c);
173            break;
174          }
175        }
176    }    }
177  }  }
178    
179  static void print_string_atom(JSAtom * atom, FILE * f) {  static void print_string_atom(JSAtom * atom, Stream * f) {
180    assert(ATOM_IS_STRING(atom));    assert(ATOM_IS_STRING(atom));
181    JSString * s = ATOM_TO_STRING(atom);    JSString * s = ATOM_TO_STRING(atom);
182    print_string(s, f);    print_string(s, f);
183  }  }
184    
185  static void print_string_jsval(jsval value, FILE * f) {  static void print_regex(jsval value, Stream * f) {
186    assert(JSVAL_IS_STRING(value));    assert(JSVAL_IS_STRING(value));
187    JSString * s = JSVAL_TO_STRING(value);    JSString * s = JSVAL_TO_STRING(value);
188    print_string(s, f);    size_t length = JSSTRING_LENGTH(s);
189      jschar * characters = JSSTRING_CHARS(s);
190      for (size_t i = 0; i < length; i++) {
191        jschar c = characters[i];
192        if (32 <= c && c <= 126) {
193          Stream_write_char(f, c);
194        }
195        else {
196          Stream_printf(f, "\\u%04x", c);
197        }
198      }
199  }  }
200    
201  static void print_quoted_string_atom(JSAtom * atom, FILE * f) {  static void print_quoted_string_atom(JSAtom * atom, Stream * f) {
202    assert(ATOM_IS_STRING(atom));    assert(ATOM_IS_STRING(atom));
203    JSString * s = ATOM_TO_STRING(atom);    JSString * s = ATOM_TO_STRING(atom);
204    JSString * quoted = js_QuoteString(context, s, '"');    Stream_write_char(f, '"');
205    print_string(quoted, f);    print_string(s, f);
206      Stream_write_char(f, '"');
207  }  }
208    
209  static const char * get_op(uint8 op) {  static const char * get_op(uint8 op) {
210    switch(op) {    switch(op) {
211      case JSOP_OR:
212        return "||";
213      case JSOP_AND:
214        return "&&";
215    case JSOP_BITOR:    case JSOP_BITOR:
216      return "|";      return "|";
217    case JSOP_BITXOR:    case JSOP_BITXOR:
# Line 109  Line 222 
222      return "==";      return "==";
223    case JSOP_NE:    case JSOP_NE:
224      return "!=";      return "!=";
225    case JSOP_NEW_EQ:    case JSOP_STRICTEQ:
226      return "===";      return "===";
227    case JSOP_NEW_NE:    case JSOP_STRICTNE:
228      return "!==";      return "!==";
229    case JSOP_LT:    case JSOP_LT:
230      return "<";      return "<";
# Line 142  Line 255 
255    }    }
256  }  }
257    
258  static void instrument_expression(JSParseNode * node, FILE * f);  static void instrument_expression(JSParseNode * node, Stream * f);
259  static void instrument_statement(JSParseNode * node, FILE * f, int indent);  static void instrument_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if);
260    
261  static void instrument_function(JSParseNode * node, FILE * f, int indent) {  enum FunctionType {
262      assert(node->pn_arity == PN_FUNC);    FUNCTION_NORMAL,
263      assert(ATOM_IS_OBJECT(node->pn_funAtom));    FUNCTION_GETTER_OR_SETTER
264      JSObject * object = ATOM_TO_OBJECT(node->pn_funAtom);  };
265      assert(JS_ObjectIsFunction(context, object));  
266      JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);  static void instrument_function(JSParseNode * node, Stream * f, int indent, enum FunctionType type) {
267      assert(function);    assert(node->pn_type == TOK_FUNCTION);
268      assert(object == function->object);    assert(node->pn_arity == PN_FUNC);
269      fprintf(f, "%*s", indent, "");    JSObject * object = node->pn_funpob->object;
270      fprintf(f, "function");    assert(JS_ObjectIsFunction(context, object));
271      JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);
272      /* function name */    assert(function);
273      if (function->atom) {    assert(object == &function->object);
274        fputc(' ', f);    Stream_printf(f, "%*s", indent, "");
275        print_string_atom(function->atom, f);    if (type == FUNCTION_NORMAL) {
276      }      Stream_write_string(f, "function");
277      }
278      /* function parameters */  
279      fprintf(f, "(");    /* function name */
280      JSAtom ** params = xmalloc(function->nargs * sizeof(JSAtom *));    if (function->atom) {
281      for (int i = 0; i < function->nargs; i++) {      Stream_write_char(f, ' ');
282        /* initialize to NULL for sanity check */      print_string_atom(function->atom, f);
283        params[i] = NULL;    }
284      }  
285      JSScope * scope = OBJ_SCOPE(object);    /*
286      for (JSScopeProperty * scope_property = SCOPE_LAST_PROP(scope); scope_property != NULL; scope_property = scope_property->parent) {    function parameters - see JS_DecompileFunction in jsapi.cpp, which calls
287        if (scope_property->getter != js_GetArgument) {    js_DecompileFunction in jsopcode.cpp
288          continue;    */
289        }    Stream_write_string(f, "(");
290        assert(scope_property->flags & SPROP_HAS_SHORTID);    JSArenaPool pool;
291        assert((uint16) scope_property->shortid < function->nargs);    JS_INIT_ARENA_POOL(&pool, "instrument_function", 256, 1, &context->scriptStackQuota);
292        assert(JSID_IS_ATOM(scope_property->id));    jsuword * local_names = NULL;
293        params[(uint16) scope_property->shortid] = JSID_TO_ATOM(scope_property->id);    if (JS_GET_LOCAL_NAME_COUNT(function)) {
294        local_names = js_GetLocalNameArray(context, function, &pool);
295        if (local_names == NULL) {
296          fatal("out of memory");
297      }      }
298      for (int i = 0; i < function->nargs; i++) {    }
299        assert(params[i] != NULL);    for (int i = 0; i < function->nargs; i++) {
300        if (i > 0) {      if (i > 0) {
301          fprintf(f, ", ");        Stream_write_string(f, ", ");
       }  
       if (ATOM_IS_STRING(params[i])) {  
         print_string_atom(params[i], f);  
       }  
302      }      }
303      fprintf(f, ") {\n");      JSAtom * param = JS_LOCAL_NAME_TO_ATOM(local_names[i]);
304      free(params);      print_string_atom(param, f);
305      }
306      JS_FinishArenaPool(&pool);
307      Stream_write_string(f, ") {\n");
308    
309      /* function body */    /* function body */
310      instrument_statement(node->pn_body, f, indent + 2);    instrument_statement(node->pn_body, f, indent + 2, false);
311    
312      fprintf(f, "}\n");    Stream_write_string(f, "}\n");
313  }  }
314    
315  static void instrument_function_call(JSParseNode * node, FILE * f) {  static void instrument_function_call(JSParseNode * node, Stream * f) {
316    instrument_expression(node->pn_head, f);    instrument_expression(node->pn_head, f);
317    fputc('(', f);    Stream_write_char(f, '(');
318    for (struct JSParseNode * p = node->pn_head->pn_next; p != NULL; p = p->pn_next) {    for (struct JSParseNode * p = node->pn_head->pn_next; p != NULL; p = p->pn_next) {
319      if (p != node->pn_head->pn_next) {      if (p != node->pn_head->pn_next) {
320        fprintf(f, ", ");        Stream_write_string(f, ", ");
321      }      }
322      instrument_expression(p, f);      instrument_expression(p, f);
323    }    }
324    fputc(')', f);    Stream_write_char(f, ')');
325  }  }
326    
327  /*  /*
# Line 222  Line 337 
337  TOK_INSTANCEOF  binary  TOK_INSTANCEOF  binary
338  TOK_IN          binary  TOK_IN          binary
339  */  */
340  static void instrument_expression(JSParseNode * node, FILE * f) {  static void instrument_expression(JSParseNode * node, Stream * f) {
341    switch (node->pn_type) {    switch (node->pn_type) {
342    case TOK_FUNCTION:    case TOK_FUNCTION:
343      instrument_function(node, f, 0);      instrument_function(node, f, 0, FUNCTION_NORMAL);
344      break;      break;
345    case TOK_COMMA:    case TOK_COMMA:
346      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
347        if (p != node->pn_head) {        if (p != node->pn_head) {
348          fprintf(f, ", ");          Stream_write_string(f, ", ");
349        }        }
350        instrument_expression(p, f);        instrument_expression(p, f);
351      }      }
352      break;      break;
353    case TOK_ASSIGN:    case TOK_ASSIGN:
354      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
355      fputc(' ', f);      Stream_write_char(f, ' ');
356      switch (node->pn_op) {      switch (node->pn_op) {
357      case JSOP_ADD:      case JSOP_ADD:
358      case JSOP_SUB:      case JSOP_SUB:
# Line 250  Line 365 
365      case JSOP_BITOR:      case JSOP_BITOR:
366      case JSOP_BITXOR:      case JSOP_BITXOR:
367      case JSOP_DIV:      case JSOP_DIV:
368        fprintf(f, "%s", get_op(node->pn_op));        Stream_printf(f, "%s", get_op(node->pn_op));
369        break;        break;
370      default:      default:
371        /* do nothing - it must be a simple assignment */        /* do nothing - it must be a simple assignment */
372        break;        break;
373      }      }
374      fprintf(f, "= ");      Stream_write_string(f, "= ");
375      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
376      break;      break;
377    case TOK_HOOK:    case TOK_HOOK:
378      instrument_expression(node->pn_kid1, f);      instrument_expression(node->pn_kid1, f);
379      fprintf(f, "? ");      Stream_write_string(f, "? ");
380      instrument_expression(node->pn_kid2, f);      instrument_expression(node->pn_kid2, f);
381      fprintf(f, ": ");      Stream_write_string(f, ": ");
382      instrument_expression(node->pn_kid3, f);      instrument_expression(node->pn_kid3, f);
383      break;      break;
384    case TOK_OR:    case TOK_OR:
     instrument_expression(node->pn_left, f);  
     fprintf(f, " || ");  
     instrument_expression(node->pn_right, f);  
     break;  
385    case TOK_AND:    case TOK_AND:
     instrument_expression(node->pn_left, f);  
     fprintf(f, " && ");  
     instrument_expression(node->pn_right, f);  
     break;  
386    case TOK_BITOR:    case TOK_BITOR:
387    case TOK_BITXOR:    case TOK_BITXOR:
388    case TOK_BITAND:    case TOK_BITAND:
# Line 289  Line 396 
396      switch (node->pn_arity) {      switch (node->pn_arity) {
397      case PN_BINARY:      case PN_BINARY:
398        instrument_expression(node->pn_left, f);        instrument_expression(node->pn_left, f);
399        fprintf(f, " %s ", get_op(node->pn_op));        Stream_printf(f, " %s ", get_op(node->pn_op));
400        instrument_expression(node->pn_right, f);        instrument_expression(node->pn_right, f);
401        break;        break;
402      case PN_LIST:      case PN_LIST:
403        for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {        for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
404          if (p != node->pn_head) {          if (p != node->pn_head) {
405            fprintf(f, " %s ", get_op(node->pn_op));            Stream_printf(f, " %s ", get_op(node->pn_op));
406          }          }
407          instrument_expression(p, f);          instrument_expression(p, f);
408        }        }
# Line 307  Line 414 
414    case TOK_UNARYOP:    case TOK_UNARYOP:
415      switch (node->pn_op) {      switch (node->pn_op) {
416      case JSOP_NEG:      case JSOP_NEG:
417        fputc('-', f);        Stream_write_char(f, '-');
418        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
419        break;        break;
420      case JSOP_POS:      case JSOP_POS:
421        fputc('+', f);        Stream_write_char(f, '+');
422        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
423        break;        break;
424      case JSOP_NOT:      case JSOP_NOT:
425        fputc('!', f);        Stream_write_char(f, '!');
426        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
427        break;        break;
428      case JSOP_BITNOT:      case JSOP_BITNOT:
429        fputc('~', f);        Stream_write_char(f, '~');
430        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
431        break;        break;
432      case JSOP_TYPEOF:      case JSOP_TYPEOF:
433        fprintf(f, "typeof ");        Stream_write_string(f, "typeof ");
434        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
435        break;        break;
436      case JSOP_VOID:      case JSOP_VOID:
437        fprintf(f, "void ");        Stream_write_string(f, "void ");
438        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
439        break;        break;
440      default:      default:
# Line 344  Line 451 
451      case JSOP_INCNAME:      case JSOP_INCNAME:
452      case JSOP_INCPROP:      case JSOP_INCPROP:
453      case JSOP_INCELEM:      case JSOP_INCELEM:
454        fprintf(f, "++");        Stream_write_string(f, "++");
455        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
456        break;        break;
457      case JSOP_DECNAME:      case JSOP_DECNAME:
458      case JSOP_DECPROP:      case JSOP_DECPROP:
459      case JSOP_DECELEM:      case JSOP_DECELEM:
460        fprintf(f, "--");        Stream_write_string(f, "--");
461        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
462        break;        break;
463      case JSOP_NAMEINC:      case JSOP_NAMEINC:
464      case JSOP_PROPINC:      case JSOP_PROPINC:
465      case JSOP_ELEMINC:      case JSOP_ELEMINC:
466        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
467        fprintf(f, "++");        Stream_write_string(f, "++");
468        break;        break;
469      case JSOP_NAMEDEC:      case JSOP_NAMEDEC:
470      case JSOP_PROPDEC:      case JSOP_PROPDEC:
471      case JSOP_ELEMDEC:      case JSOP_ELEMDEC:
472        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
473        fprintf(f, "--");        Stream_write_string(f, "--");
474        break;        break;
475      default:      default:
476        abort();        abort();
# Line 371  Line 478 
478      }      }
479      break;      break;
480    case TOK_NEW:    case TOK_NEW:
481      fprintf(f, "new ");      Stream_write_string(f, "new ");
482      instrument_function_call(node, f);      instrument_function_call(node, f);
483      break;      break;
484    case TOK_DELETE:    case TOK_DELETE:
485      fprintf(f, "delete ");      Stream_write_string(f, "delete ");
486      instrument_expression(node->pn_kid, f);      instrument_expression(node->pn_kid, f);
487      break;      break;
488    case TOK_DOT:    case TOK_DOT:
# Line 388  Line 495 
495      assert(ATOM_IS_STRING(node->pn_atom));      assert(ATOM_IS_STRING(node->pn_atom));
496      {      {
497        JSString * s = ATOM_TO_STRING(node->pn_atom);        JSString * s = ATOM_TO_STRING(node->pn_atom);
498        /* XXX - semantics changed in 1.7 */        bool is_keyword = (js_CheckKeyword(JSSTRING_CHARS(s), JSSTRING_LENGTH(s)) != TOK_EOF);
499        if (! ATOM_KEYWORD(node->pn_atom) && js_IsIdentifier(s)) {        if (! is_keyword && js_IsIdentifier(s)) {
500          fputc('.', f);          Stream_write_char(f, '.');
501          print_string_atom(node->pn_atom, f);          print_string_atom(node->pn_atom, f);
502        }        }
503        else {        else {
504          fputc('[', f);          Stream_write_char(f, '[');
505          print_quoted_string_atom(node->pn_atom, f);          print_quoted_string_atom(node->pn_atom, f);
506          fputc(']', f);          Stream_write_char(f, ']');
507        }        }
508      }      }
509      break;      break;
510    case TOK_LB:    case TOK_LB:
511      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
512      fputc('[', f);      Stream_write_char(f, '[');
513      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
514      fputc(']', f);      Stream_write_char(f, ']');
515      break;      break;
516    case TOK_LP:    case TOK_LP:
517      instrument_function_call(node, f);      instrument_function_call(node, f);
518      break;      break;
519    case TOK_RB:    case TOK_RB:
520      fputc('[', f);      Stream_write_char(f, '[');
521      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
522        if (p != node->pn_head) {        if (p != node->pn_head) {
523          fprintf(f, ", ");          Stream_write_string(f, ", ");
524        }        }
525        /* TOK_COMMA is a special case: a hole in the array */        /* TOK_COMMA is a special case: a hole in the array */
526        if (p->pn_type != TOK_COMMA) {        if (p->pn_type != TOK_COMMA) {
# Line 421  Line 528 
528        }        }
529      }      }
530      if (node->pn_extra == PNX_ENDCOMMA) {      if (node->pn_extra == PNX_ENDCOMMA) {
531        fputc(',', f);        Stream_write_char(f, ',');
532      }      }
533      fputc(']', f);      Stream_write_char(f, ']');
534      break;      break;
535    case TOK_RC:    case TOK_RC:
536      fputc('{', f);      Stream_write_char(f, '{');
537      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
538        assert(p->pn_type == TOK_COLON);        assert(p->pn_type == TOK_COLON);
539        if (p != node->pn_head) {        if (p != node->pn_head) {
540          fprintf(f, ", ");          Stream_write_string(f, ", ");
541          }
542    
543          /* check whether this is a getter or setter */
544          switch (p->pn_op) {
545          case JSOP_GETTER:
546          case JSOP_SETTER:
547            if (p->pn_op == JSOP_GETTER) {
548              Stream_write_string(f, "get ");
549            }
550            else {
551              Stream_write_string(f, "set ");
552            }
553            instrument_expression(p->pn_left, f);
554            if (p->pn_right->pn_type != TOK_FUNCTION) {
555              fatal("parse error: expected function");
556            }
557            instrument_function(p->pn_right, f, 0, FUNCTION_GETTER_OR_SETTER);
558            break;
559          default:
560            instrument_expression(p->pn_left, f);
561            Stream_write_string(f, ": ");
562            instrument_expression(p->pn_right, f);
563            break;
564        }        }
       instrument_expression(p->pn_left, f);  
       fprintf(f, ": ");  
       instrument_expression(p->pn_right, f);  
565      }      }
566      fputc('}', f);      Stream_write_char(f, '}');
567      break;      break;
568    case TOK_RP:    case TOK_RP:
569      fputc('(', f);      Stream_write_char(f, '(');
570      instrument_expression(node->pn_kid, f);      instrument_expression(node->pn_kid, f);
571      fputc(')', f);      Stream_write_char(f, ')');
572      break;      break;
573    case TOK_NAME:    case TOK_NAME:
574      print_string_atom(node->pn_atom, f);      print_string_atom(node->pn_atom, f);
# Line 449  Line 576 
576    case TOK_STRING:    case TOK_STRING:
577      print_quoted_string_atom(node->pn_atom, f);      print_quoted_string_atom(node->pn_atom, f);
578      break;      break;
579    case TOK_OBJECT:    case TOK_REGEXP:
580      switch (node->pn_op) {      assert(node->pn_op == JSOP_REGEXP);
581      case JSOP_OBJECT:      {
582        /* I assume this is JSOP_REGEXP */        JSObject * object = node->pn_pob->object;
583        abort();        jsval result;
584        break;        js_regexp_toString(context, object, &result);
585      case JSOP_REGEXP:        print_regex(result, f);
       assert(ATOM_IS_OBJECT(node->pn_atom));  
       {  
         JSObject * object = ATOM_TO_OBJECT(node->pn_atom);  
         jsval result;  
         js_regexp_toString(context, object, 0, NULL, &result);  
         print_string_jsval(result, f);  
       }  
       break;  
     default:  
       abort();  
       break;  
586      }      }
587      break;      break;
588    case TOK_NUMBER:    case TOK_NUMBER:
# Line 477  Line 593 
593      To keep the output simple, special-case zero.      To keep the output simple, special-case zero.
594      */      */
595      if (node->pn_dval == 0.0) {      if (node->pn_dval == 0.0) {
596        fprintf(f, "0");        Stream_write_string(f, "0");
597      }      }
598      else {      else {
599        fprintf(f, "%.15g", node->pn_dval);        Stream_printf(f, "%.15g", node->pn_dval);
600      }      }
601      break;      break;
602    case TOK_PRIMARY:    case TOK_PRIMARY:
603      switch (node->pn_op) {      switch (node->pn_op) {
604      case JSOP_TRUE:      case JSOP_TRUE:
605        fprintf(f, "true");        Stream_write_string(f, "true");
606        break;        break;
607      case JSOP_FALSE:      case JSOP_FALSE:
608        fprintf(f, "false");        Stream_write_string(f, "false");
609        break;        break;
610      case JSOP_NULL:      case JSOP_NULL:
611        fprintf(f, "null");        Stream_write_string(f, "null");
612        break;        break;
613      case JSOP_THIS:      case JSOP_THIS:
614        fprintf(f, "this");        Stream_write_string(f, "this");
615        break;        break;
616      /* jsscan.h mentions `super' ??? */      /* jsscan.h mentions `super' ??? */
617      default:      default:
# Line 504  Line 620 
620      break;      break;
621    case TOK_INSTANCEOF:    case TOK_INSTANCEOF:
622      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
623      fprintf(f, " instanceof ");      Stream_write_string(f, " instanceof ");
624      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
625      break;      break;
626    case TOK_IN:    case TOK_IN:
627      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
628      fprintf(f, " in ");      Stream_write_string(f, " in ");
629      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
630      break;      break;
631    default:    default:
# Line 517  Line 633 
633    }    }
634  }  }
635    
636  static void instrument_var_statement(JSParseNode * node, FILE * f, int indent) {  static void instrument_var_statement(JSParseNode * node, Stream * f, int indent) {
637    assert(node->pn_arity == PN_LIST);    assert(node->pn_arity == PN_LIST);
638    fprintf(f, "%*s", indent, "");    Stream_printf(f, "%*s", indent, "");
639    fprintf(f, "var ");    Stream_write_string(f, "var ");
640    for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {    for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {
641      assert(p->pn_type == TOK_NAME);      assert(p->pn_type == TOK_NAME);
642      assert(p->pn_arity == PN_NAME);      assert(p->pn_arity == PN_NAME);
643      if (p != node->pn_head) {      if (p != node->pn_head) {
644        fprintf(f, ", ");        Stream_write_string(f, ", ");
645      }      }
646      print_string_atom(p->pn_atom, f);      print_string_atom(p->pn_atom, f);
647      if (p->pn_expr != NULL) {      if (p->pn_expr != NULL) {
648        fprintf(f, " = ");        Stream_write_string(f, " = ");
649        instrument_expression(p->pn_expr, f);        instrument_expression(p->pn_expr, f);
650      }      }
651    }    }
652  }  }
653    
654  static void output_statement(JSParseNode * node, FILE * f, int indent) {  static void output_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
655    switch (node->pn_type) {    switch (node->pn_type) {
656    case TOK_FUNCTION:    case TOK_FUNCTION:
657      instrument_function(node, f, indent);      instrument_function(node, f, indent, FUNCTION_NORMAL);
658      break;      break;
659    case TOK_LC:    case TOK_LC:
660      assert(node->pn_arity == PN_LIST);      assert(node->pn_arity == PN_LIST);
661  /*  /*
662      fprintf(f, "{\n");      Stream_write_string(f, "{\n");
663  */  */
664      for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {
665        instrument_statement(p, f, indent);        instrument_statement(p, f, indent, false);
666      }      }
667  /*  /*
668      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
669      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
670  */  */
671      break;      break;
672    case TOK_IF:    case TOK_IF:
673      {
674      assert(node->pn_arity == PN_TERNARY);      assert(node->pn_arity == PN_TERNARY);
675      fprintf(f, "%*s", indent, "");  
676      fprintf(f, "if (");      uint16_t line = node->pn_pos.begin.lineno;
677        if (! is_jscoverage_if) {
678          if (line > num_lines) {
679            fatal("%s: script contains more than 65,535 lines", file_id);
680          }
681          if (line >= 2 && exclusive_directives[line - 2]) {
682            is_jscoverage_if = true;
683          }
684        }
685    
686        Stream_printf(f, "%*s", indent, "");
687        Stream_write_string(f, "if (");
688      instrument_expression(node->pn_kid1, f);      instrument_expression(node->pn_kid1, f);
689      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
690      instrument_statement(node->pn_kid2, f, indent + 2);      if (is_jscoverage_if && node->pn_kid3) {
691      fprintf(f, "%*s", indent, "");        uint16_t else_start = node->pn_kid3->pn_pos.begin.lineno;
692      fprintf(f, "}\n");        uint16_t else_end = node->pn_kid3->pn_pos.end.lineno + 1;
693      if (node->pn_kid3) {        Stream_printf(f, "%*s", indent + 2, "");
694        fprintf(f, "%*s", indent, "");        Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, else_start, else_end);
695        fprintf(f, "else {\n");      }
696        instrument_statement(node->pn_kid3, f, indent + 2);      instrument_statement(node->pn_kid2, f, indent + 2, false);
697        fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
698        fprintf(f, "}\n");      Stream_write_string(f, "}\n");
699    
700        if (node->pn_kid3 || is_jscoverage_if) {
701          Stream_printf(f, "%*s", indent, "");
702          Stream_write_string(f, "else {\n");
703    
704          if (is_jscoverage_if) {
705            uint16_t if_start = node->pn_kid2->pn_pos.begin.lineno + 1;
706            uint16_t if_end = node->pn_kid2->pn_pos.end.lineno + 1;
707            Stream_printf(f, "%*s", indent + 2, "");
708            Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_start, if_end);
709          }
710    
711          if (node->pn_kid3) {
712            instrument_statement(node->pn_kid3, f, indent + 2, is_jscoverage_if);
713          }
714    
715          Stream_printf(f, "%*s", indent, "");
716          Stream_write_string(f, "}\n");
717      }      }
718    
719      break;      break;
720      }
721    case TOK_SWITCH:    case TOK_SWITCH:
722      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
723      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
724      fprintf(f, "switch (");      Stream_write_string(f, "switch (");
725      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
726      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
727      for (struct JSParseNode * p = node->pn_right->pn_head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_right->pn_head; p != NULL; p = p->pn_next) {
728        fprintf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
729        switch (p->pn_type) {        switch (p->pn_type) {
730        case TOK_CASE:        case TOK_CASE:
731          fprintf(f, "case ");          Stream_write_string(f, "case ");
732          instrument_expression(p->pn_left, f);          instrument_expression(p->pn_left, f);
733          fprintf(f, ":\n");          Stream_write_string(f, ":\n");
734          break;          break;
735        case TOK_DEFAULT:        case TOK_DEFAULT:
736          fprintf(f, "default:\n");          Stream_write_string(f, "default:\n");
737          break;          break;
738        default:        default:
739          abort();          abort();
740          break;          break;
741        }        }
742        instrument_statement(p->pn_right, f, indent + 2);        instrument_statement(p->pn_right, f, indent + 2, false);
743      }      }
744      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
745      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
746      break;      break;
747    case TOK_CASE:    case TOK_CASE:
748    case TOK_DEFAULT:    case TOK_DEFAULT:
# Line 602  Line 750 
750      break;      break;
751    case TOK_WHILE:    case TOK_WHILE:
752      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
753      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
754      fprintf(f, "while (");      Stream_write_string(f, "while (");
755      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
756      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
757      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
758      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
759      break;      break;
760    case TOK_DO:    case TOK_DO:
761      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
762      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
763      fprintf(f, "do {\n");      Stream_write_string(f, "do {\n");
764      instrument_statement(node->pn_left, f, indent + 2);      instrument_statement(node->pn_left, f, indent + 2, false);
765      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
766      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
767      fprintf(f, "while (");      Stream_write_string(f, "while (");
768      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
769      fprintf(f, ");\n");      Stream_write_string(f, ");\n");
770      break;      break;
771    case TOK_FOR:    case TOK_FOR:
772      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
773      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
774      fprintf(f, "for (");      Stream_write_string(f, "for ");
775        if (node->pn_iflags & JSITER_FOREACH) {
776          Stream_write_string(f, "each ");
777        }
778        Stream_write_char(f, '(');
779      switch (node->pn_left->pn_type) {      switch (node->pn_left->pn_type) {
780      case TOK_IN:      case TOK_IN:
781        /* for/in */        /* for/in */
# Line 646  Line 798 
798          break;          break;
799  */  */
800        }        }
801        fprintf(f, " in ");        Stream_write_string(f, " in ");
802        instrument_expression(node->pn_left->pn_right, f);        instrument_expression(node->pn_left->pn_right, f);
803        break;        break;
804      case TOK_RESERVED:      case TOK_RESERVED:
# Line 660  Line 812 
812            instrument_expression(node->pn_left->pn_kid1, f);            instrument_expression(node->pn_left->pn_kid1, f);
813          }          }
814        }        }
815        fprintf(f, ";");        Stream_write_string(f, ";");
816        if (node->pn_left->pn_kid2) {        if (node->pn_left->pn_kid2) {
817          fputc(' ', f);          Stream_write_char(f, ' ');
818          instrument_expression(node->pn_left->pn_kid2, f);          instrument_expression(node->pn_left->pn_kid2, f);
819        }        }
820        fprintf(f, ";");        Stream_write_string(f, ";");
821        if (node->pn_left->pn_kid3) {        if (node->pn_left->pn_kid3) {
822          fputc(' ', f);          Stream_write_char(f, ' ');
823          instrument_expression(node->pn_left->pn_kid3, f);          instrument_expression(node->pn_left->pn_kid3, f);
824        }        }
825        break;        break;
# Line 675  Line 827 
827        abort();        abort();
828        break;        break;
829      }      }
830      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
831      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
832      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
833      break;      break;
834    case TOK_THROW:    case TOK_THROW:
835      assert(node->pn_arity == PN_UNARY);      assert(node->pn_arity == PN_UNARY);
836      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
837      fprintf(f, "throw ");      Stream_write_string(f, "throw ");
838      instrument_expression(node->pn_u.unary.kid, f);      instrument_expression(node->pn_u.unary.kid, f);
839      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
840      break;      break;
841    case TOK_TRY:    case TOK_TRY:
842      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
843      fprintf(f, "try {\n");      Stream_write_string(f, "try {\n");
844      instrument_statement(node->pn_kid1, f, indent + 2);      instrument_statement(node->pn_kid1, f, indent + 2, false);
845      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
846      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
847      {      if (node->pn_kid2) {
848        for (JSParseNode * catch = node->pn_kid2; catch != NULL; catch = catch->pn_kid2) {        assert(node->pn_kid2->pn_type == TOK_RESERVED);
849          for (JSParseNode * scope = node->pn_kid2->pn_head; scope != NULL; scope = scope->pn_next) {
850            assert(scope->pn_type == TOK_LEXICALSCOPE);
851            JSParseNode * catch = scope->pn_expr;
852          assert(catch->pn_type == TOK_CATCH);          assert(catch->pn_type == TOK_CATCH);
853          fprintf(f, "%*s", indent, "");          Stream_printf(f, "%*s", indent, "");
854          fprintf(f, "catch (");          Stream_write_string(f, "catch (");
855          assert(catch->pn_kid1->pn_arity == PN_NAME);          assert(catch->pn_kid1->pn_arity == PN_NAME);
856          print_string_atom(catch->pn_kid1->pn_atom, f);          print_string_atom(catch->pn_kid1->pn_atom, f);
857          if (catch->pn_kid1->pn_expr) {          if (catch->pn_kid2) {
858            fprintf(f, " if ");            Stream_write_string(f, " if ");
859            instrument_expression(catch->pn_kid1->pn_expr, f);            instrument_expression(catch->pn_kid2, f);
860          }          }
861          fprintf(f, ") {\n");          Stream_write_string(f, ") {\n");
862          instrument_statement(catch->pn_kid3, f, indent + 2);          instrument_statement(catch->pn_kid3, f, indent + 2, false);
863          fprintf(f, "%*s", indent, "");          Stream_printf(f, "%*s", indent, "");
864          fprintf(f, "}\n");          Stream_write_string(f, "}\n");
865        }        }
866      }      }
867      if (node->pn_kid3) {      if (node->pn_kid3) {
868        fprintf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
869        fprintf(f, "finally {\n");        Stream_write_string(f, "finally {\n");
870        instrument_statement(node->pn_kid3, f, indent + 2);        instrument_statement(node->pn_kid3, f, indent + 2, false);
871        fprintf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
872        fprintf(f, "}\n");        Stream_write_string(f, "}\n");
873      }      }
874      break;      break;
875    case TOK_CATCH:    case TOK_CATCH:
# Line 723  Line 878 
878    case TOK_BREAK:    case TOK_BREAK:
879    case TOK_CONTINUE:    case TOK_CONTINUE:
880      assert(node->pn_arity == PN_NAME || node->pn_arity == PN_NULLARY);      assert(node->pn_arity == PN_NAME || node->pn_arity == PN_NULLARY);
881      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
882      fputs(node->pn_type == TOK_BREAK? "break": "continue", f);      Stream_write_string(f, node->pn_type == TOK_BREAK? "break": "continue");
883      JSAtom * atom = node->pn_u.name.atom;      JSAtom * atom = node->pn_u.name.atom;
884      if (atom != NULL) {      if (atom != NULL) {
885        fputc(' ', f);        Stream_write_char(f, ' ');
886        print_string_atom(node->pn_atom, f);        print_string_atom(node->pn_atom, f);
887      }      }
888      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
889      break;      break;
890    case TOK_WITH:    case TOK_WITH:
891      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
892      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
893      fprintf(f, "with (");      Stream_write_string(f, "with (");
894      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
895      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
896      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
897      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
898      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
899      break;      break;
900    case TOK_VAR:    case TOK_VAR:
901      instrument_var_statement(node, f, indent);      instrument_var_statement(node, f, indent);
902      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
903      break;      break;
904    case TOK_RETURN:    case TOK_RETURN:
905      assert(node->pn_arity == PN_UNARY);      assert(node->pn_arity == PN_UNARY);
906      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
907      fprintf(f, "return");      Stream_write_string(f, "return");
908      if (node->pn_kid != NULL) {      if (node->pn_kid != NULL) {
909        fprintf(f, " ");        Stream_write_char(f, ' ');
910        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
911      }      }
912      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
913      break;      break;
914    case TOK_SEMI:    case TOK_SEMI:
915      assert(node->pn_arity == PN_UNARY);      assert(node->pn_arity == PN_UNARY);
916      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
917      if (node->pn_kid != NULL) {      if (node->pn_kid != NULL) {
918        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
919      }      }
920      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
921      break;      break;
922    case TOK_COLON:    case TOK_COLON:
923      assert(node->pn_arity == PN_NAME);      assert(node->pn_arity == PN_NAME);
# Line 770  Line 925 
925      This one is tricky: can't output instrumentation between the label and the      This one is tricky: can't output instrumentation between the label and the
926      statement it's supposed to label ...      statement it's supposed to label ...
927      */      */
928      fprintf(f, "%*s", indent < 2? 0: indent - 2, "");      Stream_printf(f, "%*s", indent < 2? 0: indent - 2, "");
929      print_string_atom(node->pn_atom, f);      print_string_atom(node->pn_atom, f);
930      fprintf(f, ":\n");      Stream_write_string(f, ":\n");
931      /*      /*
932      ... use output_statement instead of instrument_statement.      ... use output_statement instead of instrument_statement.
933      */      */
934      output_statement(node->pn_expr, f, indent);      output_statement(node->pn_expr, f, indent, false);
935      break;      break;
936    default:    default:
937      fatal("unsupported node type in file %s: %d", file_id, node->pn_type);      fatal("unsupported node type in file %s: %d", file_id, node->pn_type);
# Line 788  Line 943 
943  TOK_FUNCTION is handled as a statement and as an expression.  TOK_FUNCTION is handled as a statement and as an expression.
944  TOK_EXPORT, TOK_IMPORT are not handled.  TOK_EXPORT, TOK_IMPORT are not handled.
945  */  */
946  static void instrument_statement(JSParseNode * node, FILE * f, int indent) {  static void instrument_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
947    if (node->pn_type != TOK_LC) {    if (node->pn_type != TOK_LC) {
948      int line = node->pn_pos.begin.lineno;      uint16_t line = node->pn_pos.begin.lineno;
949        if (line > num_lines) {
950          fatal("%s: script contains more than 65,535 lines", file_id);
951        }
952    
953      /* the root node has line number 0 */      /* the root node has line number 0 */
954      if (line != 0) {      if (line != 0) {
955        fprintf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
956        fprintf(f, "_$jscoverage['%s'][%d]++;\n", file_id, line);        Stream_printf(f, "_$jscoverage['%s'][%d]++;\n", file_id, line);
957        lines[line - 1] = 1;        lines[line - 1] = 1;
958      }      }
959    }    }
960    output_statement(node, f, indent);    output_statement(node, f, indent, is_jscoverage_if);
961  }  }
962    
963  static void instrument_js_stream(const char * id, int line, FILE * input, FILE * output, const char * temporary_file_name) {  static bool characters_start_with(const jschar * characters, size_t line_start, size_t line_end, const char * prefix) {
964    file_id = id;    const jschar * characters_end = characters + line_end;
965      const jschar * cp = characters + line_start;
966      const char * bp = prefix;
967      for (;;) {
968        if (*bp == '\0') {
969          return true;
970        }
971        else if (cp == characters_end) {
972          return false;
973        }
974        else if (*cp != *bp) {
975          return false;
976        }
977        bp++;
978        cp++;
979      }
980    }
981    
982    /* scan the javascript */  static bool characters_are_white_space(const jschar * characters, size_t line_start, size_t line_end) {
983    JSTokenStream * token_stream = js_NewFileTokenStream(context, NULL, input);    /* XXX - other Unicode space */
984    if (token_stream == NULL) {    const jschar * end = characters + line_end;
985      fatal("cannot create token stream from file: %s", file_id);    for (const jschar * p = characters + line_start; p < end; p++) {
986        jschar c = *p;
987        if (c == 0x9 || c == 0xB || c == 0xC || c == 0x20 || c == 0xA0) {
988          continue;
989        }
990        else {
991          return false;
992        }
993    }    }
994      return true;
995    }
996    
997    static void error_reporter(JSContext * context, const char * message, JSErrorReport * report) {
998      fprintf(stderr, "jscoverage: parse error: line %u: %s\n", report->lineno, message);
999    }
1000    
1001    void jscoverage_instrument_js(const char * id, const uint16_t * characters, size_t num_characters, Stream * output) {
1002      file_id = id;
1003    
1004    /* parse the javascript */    /* parse the javascript */
1005    JSParseNode * node = js_ParseTokenStream(context, global, token_stream);    JSParseContext parse_context;
1006      if (! js_InitParseContext(context, &parse_context, NULL, NULL, characters, num_characters, NULL, NULL, 1)) {
1007        fatal("cannot create token stream from file: %s", file_id);
1008      }
1009      JSErrorReporter old_error_reporter = JS_SetErrorReporter(context, error_reporter);
1010      JSParseNode * node = js_ParseScript(context, global, &parse_context);
1011    if (node == NULL) {    if (node == NULL) {
1012        js_ReportUncaughtException(context);
1013      fatal("parse error in file: %s", file_id);      fatal("parse error in file: %s", file_id);
1014    }    }
1015    int num_lines = node->pn_pos.end.lineno;    JS_SetErrorReporter(context, old_error_reporter);
1016      num_lines = node->pn_pos.end.lineno;
1017    lines = xmalloc(num_lines);    lines = xmalloc(num_lines);
1018    for (int i = 0; i < num_lines; i++) {    for (unsigned int i = 0; i < num_lines; i++) {
1019      lines[i] = 0;      lines[i] = 0;
1020    }    }
1021    
1022      /* search code for conditionals */
1023      exclusive_directives = xnew(bool, num_lines);
1024      for (unsigned int i = 0; i < num_lines; i++) {
1025        exclusive_directives[i] = false;
1026      }
1027    
1028      bool has_conditionals = false;
1029      struct IfDirective * if_directives = NULL;
1030      size_t line_number = 0;
1031      size_t i = 0;
1032      while (i < num_characters) {
1033        if (line_number == UINT16_MAX) {
1034          fatal("%s: script has more than 65,535 lines", file_id);
1035        }
1036        line_number++;
1037        size_t line_start = i;
1038        jschar c;
1039        bool done = false;
1040        while (! done && i < num_characters) {
1041          c = characters[i];
1042          switch (c) {
1043          case '\r':
1044          case '\n':
1045          case 0x2028:
1046          case 0x2029:
1047            done = true;
1048            break;
1049          default:
1050            i++;
1051          }
1052        }
1053        size_t line_end = i;
1054        if (i < num_characters) {
1055          i++;
1056          if (c == '\r' && i < num_characters && characters[i] == '\n') {
1057            i++;
1058          }
1059        }
1060    
1061        if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_IF")) {
1062          has_conditionals = true;
1063    
1064          if (characters_are_white_space(characters, line_start + 16, line_end)) {
1065            exclusive_directives[line_number - 1] = true;
1066          }
1067          else {
1068            struct IfDirective * if_directive = xnew(struct IfDirective, 1);
1069            if_directive->condition_start = characters + line_start + 16;
1070            if_directive->condition_end = characters + line_end;
1071            if_directive->start_line = line_number;
1072            if_directive->end_line = 0;
1073            if_directive->next = if_directives;
1074            if_directives = if_directive;
1075          }
1076        }
1077        else if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_ENDIF")) {
1078          for (struct IfDirective * p = if_directives; p != NULL; p = p->next) {
1079            if (p->end_line == 0) {
1080              p->end_line = line_number;
1081              break;
1082            }
1083          }
1084        }
1085      }
1086    
1087    /*    /*
1088    Create a temporary file - we can't write directly to the output because we    An instrumented JavaScript file has 4 sections:
1089    need to know the line number info first.    1. initialization
1090      2. instrumented source code
1091      3. conditionals
1092      4. original source code
1093    */    */
   FILE * temporary = fopen(temporary_file_name, "w+");  
   if (temporary == NULL) {  
     fatal("cannot create temporary file for script: %s", file_id);  
   }  
1094    
1095    /* write instrumented javascript to the temporary */    Stream * instrumented = Stream_new(0);
1096    instrument_statement(node, temporary, 0);    instrument_statement(node, instrumented, 0, false);
1097      js_FinishParseContext(context, &parse_context);
1098    
1099    /* write line number info to the output */    /* write line number info to the output */
1100    fprintf(output, "/* automatically generated by JSCoverage - do not edit */\n");    Stream_write_string(output, "/* automatically generated by JSCoverage - do not edit */\n");
1101    fprintf(output, "if (! top._$jscoverage) {\n  top._$jscoverage = {};\n}\n");    Stream_write_string(output, "if (! top._$jscoverage) {\n  top._$jscoverage = {};\n}\n");
1102    fprintf(output, "var _$jscoverage = top._$jscoverage;\n");    Stream_write_string(output, "var _$jscoverage = top._$jscoverage;\n");
1103    fprintf(output, "if (! _$jscoverage['%s']) {\n", file_id);    Stream_printf(output, "if (! _$jscoverage['%s']) {\n", file_id);
1104    fprintf(output, "  _$jscoverage['%s'] = [];\n", file_id);    Stream_printf(output, "  _$jscoverage['%s'] = [];\n", file_id);
1105    for (int i = 0; i < num_lines; i++) {    for (int i = 0; i < num_lines; i++) {
1106      if (lines[i]) {      if (lines[i]) {
1107        fprintf(output, "  _$jscoverage['%s'][%d] = 0;\n", file_id, i + 1);        Stream_printf(output, "  _$jscoverage['%s'][%d] = 0;\n", file_id, i + 1);
1108      }      }
1109    }    }
1110    fprintf(output, "}\n");    Stream_write_string(output, "}\n");
1111    free(lines);    free(lines);
1112    lines = NULL;    lines = NULL;
1113      free(exclusive_directives);
1114      exclusive_directives = NULL;
1115    
1116      /* conditionals */
1117      if (has_conditionals) {
1118        Stream_printf(output, "_$jscoverage['%s'].conditionals = [];\n", file_id);
1119      }
1120    
1121      /* copy the instrumented source code to the output */
1122      Stream_write(output, instrumented->data, instrumented->length);
1123    
1124    /* copy the temporary to the output */    /* conditionals */
1125    fseek(temporary, 0, SEEK_SET);    for (struct IfDirective * if_directive = if_directives; if_directive != NULL; if_directive = if_directive->next) {
1126    copy_stream(temporary, output);      Stream_write_string(output, "if (!(");
1127        print_javascript(if_directive->condition_start, if_directive->condition_end - if_directive->condition_start, output);
1128        Stream_write_string(output, ")) {\n");
1129        Stream_printf(output, "  _$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_directive->start_line, if_directive->end_line);
1130        Stream_write_string(output, "}\n");
1131      }
1132    
1133    fclose(temporary);    /* free */
1134      while (if_directives != NULL) {
1135        struct IfDirective * if_directive = if_directives;
1136        if_directives = if_directives->next;
1137        free(if_directive);
1138      }
1139    
1140      /* copy the original source to the output */
1141      Stream_printf(output, "_$jscoverage['%s'].source = ", file_id);
1142      jscoverage_write_source(id, characters, num_characters, output);
1143      Stream_printf(output, ";\n");
1144    
1145      Stream_delete(instrumented);
1146    
1147    file_id = NULL;    file_id = NULL;
1148  }  }
1149    
1150  void jscoverage_instrument_js(const char * id, FILE * input, FILE * output, const char * temporary_file_name) {  void jscoverage_write_source(const char * id, const jschar * characters, size_t num_characters, Stream * output) {
1151    instrument_js_stream(id, 0, input, output, temporary_file_name);    Stream_write_string(output, "[");
1152      if (jscoverage_highlight) {
1153        Stream * highlighted_stream = Stream_new(num_characters);
1154        jscoverage_highlight_js(context, id, characters, num_characters, highlighted_stream);
1155        size_t i = 0;
1156        while (i < highlighted_stream->length) {
1157          if (i > 0) {
1158            Stream_write_char(output, ',');
1159          }
1160    
1161          Stream_write_char(output, '"');
1162          bool done = false;
1163          while (! done) {
1164            char c = highlighted_stream->data[i];
1165            switch (c) {
1166            case 0x8:
1167              /* backspace */
1168              Stream_write_string(output, "\\b");
1169              break;
1170            case 0x9:
1171              /* horizontal tab */
1172              Stream_write_string(output, "\\t");
1173              break;
1174            case 0xa:
1175              /* line feed (new line) */
1176              done = true;
1177              break;
1178            /* IE doesn't support this */
1179            /*
1180            case 0xb:
1181              Stream_write_string(output, "\\v");
1182              break;
1183            */
1184            case 0xc:
1185              /* form feed */
1186              Stream_write_string(output, "\\f");
1187              break;
1188            case 0xd:
1189              /* carriage return */
1190              done = true;
1191              if (i + 1 < highlighted_stream->length && highlighted_stream->data[i + 1] == '\n') {
1192                i++;
1193              }
1194              break;
1195            case '"':
1196              Stream_write_string(output, "\\\"");
1197              break;
1198            case '\\':
1199              Stream_write_string(output, "\\\\");
1200              break;
1201            default:
1202              Stream_write_char(output, c);
1203              break;
1204            }
1205            i++;
1206            if (i >= highlighted_stream->length) {
1207              done = true;
1208            }
1209          }
1210          Stream_write_char(output, '"');
1211        }
1212        Stream_delete(highlighted_stream);
1213      }
1214      else {
1215        size_t i = 0;
1216        while (i < num_characters) {
1217          if (i > 0) {
1218            Stream_write_char(output, ',');
1219          }
1220    
1221          Stream_write_char(output, '"');
1222          bool done = false;
1223          while (! done) {
1224            jschar c = characters[i];
1225            switch (c) {
1226            case 0x8:
1227              /* backspace */
1228              Stream_write_string(output, "\\b");
1229              break;
1230            case 0x9:
1231              /* horizontal tab */
1232              Stream_write_string(output, "\\t");
1233              break;
1234            case 0xa:
1235              /* line feed (new line) */
1236              done = true;
1237              break;
1238            /* IE doesn't support this */
1239            /*
1240            case 0xb:
1241              Stream_write_string(output, "\\v");
1242              break;
1243            */
1244            case 0xc:
1245              /* form feed */
1246              Stream_write_string(output, "\\f");
1247              break;
1248            case 0xd:
1249              /* carriage return */
1250              done = true;
1251              if (i + 1 < num_characters && characters[i + 1] == '\n') {
1252                i++;
1253              }
1254              break;
1255            case '"':
1256              Stream_write_string(output, "\\\"");
1257              break;
1258            case '\\':
1259              Stream_write_string(output, "\\\\");
1260              break;
1261            case '&':
1262              Stream_write_string(output, "&amp;");
1263              break;
1264            case '<':
1265              Stream_write_string(output, "&lt;");
1266              break;
1267            case '>':
1268              Stream_write_string(output, "&gt;");
1269              break;
1270            case 0x2028:
1271            case 0x2029:
1272              done = true;
1273              break;
1274            default:
1275              if (32 <= c && c <= 126) {
1276                Stream_write_char(output, c);
1277              }
1278              else {
1279                Stream_printf(output, "&#%d;", c);
1280              }
1281              break;
1282            }
1283            i++;
1284            if (i >= num_characters) {
1285              done = true;
1286            }
1287          }
1288          Stream_write_char(output, '"');
1289        }
1290      }
1291      Stream_write_string(output, "]");
1292    }
1293    
1294    void jscoverage_copy_resources(const char * destination_directory) {
1295      copy_resource("jscoverage.html", destination_directory);
1296      copy_resource("jscoverage.css", destination_directory);
1297      copy_resource("jscoverage.js", destination_directory);
1298      copy_resource("jscoverage-ie.css", destination_directory);
1299      copy_resource("jscoverage-throbber.gif", destination_directory);
1300      copy_resource("jscoverage-highlight.css", destination_directory);
1301    }
1302    
1303    /*
1304    coverage reports
1305    */
1306    
1307    struct FileCoverageList {
1308      FileCoverage * file_coverage;
1309      struct FileCoverageList * next;
1310    };
1311    
1312    struct Coverage {
1313      JSHashTable * coverage_table;
1314      struct FileCoverageList * coverage_list;
1315    };
1316    
1317    static int compare_strings(const void * p1, const void * p2) {
1318      return strcmp(p1, p2) == 0;
1319    }
1320    
1321    Coverage * Coverage_new(void) {
1322      Coverage * result = xmalloc(sizeof(Coverage));
1323      result->coverage_table = JS_NewHashTable(1024, JS_HashString, compare_strings, NULL, NULL, NULL);
1324      if (result->coverage_table == NULL) {
1325        fatal("cannot create hash table");
1326      }
1327      result->coverage_list = NULL;
1328      return result;
1329    }
1330    
1331    void Coverage_delete(Coverage * coverage) {
1332      JS_HashTableDestroy(coverage->coverage_table);
1333      struct FileCoverageList * p = coverage->coverage_list;
1334      while (p != NULL) {
1335        free(p->file_coverage->coverage_lines);
1336        if (p->file_coverage->source_lines != NULL) {
1337          for (uint32 i = 0; i < p->file_coverage->num_source_lines; i++) {
1338            free(p->file_coverage->source_lines[i]);
1339          }
1340          free(p->file_coverage->source_lines);
1341        }
1342        free(p->file_coverage->id);
1343        free(p->file_coverage);
1344        struct FileCoverageList * q = p;
1345        p = p->next;
1346        free(q);
1347      }
1348      free(coverage);
1349    }
1350    
1351    struct EnumeratorArg {
1352      CoverageForeachFunction f;
1353      void * p;
1354    };
1355    
1356    static intN enumerator(JSHashEntry * entry, intN i, void * arg) {
1357      struct EnumeratorArg * enumerator_arg = arg;
1358      enumerator_arg->f(entry->value, i, enumerator_arg->p);
1359      return 0;
1360    }
1361    
1362    void Coverage_foreach_file(Coverage * coverage, CoverageForeachFunction f, void * p) {
1363      struct EnumeratorArg enumerator_arg;
1364      enumerator_arg.f = f;
1365      enumerator_arg.p = p;
1366      JS_HashTableEnumerateEntries(coverage->coverage_table, enumerator, &enumerator_arg);
1367    }
1368    
1369    int jscoverage_parse_json(Coverage * coverage, const uint8_t * json, size_t length) {
1370      int result = 0;
1371    
1372      jschar * base = js_InflateString(context, (char *) json, &length);
1373      if (base == NULL) {
1374        fatal("out of memory");
1375      }
1376    
1377      jschar * parenthesized_json = xnew(jschar, addst(length, 2));
1378      parenthesized_json[0] = '(';
1379      memcpy(parenthesized_json + 1, base, mulst(length, sizeof(jschar)));
1380      parenthesized_json[length + 1] = ')';
1381    
1382      JS_free(context, base);
1383    
1384      JSParseContext parse_context;
1385      if (! js_InitParseContext(context, &parse_context, NULL, NULL, parenthesized_json, length + 2, NULL, NULL, 1)) {
1386        free(parenthesized_json);
1387        return -1;
1388      }
1389      JSParseNode * root = js_ParseScript(context, global, &parse_context);
1390      free(parenthesized_json);
1391      if (root == NULL) {
1392        result = -1;
1393        goto done;
1394      }
1395    
1396      /* root node must be TOK_LC */
1397      if (root->pn_type != TOK_LC) {
1398        result = -1;
1399        goto done;
1400      }
1401      JSParseNode * semi = root->pn_u.list.head;
1402    
1403      /* the list must be TOK_SEMI and it must contain only one element */
1404      if (semi->pn_type != TOK_SEMI || semi->pn_next != NULL) {
1405        result = -1;
1406        goto done;
1407      }
1408      JSParseNode * parenthesized = semi->pn_kid;
1409    
1410      /* this must be a parenthesized expression */
1411      if (parenthesized->pn_type != TOK_RP) {
1412        result = -1;
1413        goto done;
1414      }
1415      JSParseNode * object = parenthesized->pn_kid;
1416    
1417      /* this must be an object literal */
1418      if (object->pn_type != TOK_RC) {
1419        result = -1;
1420        goto done;
1421      }
1422    
1423      for (JSParseNode * p = object->pn_head; p != NULL; p = p->pn_next) {
1424        /* every element of this list must be TOK_COLON */
1425        if (p->pn_type != TOK_COLON) {
1426          result = -1;
1427          goto done;
1428        }
1429    
1430        /* the key must be a string representing the file */
1431        JSParseNode * key = p->pn_left;
1432        if (key->pn_type != TOK_STRING || ! ATOM_IS_STRING(key->pn_atom)) {
1433          result = -1;
1434          goto done;
1435        }
1436        char * id_bytes = JS_GetStringBytes(ATOM_TO_STRING(key->pn_atom));
1437    
1438        /* the value must be an object literal OR an array */
1439        JSParseNode * value = p->pn_right;
1440        if (! (value->pn_type == TOK_RC || value->pn_type == TOK_RB)) {
1441          result = -1;
1442          goto done;
1443        }
1444    
1445        JSParseNode * array = NULL;
1446        JSParseNode * source = NULL;
1447        if (value->pn_type == TOK_RB) {
1448          /* an array */
1449          array = value;
1450        }
1451        else if (value->pn_type == TOK_RC) {
1452          /* an object literal */
1453          if (value->pn_count != 2) {
1454            result = -1;
1455            goto done;
1456          }
1457          for (JSParseNode * element = value->pn_head; element != NULL; element = element->pn_next) {
1458            if (element->pn_type != TOK_COLON) {
1459              result = -1;
1460              goto done;
1461            }
1462            JSParseNode * left = element->pn_left;
1463            if (left->pn_type != TOK_STRING || ! ATOM_IS_STRING(left->pn_atom)) {
1464              result = -1;
1465              goto done;
1466            }
1467            const char * s = JS_GetStringBytes(ATOM_TO_STRING(left->pn_atom));
1468            if (strcmp(s, "coverage") == 0) {
1469              array = element->pn_right;
1470              if (array->pn_type != TOK_RB) {
1471                result = -1;
1472                goto done;
1473              }
1474            }
1475            else if (strcmp(s, "source") == 0) {
1476              source = element->pn_right;
1477              if (source->pn_type != TOK_RB) {
1478                result = -1;
1479                goto done;
1480              }
1481            }
1482            else {
1483              result = -1;
1484              goto done;
1485            }
1486          }
1487        }
1488        else {
1489          result = -1;
1490          goto done;
1491        }
1492    
1493        if (array == NULL) {
1494          result = -1;
1495          goto done;
1496        }
1497    
1498        /* look up the file in the coverage table */
1499        FileCoverage * file_coverage = JS_HashTableLookup(coverage->coverage_table, id_bytes);
1500        if (file_coverage == NULL) {
1501          /* not there: create a new one */
1502          char * id = xstrdup(id_bytes);
1503          file_coverage = xmalloc(sizeof(FileCoverage));
1504          file_coverage->id = id;
1505          file_coverage->num_coverage_lines = array->pn_count;
1506          file_coverage->coverage_lines = xnew(int, array->pn_count);
1507          file_coverage->source_lines = NULL;
1508    
1509          /* set coverage for all lines */
1510          uint32 i = 0;
1511          for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
1512            if (element->pn_type == TOK_NUMBER) {
1513              file_coverage->coverage_lines[i] = (int) element->pn_dval;
1514            }
1515            else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
1516              file_coverage->coverage_lines[i] = -1;
1517            }
1518            else {
1519              result = -1;
1520              goto done;
1521            }
1522          }
1523          assert(i == array->pn_count);
1524    
1525          /* add to the hash table */
1526          JS_HashTableAdd(coverage->coverage_table, id, file_coverage);
1527          struct FileCoverageList * coverage_list = xmalloc(sizeof(struct FileCoverageList));
1528          coverage_list->file_coverage = file_coverage;
1529          coverage_list->next = coverage->coverage_list;
1530          coverage->coverage_list = coverage_list;
1531        }
1532        else {
1533          /* sanity check */
1534          assert(strcmp(file_coverage->id, id_bytes) == 0);
1535          if (file_coverage->num_coverage_lines != array->pn_count) {
1536            result = -2;
1537            goto done;
1538          }
1539    
1540          /* merge the coverage */
1541          uint32 i = 0;
1542          for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
1543            if (element->pn_type == TOK_NUMBER) {
1544              if (file_coverage->coverage_lines[i] == -1) {
1545                result = -2;
1546                goto done;
1547              }
1548              file_coverage->coverage_lines[i] += (int) element->pn_dval;
1549            }
1550            else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
1551              if (file_coverage->coverage_lines[i] != -1) {
1552                result = -2;
1553                goto done;
1554              }
1555            }
1556            else {
1557              result = -1;
1558              goto done;
1559            }
1560          }
1561          assert(i == array->pn_count);
1562        }
1563    
1564        /* if this JSON file has source, use it */
1565        if (file_coverage->source_lines == NULL && source != NULL) {
1566          file_coverage->num_source_lines = source->pn_count;
1567          file_coverage->source_lines = xnew(char *, source->pn_count);
1568          uint32 i = 0;
1569          for (JSParseNode * element = source->pn_head; element != NULL; element = element->pn_next, i++) {
1570            if (element->pn_type != TOK_STRING) {
1571              result = -1;
1572              goto done;
1573            }
1574            file_coverage->source_lines[i] = xstrdup(JS_GetStringBytes(ATOM_TO_STRING(element->pn_atom)));
1575          }
1576          assert(i == source->pn_count);
1577        }
1578      }
1579    
1580    done:
1581      js_FinishParseContext(context, &parse_context);
1582      return result;
1583  }  }

Legend:
Removed from v.90  
changed lines
  Added in v.339

  ViewVC Help
Powered by ViewVC 1.1.24