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

Diff of /trunk/instrument-js.cpp

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

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

Legend:
Removed from v.84  
changed lines
  Added in v.293

  ViewVC Help
Powered by ViewVC 1.1.24