xref: /llvm-project/clang/utils/analyzer/exploded-graph-rewriter.py (revision 5fcf92e153806e8fb3f195104f3d057580236132)
1#!/usr/bin/env python
2#
3#===- exploded-graph-rewriter.py - ExplodedGraph dump tool -----*- python -*--#
4#
5# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6# See https://llvm.org/LICENSE.txt for license information.
7# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8#
9#===-----------------------------------------------------------------------===#
10
11
12from __future__ import print_function
13
14import argparse
15import collections
16import difflib
17import json
18import logging
19import re
20
21
22#===-----------------------------------------------------------------------===#
23# These data structures represent a deserialized ExplodedGraph.
24#===-----------------------------------------------------------------------===#
25
26
27# A helper function for finding the difference between two dictionaries.
28def diff_dicts(curr, prev):
29    removed = [k for k in prev if k not in curr or curr[k] != prev[k]]
30    added = [k for k in curr if k not in prev or curr[k] != prev[k]]
31    return (removed, added)
32
33
34# Represents any program state trait that is a dictionary of key-value pairs.
35class GenericMap(object):
36    def __init__(self, items):
37        self.generic_map = collections.OrderedDict(items)
38
39    def diff(self, prev):
40        return diff_dicts(self.generic_map, prev.generic_map)
41
42    def is_different(self, prev):
43        removed, added = self.diff(prev)
44        return len(removed) != 0 or len(added) != 0
45
46
47# A deserialized source location.
48class SourceLocation(object):
49    def __init__(self, json_loc):
50        super(SourceLocation, self).__init__()
51        self.line = json_loc['line']
52        self.col = json_loc['column']
53        self.filename = json_loc['filename'] \
54            if 'filename' in json_loc else '(main file)'
55
56
57# A deserialized program point.
58class ProgramPoint(object):
59    def __init__(self, json_pp):
60        super(ProgramPoint, self).__init__()
61        self.kind = json_pp['kind']
62        self.tag = json_pp['tag']
63        if self.kind == 'Edge':
64            self.src_id = json_pp['src_id']
65            self.dst_id = json_pp['dst_id']
66        elif self.kind == 'Statement':
67            self.stmt_kind = json_pp['stmt_kind']
68            self.stmt_point_kind = json_pp['stmt_point_kind']
69            self.pointer = json_pp['pointer']
70            self.pretty = json_pp['pretty']
71            self.loc = SourceLocation(json_pp['location']) \
72                if json_pp['location'] is not None else None
73        elif self.kind == 'BlockEntrance':
74            self.block_id = json_pp['block_id']
75
76
77# A single expression acting as a key in a deserialized Environment.
78class EnvironmentBindingKey(object):
79    def __init__(self, json_ek):
80        super(EnvironmentBindingKey, self).__init__()
81        # CXXCtorInitializer is not a Stmt!
82        self.stmt_id = json_ek['stmt_id'] if 'stmt_id' in json_ek \
83            else json_ek['init_id']
84        self.pretty = json_ek['pretty']
85        self.kind = json_ek['kind'] if 'kind' in json_ek else None
86
87    def _key(self):
88        return self.stmt_id
89
90    def __eq__(self, other):
91        return self._key() == other._key()
92
93    def __hash__(self):
94        return hash(self._key())
95
96
97# Deserialized description of a location context.
98class LocationContext(object):
99    def __init__(self, json_frame):
100        super(LocationContext, self).__init__()
101        self.lctx_id = json_frame['lctx_id']
102        self.caption = json_frame['location_context']
103        self.decl = json_frame['calling']
104        self.line = json_frame['call_line']
105
106    def _key(self):
107        return self.lctx_id
108
109    def __eq__(self, other):
110        return self._key() == other._key()
111
112    def __hash__(self):
113        return hash(self._key())
114
115
116# A group of deserialized Environment bindings that correspond to a specific
117# location context.
118class EnvironmentFrame(object):
119    def __init__(self, json_frame):
120        super(EnvironmentFrame, self).__init__()
121        self.location_context = LocationContext(json_frame)
122        self.bindings = collections.OrderedDict(
123            [(EnvironmentBindingKey(b),
124              b['value']) for b in json_frame['items']]
125            if json_frame['items'] is not None else [])
126
127    def diff_bindings(self, prev):
128        return diff_dicts(self.bindings, prev.bindings)
129
130    def is_different(self, prev):
131        removed, added = self.diff_bindings(prev)
132        return len(removed) != 0 or len(added) != 0
133
134
135# A deserialized Environment. This class can also hold other entities that
136# are similar to Environment, such as Objects Under Construction.
137class GenericEnvironment(object):
138    def __init__(self, json_e):
139        super(GenericEnvironment, self).__init__()
140        self.frames = [EnvironmentFrame(f) for f in json_e]
141
142    def diff_frames(self, prev):
143        # TODO: It's difficult to display a good diff when frame numbers shift.
144        if len(self.frames) != len(prev.frames):
145            return None
146
147        updated = []
148        for i in range(len(self.frames)):
149            f = self.frames[i]
150            prev_f = prev.frames[i]
151            if f.location_context == prev_f.location_context:
152                if f.is_different(prev_f):
153                    updated.append(i)
154            else:
155                # We have the whole frame replaced with another frame.
156                # TODO: Produce a nice diff.
157                return None
158
159        # TODO: Add support for added/removed.
160        return updated
161
162    def is_different(self, prev):
163        updated = self.diff_frames(prev)
164        return updated is None or len(updated) > 0
165
166
167# A single binding key in a deserialized RegionStore cluster.
168class StoreBindingKey(object):
169    def __init__(self, json_sk):
170        super(StoreBindingKey, self).__init__()
171        self.kind = json_sk['kind']
172        self.offset = json_sk['offset']
173
174    def _key(self):
175        return (self.kind, self.offset)
176
177    def __eq__(self, other):
178        return self._key() == other._key()
179
180    def __hash__(self):
181        return hash(self._key())
182
183
184# A single cluster of the deserialized RegionStore.
185class StoreCluster(object):
186    def __init__(self, json_sc):
187        super(StoreCluster, self).__init__()
188        self.base_region = json_sc['cluster']
189        self.bindings = collections.OrderedDict(
190            [(StoreBindingKey(b), b['value']) for b in json_sc['items']])
191
192    def diff_bindings(self, prev):
193        return diff_dicts(self.bindings, prev.bindings)
194
195    def is_different(self, prev):
196        removed, added = self.diff_bindings(prev)
197        return len(removed) != 0 or len(added) != 0
198
199
200# A deserialized RegionStore.
201class Store(object):
202    def __init__(self, json_s):
203        super(Store, self).__init__()
204        self.ptr = json_s['pointer']
205        self.clusters = collections.OrderedDict(
206            [(c['pointer'], StoreCluster(c)) for c in json_s['items']])
207
208    def diff_clusters(self, prev):
209        removed = [k for k in prev.clusters if k not in self.clusters]
210        added = [k for k in self.clusters if k not in prev.clusters]
211        updated = [k for k in prev.clusters if k in self.clusters
212                   and prev.clusters[k].is_different(self.clusters[k])]
213        return (removed, added, updated)
214
215    def is_different(self, prev):
216        removed, added, updated = self.diff_clusters(prev)
217        return len(removed) != 0 or len(added) != 0 or len(updated) != 0
218
219
220# Deserialized messages from a single checker in a single program state.
221# Basically a list of raw strings.
222class CheckerLines(object):
223    def __init__(self, json_lines):
224        super(CheckerLines, self).__init__()
225        self.lines = json_lines
226
227    def diff_lines(self, prev):
228        lines = difflib.ndiff(prev.lines, self.lines)
229        return [l.strip() for l in lines
230                if l.startswith('+') or l.startswith('-')]
231
232    def is_different(self, prev):
233        return len(self.diff_lines(prev)) > 0
234
235
236# Deserialized messages of all checkers, separated by checker.
237class CheckerMessages(object):
238    def __init__(self, json_m):
239        super(CheckerMessages, self).__init__()
240        self.items = collections.OrderedDict(
241            [(m['checker'], CheckerLines(m['messages'])) for m in json_m])
242
243    def diff_messages(self, prev):
244        removed = [k for k in prev.items if k not in self.items]
245        added = [k for k in self.items if k not in prev.items]
246        updated = [k for k in prev.items if k in self.items
247                   and prev.items[k].is_different(self.items[k])]
248        return (removed, added, updated)
249
250    def is_different(self, prev):
251        removed, added, updated = self.diff_messages(prev)
252        return len(removed) != 0 or len(added) != 0 or len(updated) != 0
253
254
255# A deserialized program state.
256class ProgramState(object):
257    def __init__(self, state_id, json_ps):
258        super(ProgramState, self).__init__()
259        logging.debug('Adding ProgramState ' + str(state_id))
260
261        self.state_id = state_id
262
263        self.store = Store(json_ps['store']) \
264            if json_ps['store'] is not None else None
265
266        self.environment = \
267            GenericEnvironment(json_ps['environment']['items']) \
268            if json_ps['environment'] is not None else None
269
270        self.constraints = GenericMap([
271            (c['symbol'], c['range']) for c in json_ps['constraints']
272        ]) if json_ps['constraints'] is not None else None
273
274        self.dynamic_types = GenericMap([
275                (t['region'], '%s%s' % (t['dyn_type'],
276                                        ' (or a sub-class)'
277                                        if t['sub_classable'] else ''))
278                for t in json_ps['dynamic_types']]) \
279            if json_ps['dynamic_types'] is not None else None
280
281        self.constructing_objects = \
282            GenericEnvironment(json_ps['constructing_objects']) \
283            if json_ps['constructing_objects'] is not None else None
284
285        self.checker_messages = CheckerMessages(json_ps['checker_messages']) \
286            if json_ps['checker_messages'] is not None else None
287
288
289# A deserialized exploded graph node. Has a default constructor because it
290# may be referenced as part of an edge before its contents are deserialized,
291# and in this moment we already need a room for predecessors and successors.
292class ExplodedNode(object):
293    def __init__(self):
294        super(ExplodedNode, self).__init__()
295        self.predecessors = []
296        self.successors = []
297
298    def construct(self, node_id, json_node):
299        logging.debug('Adding ' + node_id)
300        self.node_id = json_node['node_id']
301        self.ptr = json_node['pointer']
302        self.points = [ProgramPoint(p) for p in json_node['program_points']]
303        self.state = ProgramState(json_node['state_id'],
304                                  json_node['program_state']) \
305            if json_node['program_state'] is not None else None
306
307        assert self.node_name() == node_id
308
309    def node_name(self):
310        return 'Node' + self.ptr
311
312
313# A deserialized ExplodedGraph. Constructed by consuming a .dot file
314# line-by-line.
315class ExplodedGraph(object):
316    # Parse .dot files with regular expressions.
317    node_re = re.compile(
318        '^(Node0x[0-9a-f]*) \\[shape=record,.*label="{(.*)\\\\l}"\\];$')
319    edge_re = re.compile(
320        '^(Node0x[0-9a-f]*) -> (Node0x[0-9a-f]*);$')
321
322    def __init__(self):
323        super(ExplodedGraph, self).__init__()
324        self.nodes = collections.defaultdict(ExplodedNode)
325        self.root_id = None
326        self.incomplete_line = ''
327
328    def add_raw_line(self, raw_line):
329        if raw_line.startswith('//'):
330            return
331
332        # Allow line breaks by waiting for ';'. This is not valid in
333        # a .dot file, but it is useful for writing tests.
334        if len(raw_line) > 0 and raw_line[-1] != ';':
335            self.incomplete_line += raw_line
336            return
337        raw_line = self.incomplete_line + raw_line
338        self.incomplete_line = ''
339
340        # Apply regexps one by one to see if it's a node or an edge
341        # and extract contents if necessary.
342        logging.debug('Line: ' + raw_line)
343        result = self.edge_re.match(raw_line)
344        if result is not None:
345            logging.debug('Classified as edge line.')
346            pred = result.group(1)
347            succ = result.group(2)
348            self.nodes[pred].successors.append(succ)
349            self.nodes[succ].predecessors.append(pred)
350            return
351        result = self.node_re.match(raw_line)
352        if result is not None:
353            logging.debug('Classified as node line.')
354            node_id = result.group(1)
355            if len(self.nodes) == 0:
356                self.root_id = node_id
357            # Note: when writing tests you don't need to escape everything,
358            # even though in a valid dot file everything is escaped.
359            node_label = result.group(2).replace('\\l', '') \
360                                        .replace(' ', '') \
361                                        .replace('\\"', '"') \
362                                        .replace('\\{', '{') \
363                                        .replace('\\}', '}') \
364                                        .replace('\\\\', '\\') \
365                                        .replace('\\|', '|') \
366                                        .replace('\\<', '\\\\<') \
367                                        .replace('\\>', '\\\\>') \
368                                        .rstrip(',')
369            logging.debug(node_label)
370            json_node = json.loads(node_label)
371            self.nodes[node_id].construct(node_id, json_node)
372            return
373        logging.debug('Skipping.')
374
375
376#===-----------------------------------------------------------------------===#
377# Visitors traverse a deserialized ExplodedGraph and do different things
378# with every node and edge.
379#===-----------------------------------------------------------------------===#
380
381
382# A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based
383# syntax highlighing.
384class DotDumpVisitor(object):
385    def __init__(self, do_diffs, dark_mode):
386        super(DotDumpVisitor, self).__init__()
387        self._do_diffs = do_diffs
388        self._dark_mode = dark_mode
389
390    @staticmethod
391    def _dump_raw(s):
392        print(s, end='')
393
394    @staticmethod
395    def _dump(s):
396        print(s.replace('&', '&amp;')
397               .replace('{', '\\{')
398               .replace('}', '\\}')
399               .replace('\\<', '&lt;')
400               .replace('\\>', '&gt;')
401               .replace('\\l', '<br />')
402               .replace('|', '\\|'), end='')
403
404    @staticmethod
405    def _diff_plus_minus(is_added):
406        if is_added is None:
407            return ''
408        if is_added:
409            return '<font color="forestgreen">+</font>'
410        return '<font color="red">-</font>'
411
412    @staticmethod
413    def _short_pretty(s):
414        if s is None:
415            return None
416        if len(s) < 20:
417            return s
418        left = s.find('{')
419        right = s.rfind('}')
420        if left == -1 or right == -1 or left >= right:
421            return s
422        candidate = s[0:left + 1] + ' ... ' + s[right:]
423        if len(candidate) >= len(s):
424            return s
425        return candidate
426
427    def visit_begin_graph(self, graph):
428        self._graph = graph
429        self._dump_raw('digraph "ExplodedGraph" {\n')
430        if self._dark_mode:
431            self._dump_raw('bgcolor="gray10";\n')
432        self._dump_raw('label="";\n')
433
434    def visit_program_point(self, p):
435        if p.kind in ['Edge', 'BlockEntrance', 'BlockExit']:
436            color = 'gold3'
437        elif p.kind in ['PreStmtPurgeDeadSymbols',
438                        'PostStmtPurgeDeadSymbols']:
439            color = 'red'
440        elif p.kind in ['CallEnter', 'CallExitBegin', 'CallExitEnd']:
441            color = 'dodgerblue' if self._dark_mode else 'blue'
442        elif p.kind in ['Statement']:
443            color = 'cyan4'
444        else:
445            color = 'forestgreen'
446
447        if p.kind == 'Statement':
448            # This avoids pretty-printing huge statements such as CompoundStmt.
449            # Such statements show up only at [Pre|Post]StmtPurgeDeadSymbols
450            skip_pretty = 'PurgeDeadSymbols' in p.stmt_point_kind
451            stmt_color = 'cyan3'
452            if p.loc is not None:
453                self._dump('<tr><td align="left" width="0">'
454                           '%s:<b>%s</b>:<b>%s</b>:</td>'
455                           '<td align="left" width="0"><font color="%s">'
456                           '%s</font></td>'
457                           '<td align="left"><font color="%s">%s</font></td>'
458                           '<td>%s</td></tr>'
459                           % (p.loc.filename, p.loc.line,
460                              p.loc.col, color, p.stmt_kind,
461                              stmt_color, p.stmt_point_kind,
462                              self._short_pretty(p.pretty)
463                              if not skip_pretty else ''))
464            else:
465                self._dump('<tr><td align="left" width="0">'
466                           '<i>Invalid Source Location</i>:</td>'
467                           '<td align="left" width="0">'
468                           '<font color="%s">%s</font></td>'
469                           '<td align="left"><font color="%s">%s</font></td>'
470                           '<td>%s</td></tr>'
471                           % (color, p.stmt_kind,
472                              stmt_color, p.stmt_point_kind,
473                              self._short_pretty(p.pretty)
474                              if not skip_pretty else ''))
475        elif p.kind == 'Edge':
476            self._dump('<tr><td width="0"></td>'
477                       '<td align="left" width="0">'
478                       '<font color="%s">%s</font></td><td align="left">'
479                       '[B%d] -\\> [B%d]</td></tr>'
480                       % (color, 'BlockEdge', p.src_id, p.dst_id))
481        elif p.kind == 'BlockEntrance':
482            self._dump('<tr><td width="0"></td>'
483                       '<td align="left" width="0">'
484                       '<font color="%s">%s</font></td>'
485                       '<td align="left">[B%d]</td></tr>'
486                       % (color, p.kind, p.block_id))
487        else:
488            # TODO: Print more stuff for other kinds of points.
489            self._dump('<tr><td width="0"></td>'
490                       '<td align="left" width="0" colspan="2">'
491                       '<font color="%s">%s</font></td></tr>'
492                       % (color, p.kind))
493
494        if p.tag is not None:
495            self._dump('<tr><td width="0"></td>'
496                       '<td colspan="3" align="left">'
497                       '<b>Tag: </b> <font color="crimson">'
498                       '%s</font></td></tr>' % p.tag)
499
500    def visit_environment(self, e, prev_e=None):
501        self._dump('<table border="0">')
502
503        def dump_location_context(lc, is_added=None):
504            self._dump('<tr><td>%s</td>'
505                       '<td align="left"><b>%s</b></td>'
506                       '<td align="left" colspan="2">'
507                       '<font color="gray60">%s </font>'
508                       '%s</td></tr>'
509                       % (self._diff_plus_minus(is_added),
510                          lc.caption, lc.decl,
511                          ('(line %s)' % lc.line) if lc.line is not None
512                          else ''))
513
514        def dump_binding(f, b, is_added=None):
515            self._dump('<tr><td>%s</td>'
516                       '<td align="left"><i>S%s</i></td>'
517                       '%s'
518                       '<td align="left">%s</td>'
519                       '<td align="left">%s</td></tr>'
520                       % (self._diff_plus_minus(is_added),
521                          b.stmt_id,
522                          '<td align="left"><font color="%s"><i>'
523                          '%s</i></font></td>' % (
524                              'lavender' if self._dark_mode else 'darkgreen',
525                              ('(%s)' % b.kind) if b.kind is not None else ' '
526                          ),
527                          self._short_pretty(b.pretty), f.bindings[b]))
528
529        frames_updated = e.diff_frames(prev_e) if prev_e is not None else None
530        if frames_updated:
531            for i in frames_updated:
532                f = e.frames[i]
533                prev_f = prev_e.frames[i]
534                dump_location_context(f.location_context)
535                bindings_removed, bindings_added = f.diff_bindings(prev_f)
536                for b in bindings_removed:
537                    dump_binding(prev_f, b, False)
538                for b in bindings_added:
539                    dump_binding(f, b, True)
540        else:
541            for f in e.frames:
542                dump_location_context(f.location_context)
543                for b in f.bindings:
544                    dump_binding(f, b)
545
546        self._dump('</table>')
547
548    def visit_environment_in_state(self, selector, title, s, prev_s=None):
549        e = getattr(s, selector)
550        prev_e = getattr(prev_s, selector) if prev_s is not None else None
551        if e is None and prev_e is None:
552            return
553
554        self._dump('<hr /><tr><td align="left"><b>%s: </b>' % title)
555        if e is None:
556            self._dump('<i> Nothing!</i>')
557        else:
558            if prev_e is not None:
559                if e.is_different(prev_e):
560                    self._dump('</td></tr><tr><td align="left">')
561                    self.visit_environment(e, prev_e)
562                else:
563                    self._dump('<i> No changes!</i>')
564            else:
565                self._dump('</td></tr><tr><td align="left">')
566                self.visit_environment(e)
567
568        self._dump('</td></tr>')
569
570    def visit_store(self, s, prev_s=None):
571        self._dump('<table border="0">')
572
573        def dump_binding(s, c, b, is_added=None):
574            self._dump('<tr><td>%s</td>'
575                       '<td align="left">%s</td>'
576                       '<td align="left">%s</td>'
577                       '<td align="left">%s</td>'
578                       '<td align="left">%s</td></tr>'
579                       % (self._diff_plus_minus(is_added),
580                          s.clusters[c].base_region, b.offset,
581                          '(<i>Default</i>)' if b.kind == 'Default'
582                          else '',
583                          s.clusters[c].bindings[b]))
584
585        if prev_s is not None:
586            clusters_removed, clusters_added, clusters_updated = \
587                s.diff_clusters(prev_s)
588            for c in clusters_removed:
589                for b in prev_s.clusters[c].bindings:
590                    dump_binding(prev_s, c, b, False)
591            for c in clusters_updated:
592                bindings_removed, bindings_added = \
593                    s.clusters[c].diff_bindings(prev_s.clusters[c])
594                for b in bindings_removed:
595                    dump_binding(prev_s, c, b, False)
596                for b in bindings_added:
597                    dump_binding(s, c, b, True)
598            for c in clusters_added:
599                for b in s.clusters[c].bindings:
600                    dump_binding(s, c, b, True)
601        else:
602            for c in s.clusters:
603                for b in s.clusters[c].bindings:
604                    dump_binding(s, c, b)
605
606        self._dump('</table>')
607
608    def visit_store_in_state(self, s, prev_s=None):
609        st = s.store
610        prev_st = prev_s.store if prev_s is not None else None
611        if st is None and prev_st is None:
612            return
613
614        self._dump('<hr /><tr><td align="left"><b>Store: </b>')
615        if st is None:
616            self._dump('<i> Nothing!</i>')
617        else:
618            if prev_st is not None:
619                if s.store.is_different(prev_st):
620                    self._dump('</td></tr><tr><td align="left">')
621                    self.visit_store(st, prev_st)
622                else:
623                    self._dump('<i> No changes!</i>')
624            else:
625                self._dump('</td></tr><tr><td align="left">')
626                self.visit_store(st)
627        self._dump('</td></tr>')
628
629    def visit_generic_map(self, m, prev_m=None):
630        self._dump('<table border="0">')
631
632        def dump_pair(m, k, is_added=None):
633            self._dump('<tr><td>%s</td>'
634                       '<td align="left">%s</td>'
635                       '<td align="left">%s</td></tr>'
636                       % (self._diff_plus_minus(is_added),
637                          k, m.generic_map[k]))
638
639        if prev_m is not None:
640            removed, added = m.diff(prev_m)
641            for k in removed:
642                dump_pair(prev_m, k, False)
643            for k in added:
644                dump_pair(m, k, True)
645        else:
646            for k in m.generic_map:
647                dump_pair(m, k, None)
648
649        self._dump('</table>')
650
651    def visit_generic_map_in_state(self, selector, title, s, prev_s=None):
652        m = getattr(s, selector)
653        prev_m = getattr(prev_s, selector) if prev_s is not None else None
654        if m is None and prev_m is None:
655            return
656
657        self._dump('<hr />')
658        self._dump('<tr><td align="left">'
659                   '<b>%s: </b>' % title)
660        if m is None:
661            self._dump('<i> Nothing!</i>')
662        else:
663            if prev_m is not None:
664                if m.is_different(prev_m):
665                    self._dump('</td></tr><tr><td align="left">')
666                    self.visit_generic_map(m, prev_m)
667                else:
668                    self._dump('<i> No changes!</i>')
669            else:
670                self._dump('</td></tr><tr><td align="left">')
671                self.visit_generic_map(m)
672
673        self._dump('</td></tr>')
674
675    def visit_checker_messages(self, m, prev_m=None):
676        self._dump('<table border="0">')
677
678        def dump_line(l, is_added=None):
679            self._dump('<tr><td>%s</td>'
680                       '<td align="left">%s</td></tr>'
681                       % (self._diff_plus_minus(is_added), l))
682
683        def dump_chk(chk, is_added=None):
684            dump_line('<i>%s</i>:' % chk, is_added)
685
686        if prev_m is not None:
687            removed, added, updated = m.diff_messages(prev_m)
688            for chk in removed:
689                dump_chk(chk, False)
690                for l in prev_m.items[chk].lines:
691                    dump_line(l, False)
692            for chk in updated:
693                dump_chk(chk)
694                for l in m.items[chk].diff_lines(prev_m.items[chk]):
695                    dump_line(l[1:], l.startswith('+'))
696            for chk in added:
697                dump_chk(chk, True)
698                for l in m.items[chk].lines:
699                    dump_line(l, True)
700        else:
701            for chk in m.items:
702                dump_chk(chk)
703                for l in m.items[chk].lines:
704                    dump_line(l)
705
706        self._dump('</table>')
707
708    def visit_checker_messages_in_state(self, s, prev_s=None):
709        m = s.checker_messages
710        prev_m = prev_s.checker_messages if prev_s is not None else None
711        if m is None and prev_m is None:
712            return
713
714        self._dump('<hr />')
715        self._dump('<tr><td align="left">'
716                   '<b>Checker State: </b>')
717        if m is None:
718            self._dump('<i> Nothing!</i>')
719        else:
720            if prev_m is not None:
721                if m.is_different(prev_m):
722                    self._dump('</td></tr><tr><td align="left">')
723                    self.visit_checker_messages(m, prev_m)
724                else:
725                    self._dump('<i> No changes!</i>')
726            else:
727                self._dump('</td></tr><tr><td align="left">')
728                self.visit_checker_messages(m)
729
730        self._dump('</td></tr>')
731
732    def visit_state(self, s, prev_s):
733        self.visit_store_in_state(s, prev_s)
734        self.visit_environment_in_state('environment', 'Environment',
735                                        s, prev_s)
736        self.visit_generic_map_in_state('constraints', 'Ranges',
737                                        s, prev_s)
738        self.visit_generic_map_in_state('dynamic_types', 'Dynamic Types',
739                                        s, prev_s)
740        self.visit_environment_in_state('constructing_objects',
741                                        'Objects Under Construction',
742                                        s, prev_s)
743        self.visit_checker_messages_in_state(s, prev_s)
744
745    def visit_node(self, node):
746        self._dump('%s [shape=record,'
747                   % (node.node_name()))
748        if self._dark_mode:
749            self._dump('color="white",fontcolor="gray80",')
750        self._dump('label=<<table border="0">')
751
752        self._dump('<tr><td bgcolor="%s"><b>Node %d (%s) - '
753                   'State %s</b></td></tr>'
754                   % ("gray20" if self._dark_mode else "gray",
755                      node.node_id, node.ptr, node.state.state_id
756                      if node.state is not None else 'Unspecified'))
757        self._dump('<tr><td align="left" width="0">')
758        if len(node.points) > 1:
759            self._dump('<b>Program points:</b></td></tr>')
760        else:
761            self._dump('<b>Program point:</b></td></tr>')
762        self._dump('<tr><td align="left" width="0">'
763                   '<table border="0" align="left" width="0">')
764        for p in node.points:
765            self.visit_program_point(p)
766        self._dump('</table></td></tr>')
767
768        if node.state is not None:
769            prev_s = None
770            # Do diffs only when we have a unique predecessor.
771            # Don't do diffs on the leaf nodes because they're
772            # the important ones.
773            if self._do_diffs and len(node.predecessors) == 1 \
774               and len(node.successors) > 0:
775                prev_s = self._graph.nodes[node.predecessors[0]].state
776            self.visit_state(node.state, prev_s)
777        self._dump_raw('</table>>];\n')
778
779    def visit_edge(self, pred, succ):
780        self._dump_raw('%s -> %s%s;\n' % (
781            pred.node_name(), succ.node_name(),
782            ' [color="white"]' if self._dark_mode else ''
783        ))
784
785    def visit_end_of_graph(self):
786        self._dump_raw('}\n')
787
788
789#===-----------------------------------------------------------------------===#
790# Explorers know how to traverse the ExplodedGraph in a certain order.
791# They would invoke a Visitor on every node or edge they encounter.
792#===-----------------------------------------------------------------------===#
793
794
795# A class that encapsulates traversal of the ExplodedGraph. Different explorer
796# kinds could potentially traverse specific sub-graphs.
797class BasicExplorer(object):
798    def __init__(self):
799        super(BasicExplorer, self).__init__()
800
801    def explore(self, graph, visitor):
802        visitor.visit_begin_graph(graph)
803        for node in sorted(graph.nodes):
804            logging.debug('Visiting ' + node)
805            visitor.visit_node(graph.nodes[node])
806            for succ in sorted(graph.nodes[node].successors):
807                logging.debug('Visiting edge: %s -> %s ' % (node, succ))
808                visitor.visit_edge(graph.nodes[node], graph.nodes[succ])
809        visitor.visit_end_of_graph()
810
811
812#===-----------------------------------------------------------------------===#
813# The entry point to the script.
814#===-----------------------------------------------------------------------===#
815
816
817def main():
818    parser = argparse.ArgumentParser()
819    parser.add_argument('filename', type=str)
820    parser.add_argument('-v', '--verbose', action='store_const',
821                        dest='loglevel', const=logging.DEBUG,
822                        default=logging.WARNING,
823                        help='enable info prints')
824    parser.add_argument('-d', '--diff', action='store_const', dest='diff',
825                        const=True, default=False,
826                        help='display differences between states')
827    parser.add_argument('--dark', action='store_const', dest='dark',
828                        const=True, default=False,
829                        help='dark mode')
830    args = parser.parse_args()
831    logging.basicConfig(level=args.loglevel)
832
833    graph = ExplodedGraph()
834    with open(args.filename) as fd:
835        for raw_line in fd:
836            raw_line = raw_line.strip()
837            graph.add_raw_line(raw_line)
838
839    explorer = BasicExplorer()
840    visitor = DotDumpVisitor(args.diff, args.dark)
841    explorer.explore(graph, visitor)
842
843
844if __name__ == '__main__':
845    main()
846