1// Copyright 2012 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// LiveEdit feature implementation. The script should be executed after
6// debug.js.
7
8// A LiveEdit namespace. It contains functions that modifies JavaScript code
9// according to changes of script source (if possible).
10//
11// When new script source is put in, the difference is calculated textually,
12// in form of list of delete/add/change chunks. The functions that include
13// change chunk(s) get recompiled, or their enclosing functions are
14// recompiled instead.
15// If the function may not be recompiled (e.g. it was completely erased in new
16// version of the script) it remains unchanged, but the code that could
17// create a new instance of this function goes away. An old version of script
18// is created to back up this obsolete function.
19// All unchanged functions have their positions updated accordingly.
20//
21// LiveEdit namespace is declared inside a single function constructor.
22
23(function(global, utils) {
24  "use strict";
25
26  // -------------------------------------------------------------------
27  // Imports
28
29  var FindScriptSourcePosition = global.Debug.findScriptSourcePosition;
30  var GlobalArray = global.Array;
31  var MathFloor = global.Math.floor;
32  var MathMax = global.Math.max;
33  var SyntaxError = global.SyntaxError;
34
35  // -------------------------------------------------------------------
36
37  // Forward declaration for minifier.
38  var FunctionStatus;
39
40  // Applies the change to the script.
41  // The change is in form of list of chunks encoded in a single array as
42  // a series of triplets (pos1_start, pos1_end, pos2_end)
43  function ApplyPatchMultiChunk(script, diff_array, new_source, preview_only,
44      change_log) {
45
46    var old_source = script.source;
47
48    // Gather compile information about old version of script.
49    var old_compile_info = GatherCompileInfo(old_source, script);
50
51    // Build tree structures for old and new versions of the script.
52    var root_old_node = BuildCodeInfoTree(old_compile_info);
53
54    var pos_translator = new PosTranslator(diff_array);
55
56    // Analyze changes.
57    MarkChangedFunctions(root_old_node, pos_translator.GetChunks());
58
59    // Find all SharedFunctionInfo's that were compiled from this script.
60    FindLiveSharedInfos(root_old_node, script);
61
62    // Gather compile information about new version of script.
63    var new_compile_info;
64    try {
65      new_compile_info = GatherCompileInfo(new_source, script);
66    } catch (e) {
67      var failure =
68          new Failure("Failed to compile new version of script: " + e);
69      if (e instanceof SyntaxError) {
70        var details = {
71          type: "liveedit_compile_error",
72          syntaxErrorMessage: e.message
73        };
74        CopyErrorPositionToDetails(e, details);
75        failure.details = details;
76      }
77      throw failure;
78    }
79
80    var max_function_literal_id = new_compile_info.reduce(
81        (max, info) => MathMax(max, info.function_literal_id), 0);
82
83    var root_new_node = BuildCodeInfoTree(new_compile_info);
84
85    // Link recompiled script data with other data.
86    FindCorrespondingFunctions(root_old_node, root_new_node);
87
88    // Prepare to-do lists.
89    var replace_code_list = new GlobalArray();
90    var link_to_old_script_list = new GlobalArray();
91    var link_to_original_script_list = new GlobalArray();
92    var update_positions_list = new GlobalArray();
93
94    function HarvestTodo(old_node) {
95      function CollectDamaged(node) {
96        link_to_old_script_list.push(node);
97        for (var i = 0; i < node.children.length; i++) {
98          CollectDamaged(node.children[i]);
99        }
100      }
101
102      // Recursively collects all newly compiled functions that are going into
103      // business and should have link to the actual script updated.
104      function CollectNew(node_list) {
105        for (var i = 0; i < node_list.length; i++) {
106          link_to_original_script_list.push(node_list[i]);
107          CollectNew(node_list[i].children);
108        }
109      }
110
111      if (old_node.status == FunctionStatus.DAMAGED) {
112        CollectDamaged(old_node);
113        return;
114      }
115      if (old_node.status == FunctionStatus.UNCHANGED) {
116        update_positions_list.push(old_node);
117      } else if (old_node.status == FunctionStatus.SOURCE_CHANGED) {
118        update_positions_list.push(old_node);
119      } else if (old_node.status == FunctionStatus.CHANGED) {
120        replace_code_list.push(old_node);
121        CollectNew(old_node.unmatched_new_nodes);
122      }
123      for (var i = 0; i < old_node.children.length; i++) {
124        HarvestTodo(old_node.children[i]);
125      }
126    }
127
128    var preview_description = {
129        change_tree: DescribeChangeTree(root_old_node),
130        textual_diff: {
131          old_len: old_source.length,
132          new_len: new_source.length,
133          chunks: diff_array
134        },
135        updated: false
136    };
137
138    if (preview_only) {
139      return preview_description;
140    }
141
142    HarvestTodo(root_old_node);
143
144    // Collect shared infos for functions whose code need to be patched.
145    var replaced_function_old_infos = new GlobalArray();
146    var replaced_function_new_infos = new GlobalArray();
147    for (var i = 0; i < replace_code_list.length; i++) {
148      var old_infos = replace_code_list[i].live_shared_function_infos;
149      var new_info =
150          replace_code_list[i].corresponding_node.info.shared_function_info;
151
152      if (old_infos) {
153        for (var j = 0; j < old_infos.length; j++) {
154          replaced_function_old_infos.push(old_infos[j]);
155          replaced_function_new_infos.push(new_info);
156        }
157      }
158    }
159
160    // We haven't changed anything before this line yet.
161    // Committing all changes.
162
163    // Check that function being patched is not currently on stack or drop them.
164    var dropped_functions_number =
165        CheckStackActivations(replaced_function_old_infos,
166                              replaced_function_new_infos,
167                              change_log);
168
169    // Our current implementation requires client to manually issue "step in"
170    // command for correct stack state if the stack was modified.
171    preview_description.stack_modified = dropped_functions_number != 0;
172
173    var old_script;
174
175    // Create an old script only if there are function that should be linked
176    // to old version.
177    if (link_to_old_script_list.length == 0) {
178      %LiveEditReplaceScript(script, new_source, null);
179      old_script = UNDEFINED;
180    } else {
181      var old_script_name = CreateNameForOldScript(script);
182
183      // Update the script text and create a new script representing an old
184      // version of the script.
185      old_script = %LiveEditReplaceScript(script, new_source, old_script_name);
186
187      var link_to_old_script_report = new GlobalArray();
188      change_log.push( { linked_to_old_script: link_to_old_script_report } );
189
190      // We need to link to old script all former nested functions.
191      for (var i = 0; i < link_to_old_script_list.length; i++) {
192        LinkToOldScript(link_to_old_script_list[i], old_script,
193            link_to_old_script_report);
194      }
195
196      preview_description.created_script_name = old_script_name;
197    }
198
199    for (var i = 0; i < replace_code_list.length; i++) {
200      PatchFunctionCode(replace_code_list[i], change_log);
201    }
202
203    var position_patch_report = new GlobalArray();
204    change_log.push( {position_patched: position_patch_report} );
205
206    for (var i = 0; i < update_positions_list.length; i++) {
207      // TODO(LiveEdit): take into account whether it's source_changed or
208      // unchanged and whether positions changed at all.
209      PatchPositions(update_positions_list[i], diff_array,
210          position_patch_report);
211
212      if (update_positions_list[i].live_shared_function_infos) {
213        var new_function_literal_id =
214            update_positions_list[i]
215                .corresponding_node.info.function_literal_id;
216        update_positions_list[i].live_shared_function_infos.forEach(function(
217            info) {
218          %LiveEditFunctionSourceUpdated(
219              info.raw_array, new_function_literal_id);
220        });
221      }
222    }
223
224    %LiveEditFixupScript(script, max_function_literal_id);
225
226    // Link all the functions we're going to use to an actual script.
227    for (var i = 0; i < link_to_original_script_list.length; i++) {
228      %LiveEditFunctionSetScript(
229          link_to_original_script_list[i].info.shared_function_info, script);
230    }
231
232    preview_description.updated = true;
233    return preview_description;
234  }
235
236  // Fully compiles source string as a script. Returns Array of
237  // FunctionCompileInfo -- a descriptions of all functions of the script.
238  // Elements of array are ordered by start positions of functions (from top
239  // to bottom) in the source. Fields outer_index and next_sibling_index help
240  // to navigate the nesting structure of functions.
241  //
242  // All functions get compiled linked to script provided as parameter script.
243  // TODO(LiveEdit): consider not using actual scripts as script, because
244  // we have to manually erase all links right after compile.
245  function GatherCompileInfo(source, script) {
246    // Get function info, elements are partially sorted (it is a tree of
247    // nested functions serialized as parent followed by serialized children.
248    var raw_compile_info = %LiveEditGatherCompileInfo(script, source);
249
250    // Sort function infos by start position field.
251    var compile_info = new GlobalArray();
252    var old_index_map = new GlobalArray();
253    for (var i = 0; i < raw_compile_info.length; i++) {
254      var info = new FunctionCompileInfo(raw_compile_info[i]);
255      // Remove all links to the actual script. Breakpoints system and
256      // LiveEdit itself believe that any function in heap that points to a
257      // particular script is a regular function.
258      // For some functions we will restore this link later.
259      %LiveEditFunctionSetScript(info.shared_function_info, UNDEFINED);
260      compile_info.push(info);
261      old_index_map.push(i);
262    }
263
264    for (var i = 0; i < compile_info.length; i++) {
265      var k = i;
266      for (var j = i + 1; j < compile_info.length; j++) {
267        if (compile_info[k].start_position > compile_info[j].start_position) {
268          k = j;
269        }
270      }
271      if (k != i) {
272        var temp_info = compile_info[k];
273        var temp_index = old_index_map[k];
274        compile_info[k] = compile_info[i];
275        old_index_map[k] = old_index_map[i];
276        compile_info[i] = temp_info;
277        old_index_map[i] = temp_index;
278      }
279    }
280
281    // After sorting update outer_index field using old_index_map. Also
282    // set next_sibling_index field.
283    var current_index = 0;
284
285    // The recursive function, that goes over all children of a particular
286    // node (i.e. function info).
287    function ResetIndexes(new_parent_index, old_parent_index) {
288      var previous_sibling = -1;
289      while (current_index < compile_info.length &&
290          compile_info[current_index].outer_index == old_parent_index) {
291        var saved_index = current_index;
292        compile_info[saved_index].outer_index = new_parent_index;
293        if (previous_sibling != -1) {
294          compile_info[previous_sibling].next_sibling_index = saved_index;
295        }
296        previous_sibling = saved_index;
297        current_index++;
298        ResetIndexes(saved_index, old_index_map[saved_index]);
299      }
300      if (previous_sibling != -1) {
301        compile_info[previous_sibling].next_sibling_index = -1;
302      }
303    }
304
305    ResetIndexes(-1, -1);
306    Assert(current_index == compile_info.length);
307
308    return compile_info;
309  }
310
311
312  // Replaces function's Code.
313  function PatchFunctionCode(old_node, change_log) {
314    var new_info = old_node.corresponding_node.info;
315    if (old_node.live_shared_function_infos) {
316      old_node.live_shared_function_infos.forEach(function (old_info) {
317        %LiveEditReplaceFunctionCode(new_info.raw_array,
318                                     old_info.raw_array);
319
320        // The function got a new code. However, this new code brings all new
321        // instances of SharedFunctionInfo for nested functions. However,
322        // we want the original instances to be used wherever possible.
323        // (This is because old instances and new instances will be both
324        // linked to a script and breakpoints subsystem does not really
325        // expects this; neither does LiveEdit subsystem on next call).
326        for (var i = 0; i < old_node.children.length; i++) {
327          if (old_node.children[i].corresponding_node) {
328            var corresponding_child_info =
329                old_node.children[i].corresponding_node.info.
330                    shared_function_info;
331
332            if (old_node.children[i].live_shared_function_infos) {
333              old_node.children[i].live_shared_function_infos.
334                  forEach(function (old_child_info) {
335                    %LiveEditReplaceRefToNestedFunction(
336                        old_info.info,
337                        corresponding_child_info,
338                        old_child_info.info);
339                  });
340            }
341          }
342        }
343      });
344
345      change_log.push( {function_patched: new_info.function_name} );
346    } else {
347      change_log.push( {function_patched: new_info.function_name,
348          function_info_not_found: true} );
349    }
350  }
351
352
353  // Makes a function associated with another instance of a script (the
354  // one representing its old version). This way the function still
355  // may access its own text.
356  function LinkToOldScript(old_info_node, old_script, report_array) {
357    if (old_info_node.live_shared_function_infos) {
358      old_info_node.live_shared_function_infos.
359          forEach(function (info) {
360            %LiveEditFunctionSetScript(info.info, old_script);
361          });
362
363      report_array.push( { name: old_info_node.info.function_name } );
364    } else {
365      report_array.push(
366          { name: old_info_node.info.function_name, not_found: true } );
367    }
368  }
369
370  function Assert(condition, message) {
371    if (!condition) {
372      if (message) {
373        throw "Assert " + message;
374      } else {
375        throw "Assert";
376      }
377    }
378  }
379
380  function DiffChunk(pos1, pos2, len1, len2) {
381    this.pos1 = pos1;
382    this.pos2 = pos2;
383    this.len1 = len1;
384    this.len2 = len2;
385  }
386
387  function PosTranslator(diff_array) {
388    var chunks = new GlobalArray();
389    var current_diff = 0;
390    for (var i = 0; i < diff_array.length; i += 3) {
391      var pos1_begin = diff_array[i];
392      var pos2_begin = pos1_begin + current_diff;
393      var pos1_end = diff_array[i + 1];
394      var pos2_end = diff_array[i + 2];
395      chunks.push(new DiffChunk(pos1_begin, pos2_begin, pos1_end - pos1_begin,
396          pos2_end - pos2_begin));
397      current_diff = pos2_end - pos1_end;
398    }
399    this.chunks = chunks;
400  }
401  PosTranslator.prototype.GetChunks = function() {
402    return this.chunks;
403  };
404
405  PosTranslator.prototype.Translate = function(pos, inside_chunk_handler) {
406    var array = this.chunks;
407    if (array.length == 0 || pos < array[0].pos1) {
408      return pos;
409    }
410    var chunk_index1 = 0;
411    var chunk_index2 = array.length - 1;
412
413    while (chunk_index1 < chunk_index2) {
414      var middle_index = MathFloor((chunk_index1 + chunk_index2) / 2);
415      if (pos < array[middle_index + 1].pos1) {
416        chunk_index2 = middle_index;
417      } else {
418        chunk_index1 = middle_index + 1;
419      }
420    }
421    var chunk = array[chunk_index1];
422    if (pos >= chunk.pos1 + chunk.len1) {
423      return pos + chunk.pos2 + chunk.len2 - chunk.pos1 - chunk.len1;
424    }
425
426    if (!inside_chunk_handler) {
427      inside_chunk_handler = PosTranslator.DefaultInsideChunkHandler;
428    }
429    return inside_chunk_handler(pos, chunk);
430  };
431
432  PosTranslator.DefaultInsideChunkHandler = function(pos, diff_chunk) {
433    Assert(false, "Cannot translate position in changed area");
434  };
435
436  PosTranslator.ShiftWithTopInsideChunkHandler =
437      function(pos, diff_chunk) {
438    // We carelessly do not check whether we stay inside the chunk after
439    // translation.
440    return pos - diff_chunk.pos1 + diff_chunk.pos2;
441  };
442
443  var FunctionStatus = {
444      // No change to function or its inner functions; however its positions
445      // in script may have been shifted.
446      UNCHANGED: "unchanged",
447      // The code of a function remains unchanged, but something happened inside
448      // some inner functions.
449      SOURCE_CHANGED: "source changed",
450      // The code of a function is changed or some nested function cannot be
451      // properly patched so this function must be recompiled.
452      CHANGED: "changed",
453      // Function is changed but cannot be patched.
454      DAMAGED: "damaged"
455  };
456
457  function CodeInfoTreeNode(code_info, children, array_index) {
458    this.info = code_info;
459    this.children = children;
460    // an index in array of compile_info
461    this.array_index = array_index;
462    this.parent = UNDEFINED;
463
464    this.status = FunctionStatus.UNCHANGED;
465    // Status explanation is used for debugging purposes and will be shown
466    // in user UI if some explanations are needed.
467    this.status_explanation = UNDEFINED;
468    this.new_start_pos = UNDEFINED;
469    this.new_end_pos = UNDEFINED;
470    this.corresponding_node = UNDEFINED;
471    this.unmatched_new_nodes = UNDEFINED;
472
473    // 'Textual' correspondence/matching is weaker than 'pure'
474    // correspondence/matching. We need 'textual' level for visual presentation
475    // in UI, we use 'pure' level for actual code manipulation.
476    // Sometimes only function body is changed (functions in old and new script
477    // textually correspond), but we cannot patch the code, so we see them
478    // as an old function deleted and new function created.
479    this.textual_corresponding_node = UNDEFINED;
480    this.textually_unmatched_new_nodes = UNDEFINED;
481
482    this.live_shared_function_infos = UNDEFINED;
483  }
484
485  // From array of function infos that is implicitly a tree creates
486  // an actual tree of functions in script.
487  function BuildCodeInfoTree(code_info_array) {
488    // Throughtout all function we iterate over input array.
489    var index = 0;
490
491    // Recursive function that builds a branch of tree.
492    function BuildNode() {
493      var my_index = index;
494      index++;
495      var child_array = new GlobalArray();
496      while (index < code_info_array.length &&
497          code_info_array[index].outer_index == my_index) {
498        child_array.push(BuildNode());
499      }
500      var node = new CodeInfoTreeNode(code_info_array[my_index], child_array,
501          my_index);
502      for (var i = 0; i < child_array.length; i++) {
503        child_array[i].parent = node;
504      }
505      return node;
506    }
507
508    var root = BuildNode();
509    Assert(index == code_info_array.length);
510    return root;
511  }
512
513  // Applies a list of the textual diff chunks onto the tree of functions.
514  // Determines status of each function (from unchanged to damaged). However
515  // children of unchanged functions are ignored.
516  function MarkChangedFunctions(code_info_tree, chunks) {
517
518    // A convenient iterator over diff chunks that also translates
519    // positions from old to new in a current non-changed part of script.
520    var chunk_it = new function() {
521      var chunk_index = 0;
522      var pos_diff = 0;
523      this.current = function() { return chunks[chunk_index]; };
524      this.next = function() {
525        var chunk = chunks[chunk_index];
526        pos_diff = chunk.pos2 + chunk.len2 - (chunk.pos1 + chunk.len1);
527        chunk_index++;
528      };
529      this.done = function() { return chunk_index >= chunks.length; };
530      this.TranslatePos = function(pos) { return pos + pos_diff; };
531    };
532
533    // A recursive function that processes internals of a function and all its
534    // inner functions. Iterator chunk_it initially points to a chunk that is
535    // below function start.
536    function ProcessInternals(info_node) {
537      info_node.new_start_pos = chunk_it.TranslatePos(
538          info_node.info.start_position);
539      var child_index = 0;
540      var code_changed = false;
541      var source_changed = false;
542      // Simultaneously iterates over child functions and over chunks.
543      while (!chunk_it.done() &&
544          chunk_it.current().pos1 < info_node.info.end_position) {
545        if (child_index < info_node.children.length) {
546          var child = info_node.children[child_index];
547
548          if (child.info.end_position <= chunk_it.current().pos1) {
549            ProcessUnchangedChild(child);
550            child_index++;
551            continue;
552          } else if (child.info.start_position >=
553              chunk_it.current().pos1 + chunk_it.current().len1) {
554            code_changed = true;
555            chunk_it.next();
556            continue;
557          } else if (child.info.start_position <= chunk_it.current().pos1 &&
558              child.info.end_position >= chunk_it.current().pos1 +
559              chunk_it.current().len1) {
560            ProcessInternals(child);
561            source_changed = source_changed ||
562                ( child.status != FunctionStatus.UNCHANGED );
563            code_changed = code_changed ||
564                ( child.status == FunctionStatus.DAMAGED );
565            child_index++;
566            continue;
567          } else {
568            code_changed = true;
569            child.status = FunctionStatus.DAMAGED;
570            child.status_explanation =
571                "Text diff overlaps with function boundary";
572            child_index++;
573            continue;
574          }
575        } else {
576          if (chunk_it.current().pos1 + chunk_it.current().len1 <=
577              info_node.info.end_position) {
578            info_node.status = FunctionStatus.CHANGED;
579            chunk_it.next();
580            continue;
581          } else {
582            info_node.status = FunctionStatus.DAMAGED;
583            info_node.status_explanation =
584                "Text diff overlaps with function boundary";
585            return;
586          }
587        }
588        Assert("Unreachable", false);
589      }
590      while (child_index < info_node.children.length) {
591        var child = info_node.children[child_index];
592        ProcessUnchangedChild(child);
593        child_index++;
594      }
595      if (code_changed) {
596        info_node.status = FunctionStatus.CHANGED;
597      } else if (source_changed) {
598        info_node.status = FunctionStatus.SOURCE_CHANGED;
599      }
600      info_node.new_end_pos =
601          chunk_it.TranslatePos(info_node.info.end_position);
602    }
603
604    function ProcessUnchangedChild(node) {
605      node.new_start_pos = chunk_it.TranslatePos(node.info.start_position);
606      node.new_end_pos = chunk_it.TranslatePos(node.info.end_position);
607    }
608
609    ProcessInternals(code_info_tree);
610  }
611
612  // For each old function (if it is not damaged) tries to find a corresponding
613  // function in new script. Typically it should succeed (non-damaged functions
614  // by definition may only have changes inside their bodies). However there are
615  // reasons for correspondence not to be found; function with unmodified text
616  // in new script may become enclosed into other function; the innocent change
617  // inside function body may in fact be something like "} function B() {" that
618  // splits a function into 2 functions.
619  function FindCorrespondingFunctions(old_code_tree, new_code_tree) {
620
621    // A recursive function that tries to find a correspondence for all
622    // child functions and for their inner functions.
623    function ProcessNode(old_node, new_node) {
624      var scope_change_description =
625          IsFunctionContextLocalsChanged(old_node.info, new_node.info);
626      if (scope_change_description) {
627        old_node.status = FunctionStatus.CHANGED;
628      }
629
630      var old_children = old_node.children;
631      var new_children = new_node.children;
632
633      var unmatched_new_nodes_list = [];
634      var textually_unmatched_new_nodes_list = [];
635
636      var old_index = 0;
637      var new_index = 0;
638      while (old_index < old_children.length) {
639        if (old_children[old_index].status == FunctionStatus.DAMAGED) {
640          old_index++;
641        } else if (new_index < new_children.length) {
642          if (new_children[new_index].info.start_position <
643              old_children[old_index].new_start_pos) {
644            unmatched_new_nodes_list.push(new_children[new_index]);
645            textually_unmatched_new_nodes_list.push(new_children[new_index]);
646            new_index++;
647          } else if (new_children[new_index].info.start_position ==
648              old_children[old_index].new_start_pos) {
649            if (new_children[new_index].info.end_position ==
650                old_children[old_index].new_end_pos) {
651              old_children[old_index].corresponding_node =
652                  new_children[new_index];
653              old_children[old_index].textual_corresponding_node =
654                  new_children[new_index];
655              if (scope_change_description) {
656                old_children[old_index].status = FunctionStatus.DAMAGED;
657                old_children[old_index].status_explanation =
658                    "Enclosing function is now incompatible. " +
659                    scope_change_description;
660                old_children[old_index].corresponding_node = UNDEFINED;
661              } else if (old_children[old_index].status !=
662                  FunctionStatus.UNCHANGED) {
663                ProcessNode(old_children[old_index],
664                    new_children[new_index]);
665                if (old_children[old_index].status == FunctionStatus.DAMAGED) {
666                  unmatched_new_nodes_list.push(
667                      old_children[old_index].corresponding_node);
668                  old_children[old_index].corresponding_node = UNDEFINED;
669                  old_node.status = FunctionStatus.CHANGED;
670                }
671              } else {
672                ProcessNode(old_children[old_index], new_children[new_index]);
673              }
674            } else {
675              old_children[old_index].status = FunctionStatus.DAMAGED;
676              old_children[old_index].status_explanation =
677                  "No corresponding function in new script found";
678              old_node.status = FunctionStatus.CHANGED;
679              unmatched_new_nodes_list.push(new_children[new_index]);
680              textually_unmatched_new_nodes_list.push(new_children[new_index]);
681            }
682            new_index++;
683            old_index++;
684          } else {
685            old_children[old_index].status = FunctionStatus.DAMAGED;
686            old_children[old_index].status_explanation =
687                "No corresponding function in new script found";
688            old_node.status = FunctionStatus.CHANGED;
689            old_index++;
690          }
691        } else {
692          old_children[old_index].status = FunctionStatus.DAMAGED;
693          old_children[old_index].status_explanation =
694              "No corresponding function in new script found";
695          old_node.status = FunctionStatus.CHANGED;
696          old_index++;
697        }
698      }
699
700      while (new_index < new_children.length) {
701        unmatched_new_nodes_list.push(new_children[new_index]);
702        textually_unmatched_new_nodes_list.push(new_children[new_index]);
703        new_index++;
704      }
705
706      if (old_node.status == FunctionStatus.CHANGED) {
707        if (old_node.info.param_num != new_node.info.param_num) {
708          old_node.status = FunctionStatus.DAMAGED;
709          old_node.status_explanation = "Changed parameter number: " +
710              old_node.info.param_num + " and " + new_node.info.param_num;
711        }
712      }
713      old_node.unmatched_new_nodes = unmatched_new_nodes_list;
714      old_node.textually_unmatched_new_nodes =
715          textually_unmatched_new_nodes_list;
716    }
717
718    ProcessNode(old_code_tree, new_code_tree);
719
720    old_code_tree.corresponding_node = new_code_tree;
721    old_code_tree.textual_corresponding_node = new_code_tree;
722
723    Assert(old_code_tree.status != FunctionStatus.DAMAGED,
724        "Script became damaged");
725  }
726
727  function FindLiveSharedInfos(old_code_tree, script) {
728    var shared_raw_list = %LiveEditFindSharedFunctionInfosForScript(script);
729
730    var shared_infos = new GlobalArray();
731
732    for (var i = 0; i < shared_raw_list.length; i++) {
733      shared_infos.push(new SharedInfoWrapper(shared_raw_list[i]));
734    }
735
736    // Finds all SharedFunctionInfos that corresponds to compile info
737    // in old version of the script.
738    function FindFunctionInfos(compile_info) {
739      var wrappers = [];
740
741      for (var i = 0; i < shared_infos.length; i++) {
742        var wrapper = shared_infos[i];
743        if (wrapper.start_position == compile_info.start_position &&
744            wrapper.end_position == compile_info.end_position) {
745          wrappers.push(wrapper);
746        }
747      }
748
749      if (wrappers.length > 0) {
750        return wrappers;
751      }
752    }
753
754    function TraverseTree(node) {
755      node.live_shared_function_infos = FindFunctionInfos(node.info);
756
757      for (var i = 0; i < node.children.length; i++) {
758        TraverseTree(node.children[i]);
759      }
760    }
761
762    TraverseTree(old_code_tree);
763  }
764
765
766  // An object describing function compilation details. Its index fields
767  // apply to indexes inside array that stores these objects.
768  function FunctionCompileInfo(raw_array) {
769    this.function_name = raw_array[0];
770    this.start_position = raw_array[1];
771    this.end_position = raw_array[2];
772    this.param_num = raw_array[3];
773    this.scope_info = raw_array[4];
774    this.outer_index = raw_array[5];
775    this.shared_function_info = raw_array[6];
776    this.function_literal_id = raw_array[7];
777    this.next_sibling_index = null;
778    this.raw_array = raw_array;
779  }
780
781  function SharedInfoWrapper(raw_array) {
782    this.function_name = raw_array[0];
783    this.start_position = raw_array[1];
784    this.end_position = raw_array[2];
785    this.info = raw_array[3];
786    this.raw_array = raw_array;
787  }
788
789  // Changes positions (including all statements) in function.
790  function PatchPositions(old_info_node, diff_array, report_array) {
791    if (old_info_node.live_shared_function_infos) {
792      old_info_node.live_shared_function_infos.forEach(function (info) {
793          %LiveEditPatchFunctionPositions(info.raw_array,
794                                          diff_array);
795      });
796
797      report_array.push( { name: old_info_node.info.function_name } );
798    } else {
799      // TODO(LiveEdit): function is not compiled yet or is already collected.
800      report_array.push(
801          { name: old_info_node.info.function_name, info_not_found: true } );
802    }
803  }
804
805  // Adds a suffix to script name to mark that it is old version.
806  function CreateNameForOldScript(script) {
807    // TODO(635): try better than this; support several changes.
808    return script.name + " (old)";
809  }
810
811  // Compares a function scope heap structure, old and new version, whether it
812  // changed or not. Returns explanation if they differ.
813  function IsFunctionContextLocalsChanged(function_info1, function_info2) {
814    var scope_info1 = function_info1.scope_info;
815    var scope_info2 = function_info2.scope_info;
816
817    var scope_info1_text;
818    var scope_info2_text;
819
820    if (scope_info1) {
821      scope_info1_text = scope_info1.toString();
822    } else {
823      scope_info1_text = "";
824    }
825    if (scope_info2) {
826      scope_info2_text = scope_info2.toString();
827    } else {
828      scope_info2_text = "";
829    }
830
831    if (scope_info1_text != scope_info2_text) {
832      return "Variable map changed: [" + scope_info1_text +
833          "] => [" + scope_info2_text + "]";
834    }
835    // No differences. Return undefined.
836    return;
837  }
838
839  // Minifier forward declaration.
840  var FunctionPatchabilityStatus;
841
842  // For array of wrapped shared function infos checks that none of them
843  // have activations on stack (of any thread). Throws a Failure exception
844  // if this proves to be false.
845  function CheckStackActivations(old_shared_wrapper_list,
846                                 new_shared_list,
847                                 change_log) {
848    var old_shared_list = new GlobalArray();
849    for (var i = 0; i < old_shared_wrapper_list.length; i++) {
850      old_shared_list[i] = old_shared_wrapper_list[i].info;
851    }
852    var result = %LiveEditCheckAndDropActivations(
853                     old_shared_list, new_shared_list, true);
854    if (result[old_shared_wrapper_list.length]) {
855      // Extra array element may contain error message.
856      throw new Failure(result[old_shared_wrapper_list.length]);
857    }
858
859    var problems = new GlobalArray();
860    var dropped = new GlobalArray();
861    for (var i = 0; i < old_shared_list.length; i++) {
862      var shared = old_shared_wrapper_list[i];
863      if (result[i] == FunctionPatchabilityStatus.REPLACED_ON_ACTIVE_STACK) {
864        dropped.push({ name: shared.function_name } );
865      } else if (result[i] != FunctionPatchabilityStatus.AVAILABLE_FOR_PATCH) {
866        var description = {
867            name: shared.function_name,
868            start_pos: shared.start_position,
869            end_pos: shared.end_position,
870            replace_problem:
871                FunctionPatchabilityStatus.SymbolName(result[i])
872        };
873        problems.push(description);
874      }
875    }
876    if (dropped.length > 0) {
877      change_log.push({ dropped_from_stack: dropped });
878    }
879    if (problems.length > 0) {
880      change_log.push( { functions_on_stack: problems } );
881      throw new Failure("Blocked by functions on stack");
882    }
883
884    return dropped.length;
885  }
886
887  // A copy of the FunctionPatchabilityStatus enum from liveedit.h
888  var FunctionPatchabilityStatus = {
889      AVAILABLE_FOR_PATCH: 1,
890      BLOCKED_ON_ACTIVE_STACK: 2,
891      BLOCKED_ON_OTHER_STACK: 3,
892      BLOCKED_UNDER_NATIVE_CODE: 4,
893      REPLACED_ON_ACTIVE_STACK: 5,
894      BLOCKED_UNDER_GENERATOR: 6,
895      BLOCKED_ACTIVE_GENERATOR: 7,
896      BLOCKED_NO_NEW_TARGET_ON_RESTART: 8
897  };
898
899  FunctionPatchabilityStatus.SymbolName = function(code) {
900    var enumeration = FunctionPatchabilityStatus;
901    for (var name in enumeration) {
902      if (enumeration[name] == code) {
903        return name;
904      }
905    }
906  };
907
908
909  // A logical failure in liveedit process. This means that change_log
910  // is valid and consistent description of what happened.
911  function Failure(message) {
912    this.message = message;
913  }
914
915  Failure.prototype.toString = function() {
916    return "LiveEdit Failure: " + this.message;
917  };
918
919  function CopyErrorPositionToDetails(e, details) {
920    function createPositionStruct(script, position) {
921      if (position == -1) return;
922      var location = script.locationFromPosition(position, true);
923      if (location == null) return;
924      return {
925        line: location.line + 1,
926        column: location.column + 1,
927        position: position
928      };
929    }
930
931    if (!("scriptObject" in e) || !("startPosition" in e)) {
932      return;
933    }
934
935    var script = e.scriptObject;
936
937    var position_struct = {
938      start: createPositionStruct(script, e.startPosition),
939      end: createPositionStruct(script, e.endPosition)
940    };
941    details.position = position_struct;
942  }
943
944  // LiveEdit main entry point: changes a script text to a new string.
945  function SetScriptSource(script, new_source, preview_only, change_log) {
946    var old_source = script.source;
947    var diff = CompareStrings(old_source, new_source);
948    return ApplyPatchMultiChunk(script, diff, new_source, preview_only,
949        change_log);
950  }
951
952  function CompareStrings(s1, s2) {
953    return %LiveEditCompareStrings(s1, s2);
954  }
955
956  // Applies the change to the script.
957  // The change is always a substring (change_pos, change_pos + change_len)
958  // being replaced with a completely different string new_str.
959  // This API is a legacy and is obsolete.
960  //
961  // @param {Script} script that is being changed
962  // @param {Array} change_log a list that collects engineer-readable
963  //     description of what happened.
964  function ApplySingleChunkPatch(script, change_pos, change_len, new_str,
965      change_log) {
966    var old_source = script.source;
967
968    // Prepare new source string.
969    var new_source = old_source.substring(0, change_pos) +
970        new_str + old_source.substring(change_pos + change_len);
971
972    return ApplyPatchMultiChunk(script,
973        [ change_pos, change_pos + change_len, change_pos + new_str.length],
974        new_source, false, change_log);
975  }
976
977  // Creates JSON description for a change tree.
978  function DescribeChangeTree(old_code_tree) {
979
980    function ProcessOldNode(node) {
981      var child_infos = [];
982      for (var i = 0; i < node.children.length; i++) {
983        var child = node.children[i];
984        if (child.status != FunctionStatus.UNCHANGED) {
985          child_infos.push(ProcessOldNode(child));
986        }
987      }
988      var new_child_infos = [];
989      if (node.textually_unmatched_new_nodes) {
990        for (var i = 0; i < node.textually_unmatched_new_nodes.length; i++) {
991          var child = node.textually_unmatched_new_nodes[i];
992          new_child_infos.push(ProcessNewNode(child));
993        }
994      }
995      var res = {
996        name: node.info.function_name,
997        positions: DescribePositions(node),
998        status: node.status,
999        children: child_infos,
1000        new_children: new_child_infos
1001      };
1002      if (node.status_explanation) {
1003        res.status_explanation = node.status_explanation;
1004      }
1005      if (node.textual_corresponding_node) {
1006        res.new_positions = DescribePositions(node.textual_corresponding_node);
1007      }
1008      return res;
1009    }
1010
1011    function ProcessNewNode(node) {
1012      var child_infos = [];
1013      // Do not list ancestors.
1014      if (false) {
1015        for (var i = 0; i < node.children.length; i++) {
1016          child_infos.push(ProcessNewNode(node.children[i]));
1017        }
1018      }
1019      var res = {
1020        name: node.info.function_name,
1021        positions: DescribePositions(node),
1022        children: child_infos,
1023      };
1024      return res;
1025    }
1026
1027    function DescribePositions(node) {
1028      return {
1029        start_position: node.info.start_position,
1030        end_position: node.info.end_position
1031      };
1032    }
1033
1034    return ProcessOldNode(old_code_tree);
1035  }
1036
1037  // -------------------------------------------------------------------
1038  // Exports
1039
1040  var LiveEdit = {};
1041  LiveEdit.SetScriptSource = SetScriptSource;
1042  LiveEdit.ApplyPatchMultiChunk = ApplyPatchMultiChunk;
1043  LiveEdit.Failure = Failure;
1044
1045  LiveEdit.TestApi = {
1046    PosTranslator: PosTranslator,
1047    CompareStrings: CompareStrings,
1048    ApplySingleChunkPatch: ApplySingleChunkPatch
1049  };
1050
1051  global.Debug.LiveEdit = LiveEdit;
1052
1053})
1054