File: Synopsis/Processors/Comments/Translator.py
 1#
 2# Copyright (C) 2006 Stefan Seefeld
 3# All rights reserved.
 4# Licensed to the public under the terms of the GNU LGPL (>= 2),
 5# see the file COPYING for details.
 6#
 7
 8from Synopsis import ASG
 9from Synopsis.DocString import DocString
10from Synopsis.Processor import Processor, Parameter
11from Filter import *
12
13class Translator(Processor, ASG.Visitor):
14    """A Translator translates comments into documentation."""
15
16    filter = Parameter(SSFilter(), 'A comment filter to apply.')
17    processor = Parameter(None, 'A comment processor to run.')
18    markup = Parameter('', 'The markup type for this declaration.')
19    concatenate = Parameter(False, 'Whether or not to concatenate adjacent comments.')
20    primary_only = Parameter(True, 'Whether or not to preserve secondary comments.')
21
22    def process(self, ir, **kwds):
23
24        self.set_parameters(kwds)
25        self.ir = self.merge_input(ir)
26        if self.filter:
27            self.ir = self.filter.process(self.ir)
28        if self.processor:
29            self.ir = self.processor.process(self.ir)
30
31        for sf in self.ir.files.values():
32            self.visit_sourcefile(sf)
33
34        for decl in self.ir.asg.declarations:
35            decl.accept(self)
36
37        return self.output_and_return_ir()
38
39
40    def visit_declaration(self, decl):
41        """Map comments to a doc string."""
42
43        comments = decl.annotations.get('comments')
44        if comments:
45            text = None
46            if self.primary_only:
47                text = comments[-1]
48            elif self.combine:
49                text = ''.join([c for c in comments if c])
50            else:
51                comments = comments[:]
52                comments.reverse()
53                for c in comments:
54                    if c is not None:
55                        text = c
56                        break
57            doc = DocString(text or '', self.markup)
58            decl.annotations['doc'] = doc
59
60    def visit_sourcefile(self, sf):
61        """Map comments to a doc string."""
62
63        comments = sf.annotations.get('comments')
64        if comments:
65            text = None
66            if self.primary_only:
67                # A 'primary' comment for a file is the first one,
68                # not the last.
69                text = comments[0]
70            elif self.combine:
71                text = ''.join([c for c in comments if c])
72            else:
73                comments = comments[:]
74                for c in comments:
75                    if c is not None:
76                        text = c
77                        break
78            doc = DocString(text or '', self.markup)
79            sf.annotations['doc'] = doc
80