translator.py 84.6 KB
Newer Older
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1 2 3 4 5 6
"""Script to generate reports on translator classes from Doxygen sources.

  The main purpose of the script is to extract the information from sources
  related to internationalization (the translator classes). It uses the
  information to generate documentation (language.doc,
  translator_report.txt) from templates (language.tpl, maintainers.txt).
7

Dimitri van Heesch's avatar
Dimitri van Heesch committed
8 9 10 11 12
  Simply run the script without parameters to get the reports and
  documentation for all supported languages. If you want to generate the
  translator report only for some languages, pass their codes as arguments
  to the script. In that case, the language.doc will not be generated.
  Example:
13

Dimitri van Heesch's avatar
Dimitri van Heesch committed
14
    python translator.py en nl cz
15

Dimitri van Heesch's avatar
Dimitri van Heesch committed
16
  Originally, the script was written in Perl and was known as translator.pl.
17
  The last Perl version was dated 2002/05/21 (plus some later corrections)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
18

19
  $Id$
20

21
                                         Petr Prikryl (prikrylp@skil.cz)
22

23 24
  History:
  --------
25
  2002/05/21 - This was the last Perl version.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
26 27 28 29 30 31 32 33 34
  2003/05/16 - List of language marks can be passed as arguments.
  2004/01/24 - Total reimplementation started: classes TrManager, and Transl.
  2004/02/05 - First version that produces translator report. No language.doc yet.
  2004/02/10 - First fully functional version that generates both the translator
               report and the documentation. It is a bit slower than the
               Perl version, but is much less tricky and much more flexible.
               It also solves some problems that were not solved by the Perl
               version. The translator report content should be more useful
               for developers.
35 36
  2004/02/11 - Some tuning-up to provide more useful information.
  2004/04/16 - Added new tokens to the tokenizer (to remove some warnings).
37 38
  2004/05/25 - Added from __future__ import generators not to force Python 2.3.
  2004/06/03 - Removed dependency on textwrap module.
39
  2004/07/07 - Fixed the bug in the fill() function.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
40 41 42 43
  2004/07/21 - Better e-mail mangling for HTML part of language.doc.
             - Plural not used for reporting a single missing method.
             - Removal of not used translator adapters is suggested only
               when the report is not restricted to selected languages
44 45
               explicitly via script arguments.
  2004/07/26 - Better reporting of not-needed adapters.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
46
  2004/10/04 - Reporting of not called translator methods added.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
47
  2004/10/05 - Modified to check only doxygen/src sources for the previous report.
48
  2005/02/28 - Slight modification to generate "mailto.txt" auxiliary file.
49
  2005/08/15 - Doxygen's root directory determined primarily from DOXYGEN
Dimitri van Heesch's avatar
Dimitri van Heesch committed
50
               environment variable. When not found, then relatively to the script.
51 52 53 54
  2007/03/20 - The "translate me!" searched in comments and reported if found.
  2008/06/09 - Warning when the MAX_DOT_GRAPH_HEIGHT is still part of trLegendDocs().
  2009/05/09 - Changed HTML output to fit it with XHTML DTD
  2009/09/02 - Added percentage info to the report (implemented / to be implemented).
55 56 57 58
  2010/02/09 - Added checking/suggestion 'Reimplementation using UTF-8 suggested.
  2010/03/03 - Added [unreachable] prefix used in maintainers.txt.
  2010/05/28 - BOM skipped; minor code cleaning.
  2010/05/31 - e-mail mangled already in maintainers.txt
59 60 61
  2010/08/20 - maintainers.txt to UTF-8, related processin of unicode strings
             - [any mark] introduced instead of [unreachable] only
             - marks hihglighted in HTML
Dimitri van Heesch's avatar
Dimitri van Heesch committed
62 63 64
  2010/08/30 - Highlighting in what will be the table in langhowto.html modified.
  2010/09/27 - The underscore in \latexonly part of the generated language.doc
               was prefixed by backslash (was LaTeX related error).
65 66
  2013/02/19 - Better diagnostics when translator_xx.h is too crippled.
  """
67

68
from __future__ import generators
69 70 71 72
import codecs
import os
import re
import sys
73 74 75 76


def fill(s):
    """Returns string formated to the wrapped paragraph multiline string.
77

78
    Replaces whitespaces by one space and then uses he textwrap.fill()."""
79

80
    # Replace all whitespace by spaces, remove whitespaces that are not
81
    # necessary, strip the left and right whitespaces, and break the string
82
    # to list of words.
83
    rexWS = re.compile(r'\s+')
84
    lst = rexWS.sub(' ', s).strip().split()
85 86

    # If the list is not empty, put the words together and form the lines
87 88 89 90 91 92 93 94 95 96
    # of maximum 70 characters. Build the list of lines.
    lines = []
    if lst:
        line = lst.pop(0)   # no separation space in front of the first word
        for word in lst:
            if len(line) + len(word) < 70:
                line += ' ' + word
            else:
                lines.append(line)  # another full line formed
                line = word         # next line started
97
        lines.append(line)          # the last line
98 99
    return '\n'.join(lines)

100

101 102
# The following function dedent() is the verbatim copy from the textwrap.py
# module. The textwrap.py was introduced in Python 2.3. To make this script
103
# working also in older Python versions, I have decided to copy it.
104 105 106 107 108 109
# Notice that the textwrap.py is copyrighted:
#
# Copyright (C) 1999-2001 Gregory P. Ward.
# Copyright (C) 2002, 2003 Python Software Foundation.
# Written by Greg Ward <gward@python.net>
#
110
# The explicit permission to use the code here was sent by Guido van Rossum
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
# (4th June, 2004).
#
def dedent(text):
    """dedent(text : string) -> string

    Remove any whitespace than can be uniformly removed from the left
    of every line in `text`.

    This can be used e.g. to make triple-quoted strings line up with
    the left edge of screen/whatever, while still presenting it in the
    source code in indented form.

    For example:

        def test():
            # end first line with \ to avoid the empty line!
            s = '''\
            hello
              world
            '''
            print repr(s)          # prints '    hello\n      world\n    '
            print repr(dedent(s))  # prints 'hello\n  world\n'
    """
    lines = text.expandtabs().split('\n')
    margin = None
    for line in lines:
        content = line.lstrip()
        if not content:
            continue
        indent = len(line) - len(content)
        if margin is None:
            margin = indent
        else:
            margin = min(margin, indent)

    if margin is not None and margin > 0:
        for i in range(len(lines)):
            lines[i] = lines[i][margin:]

    return '\n'.join(lines)
151

152 153 154

class Transl:
    """One instance is build for each translator.
155

156 157 158 159
    The abbreviation of the source file--part after 'translator_'--is used as
    the identification of the object. The empty string is used for the
    abstract Translator class from translator.h. The other information is
    extracted from inside the source file."""
160

161 162
    def __init__(self, fname, manager):
        """Bind to the manager and initialize."""
163

164 165 166
        # Store the filename and the reference to the manager object.
        self.fname = fname
        self.manager = manager
167

168 169 170 171 172
        # The instance is responsible for loading the source file, so it checks
        # for its existence and quits if something goes wrong.
        if not os.path.isfile(fname):
            sys.stderr.write("\a\nFile '%s' not found!\n" % fname)
            sys.exit(1)
173

174 175 176
        # Initialize the other collected information.
        self.classId = None
        self.baseClassId = None
177 178 179 180 181 182 183 184
        self.readableStatus = None   # 'up-to-date', '1.2.3', '1.3', etc.
        self.status = None           # '', '1.2.03', '1.3.00', etc.
        self.lang = None             # like 'Brasilian'
        self.langReadable = None     # like 'Brasilian Portuguese'
        self.note = None             # like 'should be cleaned up'
        self.prototypeDic = {}       # uniPrototype -> prototype
        self.translateMeText = 'translate me!'
        self.translateMeFlag = False # comments with "translate me!" found
185
        self.txtMAX_DOT_GRAPH_HEIGHT_flag = False # found in string in trLegendDocs()
186 187
        self.obsoleteMethods = None  # list of prototypes to be removed
        self.missingMethods = None   # list of prototypes to be implemented
188
        self.implementedMethods = None  # list of implemented required methods
189
        self.adaptMinClass = None    # The newest adapter class that can be used
190 191
        self.isDecodedTranslator = None  # Flag related to internal usage of UTF-8

192 193
    def __tokenGenerator(self):
        """Generator that reads the file and yields tokens as 4-tuples.
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208
        The tokens have the form (tokenId, tokenString, lineNo). The
        last returned token has the form ('eof', None, None). When trying
        to access next token afer that, the exception would be raised."""

        # Set the dictionary for recognizing tokenId for keywords, separators
        # and the similar categories. The key is the string to be recognized,
        # the value says its token identification.
        tokenDic = { 'class':     'class',
                     'const':     'const',
                     'public':    'public',
                     'protected': 'protected',
                     'private':   'private',
                     'static':    'static',
                     'virtual':   'virtual',
209
                     ':':         'colon',
210 211
                     ';':         'semic',
                     ',':         'comma',
212
                     '[':         'lsqbra',
213
                     ']':         'rsqbra',
214
                     '(':         'lpar',
215
                     ')':         'rpar',
216
                     '{':         'lcurly',
217 218 219 220 221 222 223 224 225 226 227 228 229 230
                     '}':         'rcurly',
                     '=':         'assign',
                     '*':         'star',
                     '&':         'amp',
                     '+':         'plus',
                     '-':         'minus',
                     '!':         'excl',
                     '?':         'qmark',
                     '<':         'lt',
                     '>':         'gt',
                     "'":         'quot',
                     '"':         'dquot',
                     '.':         'dot',
                     '%':         'perc',
231 232
                     '~':         'tilde',
                     '^':         'caret',
233
                   }
234

235 236 237 238 239
        # Regular expression for recognizing identifiers.
        rexId = re.compile(r'^[a-zA-Z]\w*$')

        # Open the file for reading and extracting tokens until the eof.
        # Initialize the finite automaton.
240
        f = open(self.fname)
241 242 243 244
        lineNo = 0
        line = ''         # init -- see the pos initialization below
        linelen = 0       # init
        pos = 100         # init -- pos after the end of line
245 246
        status = 0

247 248 249
        tokenId = None    # init
        tokenStr = ''     # init -- the characters will be appended.
        tokenLineNo = 0
Dimitri van Heesch's avatar
Dimitri van Heesch committed
250

251
        while status != 777:
252

253 254 255 256 257 258
            # Get the next character. Read next line first, if necessary.
            if pos < linelen:
                c = line[pos]
            else:
                lineNo += 1
                line = f.readline()
259 260
                if line.startswith('\xef\xbb\xbf'):
                    line = line[3:]    # skip the BOM
261 262
                linelen = len(line)
                pos = 0
263
                if line == '':         # eof
264 265 266
                    status = 777
                else:
                    c = line[pos]
267

268 269 270
            # Consume the character based on the status

            if status == 0:     # basic status
271

272 273 274 275 276 277
                # This is the initial status. If tokenId is set, yield the
                # token here and only here (except when eof is found).
                # Initialize the token variables after the yield.
                if tokenId:
                    # If it is an unknown item, it can still be recognized
                    # here. Keywords and separators are the example.
278
                    if tokenId == 'unknown':
279 280 281 282 283 284 285 286
                        if tokenDic.has_key(tokenStr):
                            tokenId = tokenDic[tokenStr]
                        elif tokenStr.isdigit():
                            tokenId = 'num'
                        elif rexId.match(tokenStr):
                            tokenId = 'id'
                        else:
                            msg = '\aWarning: unknown token "' + tokenStr + '"'
287
                            msg += '\tfound on line %d' % tokenLineNo
288
                            msg += ' in "' + self.fname + '".\n'
289
                            sys.stderr.write(msg)
290

291
                    yield (tokenId, tokenStr, tokenLineNo)
292

293
                    # If it is a comment that contains the self.translateMeText
294 295 296
                    # string, set the flag -- the situation will be reported.
                    if tokenId == 'comment' and tokenStr.find(self.translateMeText) >= 0:
                        self.translateMeFlag = True
297

298 299
                    tokenId = None
                    tokenStr = ''
300 301
                    tokenLineNo = 0

302 303 304
                # Now process the character. When we just skip it (spaces),
                # stay in this status. All characters that will be part of
                # some token cause moving to the specific status. And only
305
                # when moving to the status == 0 (or the final state 777),
306
                # the token is yielded. With respect to that the automaton
307 308
                # behaves as Moore's one (output bound to status). When
                # collecting tokens, the automaton is the Mealy's one
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
                # (actions bound to transitions).
                if c.isspace():
                    pass                 # just skip whitespace characters
                elif c == '/':           # Possibly comment starts here, but
                    tokenId = 'unknown'  # it could be only a slash in code.
                    tokenStr = c
                    tokenLineNo = lineNo
                    status = 1
                elif c == '#':
                    tokenId = 'preproc'  # preprocessor directive
                    tokenStr = c
                    tokenLineNo = lineNo
                    status = 5
                elif c == '"':           # string starts here
                    tokenId = 'string'
                    tokenStr = c
                    tokenLineNo = lineNo
                    status = 6
                elif c == "'":           # char literal starts here
                    tokenId = 'charlit'
                    tokenStr = c
                    tokenLineNo = lineNo
                    status = 8
332
                elif tokenDic.has_key(c):  # known one-char token
333 334 335 336 337 338 339 340 341
                    tokenId = tokenDic[c]
                    tokenStr = c
                    tokenLineNo = lineNo
                    # stay in this state to yield token immediately
                else:
                    tokenId = 'unknown'  # totally unknown
                    tokenStr = c
                    tokenLineNo = lineNo
                    status = 333
342

343
                pos += 1                 # move position in any case
344

345 346 347 348
            elif status == 1:            # possibly a comment
                if c == '/':             # ... definitely the C++ comment
                    tokenId = 'comment'
                    tokenStr += c
349
                    pos += 1
350 351 352 353
                    status = 2
                elif c == '*':           # ... definitely the C comment
                    tokenId = 'comment'
                    tokenStr += c
354
                    pos += 1
355 356 357
                    status = 3
                else:
                    status = 0           # unrecognized, don't move pos
358

359 360 361 362 363 364
            elif status == 2:            # inside the C++ comment
                if c == '\n':            # the end of C++ comment
                    status = 0           # yield the token
                else:
                    tokenStr += c        # collect the C++ comment
                pos += 1
365

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
            elif status == 3:            # inside the C comment
                if c == '*':             # possibly the end of the C comment
                    tokenStr += c
                    status = 4
                else:
                    tokenStr += c        # collect the C comment
                pos += 1

            elif status == 4:            # possibly the end of the C comment
                if c == '/':             # definitely the end of the C comment
                    tokenStr += c
                    status = 0           # yield the token
                elif c == '*':           # more stars inside the comment
                    tokenStr += c
                else:
                    tokenStr += c        # this cannot be the end of comment
                    status = 3
                pos += 1

            elif status == 5:            # inside the preprocessor directive
                if c == '\n':            # the end of the preproc. command
                    status = 0           # yield the token
                else:
                    tokenStr += c        # collect the preproc
                pos += 1
391

392 393 394 395 396 397 398 399 400 401
            elif status == 6:            # inside the string
                if c == '\\':            # escaped char inside the string
                    tokenStr += c
                    status = 7
                elif c == '"':           # end of the string
                    tokenStr += c
                    status = 0
                else:
                    tokenStr += c        # collect the chars of the string
                pos += 1
402

403 404 405 406
            elif status == 7:            # escaped char inside the string
                tokenStr += c            # collect the char of the string
                status = 6
                pos += 1
407

408 409 410 411
            elif status == 8:            # inside the char literal
                tokenStr += c            # collect the char of the literal
                status = 9
                pos += 1
412

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
            elif status == 9:            # end of char literal expected
                if c == "'":             # ... and found
                    tokenStr += c
                    status = 0
                    pos += 1
                else:
                    tokenId = 'error'    # end of literal was expected
                    tokenStr += c
                    status = 0

            elif status == 333:          # start of the unknown token
                if c.isspace():
                    pos += 1
                    status = 0           # tokenId may be determined later
                elif tokenDic.has_key(c):  # separator, don't move pos
                    status = 0
                else:
                    tokenStr += c        # collect
                    pos += 1
432 433

        # We should have finished in the final status. If some token
434 435 436 437 438 439
        # have been extracted, yield it first.
        assert(status == 777)
        if tokenId:
            yield (tokenId, tokenStr, tokenLineNo)
            tokenId = None
            tokenStr = ''
440
            tokenLineNo = 0
441

442
        # The file content is processed. Close the file. Then always yield
443 444 445
        # the eof token.
        f.close()
        yield ('eof', None, None)
446 447


448 449
    def __collectClassInfo(self, tokenIterator):
        """Collect the information about the class and base class.
450

451 452
        The tokens including the opening left curly brace of the class are
        consumed."""
453

454
        status = 0  # initial state
455

456
        while status != 777:   # final state
457

458 459 460 461 462 463 464 465
            # Always assume that the previous tokens were processed. Get
            # the next one.
            tokenId, tokenStr, tokenLineNo = tokenIterator.next()

            # Process the token and never return back.
            if status == 0:    # waiting for the 'class' keyword.
                if tokenId == 'class':
                    status = 1
466

467 468 469 470 471 472
            elif status == 1:  # expecting the class identification
                if tokenId == 'id':
                    self.classId = tokenStr
                    status = 2
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
473

474 475 476 477 478 479 480
            elif status == 2:  # expecting the curly brace or base class info
                if tokenId == 'lcurly':
                    status = 777        # correctly finished
                elif tokenId == 'colon':
                    status = 3
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
481

482 483 484 485 486
            elif status == 3:  # expecting the 'public' in front of base class id
                if tokenId == 'public':
                    status = 4
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
487

488 489 490 491 492 493
            elif status == 4:  # expecting the base class id
                if tokenId == 'id':
                    self.baseClassId = tokenStr
                    status = 5
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
494

495 496 497 498 499 500 501
            elif status == 5:  # expecting the curly brace and quitting
                if tokenId == 'lcurly':
                    status = 777        # correctly finished
                elif tokenId == 'comment':
                    pass
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
502

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        # Extract the status of the TranslatorXxxx class. The readable form
        # will be used in reports the status form is a string that can be
        # compared lexically (unified length, padding with zeros, etc.).
        if self.baseClassId:
            lst = self.baseClassId.split('_')
            if lst[0] == 'Translator':
                self.readableStatus = 'up-to-date'
                self.status = ''
            elif lst[0] == 'TranslatorAdapter':
                self.status = lst[1] + '.' + lst[2]
                self.readableStatus = self.status
                if len(lst) > 3:        # add the last part of the number
                    self.status += '.' + ('%02d' % int(lst[3]))
                    self.readableStatus += '.' + lst[3]
                else:
                    self.status += '.00'
            elif lst[0] == 'TranslatorEnglish':
                # Obsolete or Based on English.
                if self.classId[-2:] == 'En':
                    self.readableStatus = 'English based'
                    self.status = 'En'
                else:
                    self.readableStatus = 'obsolete'
                    self.status = '0.0.00'
527

528
            # Check whether status was set, or set 'strange'.
529
            if self.status == None:
530
                self.status = 'strange'
531
            if not self.readableStatus:
532
                self.readableStatus = 'strange'
533

534 535 536 537 538 539 540 541
            # Extract the name of the language and the readable form.
            self.lang = self.classId[10:]  # without 'Translator'
            if self.lang == 'Brazilian':
                self.langReadable = 'Brazilian Portuguese'
            elif self.lang == 'Chinesetraditional':
                self.langReadable = 'Chinese Traditional'
            else:
                self.langReadable = self.lang
542

Dimitri van Heesch's avatar
Dimitri van Heesch committed
543

544 545
    def __unexpectedToken(self, status, tokenId, tokenLineNo):
        """Reports unexpected token and quits with exit code 1."""
546

547 548 549 550 551 552 553
        import inspect
        calledFrom = inspect.stack()[1][3]
        msg = "\a\nUnexpected token '%s' on the line %d in '%s'.\n"
        msg = msg % (tokenId, tokenLineNo, self.fname)
        msg += 'status = %d in %s()\n' % (status, calledFrom)
        sys.stderr.write(msg)
        sys.exit(1)
554 555


556 557
    def collectPureVirtualPrototypes(self):
        """Returns dictionary 'unified prototype' -> 'full prototype'.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
558

559 560 561
        The method is expected to be called only for the translator.h. It
        extracts only the pure virtual method and build the dictionary where
        key is the unified prototype without argument identifiers."""
562

563 564
        # Prepare empty dictionary that will be returned.
        resultDic = {}
565

566 567 568 569 570 571
        # Start the token generator which parses the class source file.
        tokenIterator = self.__tokenGenerator()

        # Collect the class and the base class identifiers.
        self.__collectClassInfo(tokenIterator)
        assert(self.classId == 'Translator')
572

573 574 575 576 577 578 579
        # Let's collect readable form of the public virtual pure method
        # prototypes in the readable form -- as defined in translator.h.
        # Let's collect also unified form of the same prototype that omits
        # everything that can be omitted, namely 'virtual' and argument
        # identifiers.
        prototype = ''    # readable prototype (with everything)
        uniPrototype = '' # unified prototype (without arg. identifiers)
580

581 582 583 584 585 586 587
        # Collect the pure virtual method prototypes. Stop on the closing
        # curly brace followed by the semicolon (end of class).
        status = 0
        curlyCnt = 0      # counter for the level of curly braces

        # Loop until the final state 777 is reached. The errors are processed
        # immediately. In this implementation, it always quits the application.
588 589
        while status != 777:

590 591
            # Get the next token.
            tokenId, tokenStr, tokenLineNo = tokenIterator.next()
592

593 594 595
            if status == 0:      # waiting for 'public:'
                if tokenId == 'public':
                    status = 1
596

597 598 599 600 601
            elif status == 1:    # colon after the 'public'
                if tokenId == 'colon':
                    status = 2
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
602

603 604 605 606 607 608 609 610 611 612
            elif status == 2:    # waiting for 'virtual'
                if tokenId == 'virtual':
                    prototype = tokenStr  # but not to unified prototype
                    status = 3
                elif tokenId == 'comment':
                    pass
                elif tokenId == 'rcurly':
                    status = 11         # expected end of class
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
613

614 615 616 617 618
            elif status == 3:    # return type of the method expected
                if tokenId == 'id':
                    prototype += ' ' + tokenStr
                    uniPrototype = tokenStr  # start collecting the unified prototype
                    status = 4
619 620
		elif tokenId == 'tilde':
                    status = 4
621 622
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
623

624 625 626 627 628 629 630
            elif status == 4:    # method identifier expected
                if tokenId == 'id':
                    prototype += ' ' + tokenStr
                    uniPrototype += ' ' + tokenStr
                    status = 5
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
631

632 633 634 635 636 637 638
            elif status == 5:    # left bracket of the argument list expected
                if tokenId == 'lpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 6
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
639

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
            elif status == 6:    # collecting arguments of the method
                if tokenId == 'rpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 7
                elif tokenId == 'const':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 12
                elif tokenId == 'id':           # type identifier
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 13
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
655

656 657 658 659
            elif status == 7:    # assignment expected or left curly brace
                if tokenId == 'assign':
                    status = 8
                elif tokenId == 'lcurly':
660
                    curlyCnt = 1      # method body entered
661 662 663
                    status = 10
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
664

665 666 667 668 669
            elif status == 8:    # zero expected
                if tokenId == 'num' and tokenStr == '0':
                    status = 9
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
670

671 672 673 674 675 676 677
            elif status == 9:    # after semicolon, produce the dic item
                if tokenId == 'semic':
                    assert(not resultDic.has_key(uniPrototype))
                    resultDic[uniPrototype] = prototype
                    status = 2
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
678

679 680 681 682 683 684 685
            elif status == 10:   # consuming the body of the method
                if tokenId == 'rcurly':
                    curlyCnt -= 1
                    if curlyCnt == 0:
                        status = 2     # body consumed
                elif tokenId == 'lcurly':
                    curlyCnt += 1
686

687 688 689 690 691
            elif status == 11:   # probably the end of class
                if tokenId == 'semic':
                    status = 777
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
692

693 694 695 696 697 698 699
            elif status == 12:   # type id for argument expected
                if tokenId == 'id':
                    prototype += ' ' + tokenStr
                    uniPrototype += ' ' + tokenStr
                    status = 13
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
700

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
            elif status == 13:   # namespace qualification or * or & expected
                if tokenId == 'colon':        # was namespace id
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 14
                elif tokenId == 'star' or tokenId == 'amp':  # pointer or reference
                    prototype += ' ' + tokenStr
                    uniPrototype += ' ' + tokenStr
                    status = 16
                elif tokenId == 'id':         # argument identifier
                    prototype += ' ' + tokenStr
                    # don't put this into unified prototype
                    status = 17
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
716

717
            elif status == 14:   # second colon for namespace:: expected
718
                if tokenId == 'colon':
719 720 721 722 723
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 15
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
724

725
            elif status == 15:   # type after namespace:: expected
726
                if tokenId == 'id':
727 728 729 730 731
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 13
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
732

733
            elif status == 16:   # argument identifier expected
734
                if tokenId == 'id':
735 736 737 738 739
                    prototype += ' ' + tokenStr
                    # don't put this into unified prototype
                    status = 17
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
740

741
            elif status == 17:   # comma or ')' after argument identifier expected
742
                if tokenId == 'comma':
743 744 745 746 747 748 749 750 751
                    prototype += ', '
                    uniPrototype += ', '
                    status = 6
                elif tokenId == 'rpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 7
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
752

753 754 755
        # Eat the rest of the source to cause closing the file.
        while tokenId != 'eof':
            tokenId, tokenStr, tokenLineNo = tokenIterator.next()
756

757 758
        # Return the resulting dictionary with 'uniPrototype -> prototype'.
        return resultDic
759 760 761


    def __collectPublicMethodPrototypes(self, tokenIterator):
762
        """Collects prototypes of public methods and fills self.prototypeDic.
763 764

        The dictionary is filled by items: uniPrototype -> prototype.
765 766 767
        The method is expected to be called only for TranslatorXxxx classes,
        i.e. for the classes that implement translation to some language.
        It assumes that the openning curly brace of the class was already
768 769
        consumed. The source is consumed until the end of the class.
        The caller should consume the source until the eof to cause closing
770
        the source file."""
771

772 773 774 775 776 777 778 779 780 781 782
        assert(self.classId != 'Translator')
        assert(self.baseClassId != None)

        # The following finite automaton slightly differs from the one
        # inside self.collectPureVirtualPrototypes(). It produces the
        # dictionary item just after consuming the body of the method
        # (transition from from state 10 to state 2). It also does not allow
        # definitions of public pure virtual methods, except for
        # TranslatorAdapterBase (states 8 and 9). Argument identifier inside
        # method argument lists can be omitted or commented.
        #
783
        # Let's collect readable form of all public method prototypes in
784 785 786 787 788 789
        # the readable form -- as defined in the source file.
        # Let's collect also unified form of the same prototype that omits
        # everything that can be omitted, namely 'virtual' and argument
        # identifiers.
        prototype = ''    # readable prototype (with everything)
        uniPrototype = '' # unified prototype (without arg. identifiers)
790 791
        warning = ''      # warning message -- if something special detected
        methodId = None   # processed method id
792

793 794 795 796 797 798 799
        # Collect the method prototypes. Stop on the closing
        # curly brace followed by the semicolon (end of class).
        status = 0
        curlyCnt = 0      # counter for the level of curly braces

        # Loop until the final state 777 is reached. The errors are processed
        # immediately. In this implementation, it always quits the application.
800 801
        while status != 777:

802 803
            # Get the next token.
            tokenId, tokenStr, tokenLineNo = tokenIterator.next()
804

805 806 807 808 809
            if status == 0:      # waiting for 'public:'
                if tokenId == 'public':
                    status = 1
                elif tokenId == 'eof':  # non-public things until the eof
                    status = 777
810

811 812 813 814 815
            elif status == 1:    # colon after the 'public'
                if tokenId == 'colon':
                    status = 2
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
816

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
            elif status == 2:    # waiting for 'virtual' (can be omitted)
                if tokenId == 'virtual':
                    prototype = tokenStr  # but not to unified prototype
                    status = 3
                elif tokenId == 'id':     # 'virtual' was omitted
                    prototype = tokenStr
                    uniPrototype = tokenStr  # start collecting the unified prototype
                    status = 4
                elif tokenId == 'comment':
                    pass
                elif tokenId == 'protected' or tokenId == 'private':
                    status = 0
                elif tokenId == 'rcurly':
                    status = 11         # expected end of class
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
833

834 835 836 837 838 839 840
            elif status == 3:    # return type of the method expected
                if tokenId == 'id':
                    prototype += ' ' + tokenStr
                    uniPrototype = tokenStr  # start collecting the unified prototype
                    status = 4
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
841

842 843 844 845
            elif status == 4:    # method identifier expected
                if tokenId == 'id':
                    prototype += ' ' + tokenStr
                    uniPrototype += ' ' + tokenStr
846
                    methodId = tokenStr    # for reporting
847 848 849
                    status = 5
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
850

851 852 853 854 855 856 857
            elif status == 5:    # left bracket of the argument list expected
                if tokenId == 'lpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 6
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
858

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
            elif status == 6:    # collecting arguments of the method
                if tokenId == 'rpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 7
                elif tokenId == 'const':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 12
                elif tokenId == 'id':           # type identifier
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 13
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
874 875

            elif status == 7:    # left curly brace expected
876
                if tokenId == 'lcurly':
877
                    curlyCnt = 1      # method body entered
878 879 880 881 882 883 884 885
                    status = 10
                elif tokenId == 'comment':
                    pass
                elif tokenId == 'assign': # allowed only for TranslatorAdapterBase
                    assert(self.classId == 'TranslatorAdapterBase')
                    status = 8
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
886

887 888 889 890 891 892
            elif status == 8:    # zero expected (TranslatorAdapterBase)
                assert(self.classId == 'TranslatorAdapterBase')
                if tokenId == 'num' and tokenStr == '0':
                    status = 9
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
893

894 895 896 897 898 899 900 901 902 903 904
            elif status == 9:    # after semicolon (TranslatorAdapterBase)
                assert(self.classId == 'TranslatorAdapterBase')
                if tokenId == 'semic':
                    status = 2
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)

            elif status == 10:   # consuming the body of the method, then dic item
                if tokenId == 'rcurly':
                    curlyCnt -= 1
                    if curlyCnt == 0:
905 906 907 908 909 910 911 912 913 914
                        # Check for possible copy/paste error when name
                        # of the method was not corrected (i.e. the same
                        # name already exists).
                        if uniPrototype in self.prototypeDic:
                            msg = "'%s' prototype found again (duplicity)\n"
                            msg += "in '%s'.\n" % self.fname
                            msg = msg % uniPrototype
                            sys.stderr.write(msg)
                            assert False

915
                        assert(not self.prototypeDic.has_key(uniPrototype))
916
                        # Insert new dictionary item.
917
                        self.prototypeDic[uniPrototype] = prototype
918 919
                        status = 2      # body consumed
                        methodId = None # outside of any method
920 921
                elif tokenId == 'lcurly':
                    curlyCnt += 1
922 923

                # Warn in special case.
924 925
                elif methodId == 'trLegendDocs' and tokenId == 'string' \
                    and tokenStr.find('MAX_DOT_GRAPH_HEIGHT') >= 0:
926 927 928
                        self.txtMAX_DOT_GRAPH_HEIGHT_flag = True


929 930 931 932 933
            elif status == 11:   # probably the end of class
                if tokenId == 'semic':
                    status = 777
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
934

935 936 937 938 939 940 941
            elif status == 12:   # type id for argument expected
                if tokenId == 'id':
                    prototype += ' ' + tokenStr
                    uniPrototype += ' ' + tokenStr
                    status = 13
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
942

943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
            elif status == 13:   # :: or * or & or id or ) expected
                if tokenId == 'colon':        # was namespace id
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 14
                elif tokenId == 'star' or tokenId == 'amp':  # pointer or reference
                    prototype += ' ' + tokenStr
                    uniPrototype += ' ' + tokenStr
                    status = 16
                elif tokenId == 'id':         # argument identifier
                    prototype += ' ' + tokenStr
                    # don't put this into unified prototype
                    status = 17
                elif tokenId == 'comment':    # probably commented-out identifier
                    prototype += tokenStr
                elif tokenId == 'rpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 7
962
                elif tokenId == 'comma':
963 964 965 966 967
                    prototype += ', '
                    uniPrototype += ', '
                    status = 6
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
968

969
            elif status == 14:   # second colon for namespace:: expected
970
                if tokenId == 'colon':
971 972 973 974 975
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 15
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
976

977
            elif status == 15:   # type after namespace:: expected
978
                if tokenId == 'id':
979 980 981 982 983
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 13
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
984

985
            elif status == 16:   # argument identifier or ) expected
986
                if tokenId == 'id':
987 988 989 990 991 992 993 994 995 996 997
                    prototype += ' ' + tokenStr
                    # don't put this into unified prototype
                    status = 17
                elif tokenId == 'rpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 7
                elif tokenId == 'comment':
                    prototype += tokenStr
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
998

999
            elif status == 17:   # comma or ')' after argument identifier expected
1000
                if tokenId == 'comma':
1001 1002 1003 1004 1005 1006 1007 1008 1009
                    prototype += ', '
                    uniPrototype += ', '
                    status = 6
                elif tokenId == 'rpar':
                    prototype += tokenStr
                    uniPrototype += tokenStr
                    status = 7
                else:
                    self.__unexpectedToken(status, tokenId, tokenLineNo)
1010 1011


Dimitri van Heesch's avatar
Dimitri van Heesch committed
1012

1013 1014
    def collectAdapterPrototypes(self):
        """Returns the dictionary of prototypes implemented by adapters.
1015 1016

        It is created to process the translator_adapter.h. The returned
1017
        dictionary has the form: unifiedPrototype -> (version, classId)
1018 1019 1020
        thus by looking for the prototype, we get the information what is
        the newest (least adapting) adapter that is sufficient for
        implementing the method."""
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1021

1022 1023 1024
        # Start the token generator which parses the class source file.
        assert(os.path.split(self.fname)[1] == 'translator_adapter.h')
        tokenIterator = self.__tokenGenerator()
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1025

1026 1027
        # Get the references to the involved dictionaries.
        reqDic = self.manager.requiredMethodsDic
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1028

1029 1030
        # Create the empty dictionary that will be returned.
        adaptDic = {}
1031 1032


1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        # Loop through the source of the adapter file until no other adapter
        # class is found.
        while True:
            try:
                # Collect the class and the base class identifiers.
                self.__collectClassInfo(tokenIterator)

                # Extract the comparable version of the adapter class.
                # Note: The self.status as set by self.__collectClassInfo()
                # contains similar version, but is related to the base class,
                # not to the class itself.
                lst = self.classId.split('_')
                version = ''
                if lst[0] == 'TranslatorAdapter': # TranslatorAdapterBase otherwise
                    version = lst[1] + '.' + lst[2]
                    if len(lst) > 3:        # add the last part of the number
                        version += '.' + ('%02d' % int(lst[3]))
                    else:
                        version += '.00'
1052

1053 1054
                # Collect the prototypes of implemented public methods.
                self.__collectPublicMethodPrototypes(tokenIterator)
1055 1056

                # For the required methods, update the dictionary of methods
1057 1058 1059 1060
                # implemented by the adapter.
                for protoUni in self.prototypeDic:
                    if reqDic.has_key(protoUni):
                        # This required method will be marked as implemented
1061
                        # by this adapter class. This implementation assumes
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                        # that newer adapters do not reimplement any required
                        # methods already implemented by older adapters.
                        assert(not adaptDic.has_key(protoUni))
                        adaptDic[protoUni] = (version, self.classId)

                # Clear the dictionary object and the information related
                # to the class as the next adapter class is to be processed.
                self.prototypeDic.clear()
                self.classId = None
                self.baseClassId = None
1072

1073 1074
            except StopIteration:
                break
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1075

1076
        # Return the result dictionary.
1077 1078
        return adaptDic

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1079

1080
    def processing(self):
1081
        """Processing of the source file -- only for TranslatorXxxx classes."""
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1082

1083 1084
        # Start the token generator which parses the class source file.
        tokenIterator = self.__tokenGenerator()
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1085

1086 1087 1088 1089
        # Collect the class and the base class identifiers.
        self.__collectClassInfo(tokenIterator)
        assert(self.classId != 'Translator')
        assert(self.classId[:17] != 'TranslatorAdapter')
1090

1091 1092
        # Collect the prototypes of implemented public methods.
        self.__collectPublicMethodPrototypes(tokenIterator)
1093

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        # Eat the rest of the source to cause closing the file.
        while True:
            try:
                t = tokenIterator.next()
            except StopIteration:
                break

        # Shorthands for the used dictionaries.
        reqDic = self.manager.requiredMethodsDic
        adaptDic = self.manager.adaptMethodsDic
        myDic = self.prototypeDic
1105

1106 1107 1108 1109 1110
        # Build the list of obsolete methods.
        self.obsoleteMethods = []
        for p in myDic:
            if not reqDic.has_key(p):
                self.obsoleteMethods.append(p)
1111

1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
        # Build the list of missing methods and the list of implemented
        # required methods.
        self.missingMethods = []
        self.implementedMethods = []
        for p in reqDic:
            if myDic.has_key(p):
                self.implementedMethods.append(p)
            else:
                self.missingMethods.append(p)

1122 1123 1124 1125 1126 1127
        # Set the least important note first if the translator is decoded.
        # If yes, then it means that the implementation should be switched
        # to UTF-8 later (suggestion).
        self.isDecodedTranslator = self.classId in self.manager.decodedTranslators
        if self.isDecodedTranslator:
            self.note = 'Reimplementation using UTF-8 suggested.'
1128

1129 1130 1131
        # Check whether adapter must be used or suggest the newest one.
        # Change the status and set the note accordingly.
        if self.baseClassId != 'Translator':
1132
            if not self.missingMethods:
1133 1134 1135 1136 1137
                self.note = 'Change the base class to Translator.'
                self.status = ''
                self.readableStatus = 'up-to-date'
            elif self.baseClassId != 'TranslatorEnglish':
                # The translator uses some of the adapters.
1138
                # Look at the missing methods and check what adapter
1139 1140 1141 1142 1143 1144 1145 1146 1147
                # implements them. Remember the one with the lowest version.
                adaptMinVersion = '9.9.99'
                adaptMinClass = 'TranslatorAdapter_9_9_99'
                for uniProto in self.missingMethods:
                    if adaptDic.has_key(uniProto):
                        version, cls = adaptDic[uniProto]
                        if version < adaptMinVersion:
                            adaptMinVersion = version
                            adaptMinClass = cls
1148

1149
                # Test against the current status -- preserve the self.status.
1150
                # Possibly, the translator implements enough methods to
1151 1152
                # use some newer adapter.
                status = self.status
1153

1154 1155 1156 1157 1158 1159 1160 1161
                # If the version of the used adapter is smaller than
                # the required, set the note and update the status as if
                # the newer adapter was used.
                if adaptMinVersion > status:
                    self.note = 'Change the base class to %s.' % adaptMinClass
                    self.status = adaptMinVersion
                    self.adaptMinClass = adaptMinClass
                    self.readableStatus = adaptMinVersion # simplified
1162 1163 1164

        # If everything seems OK, some explicit warning flags still could
        # be set.
1165 1166
        if not self.note and self.status == '' and \
           (self.translateMeFlag or self.txtMAX_DOT_GRAPH_HEIGHT_flag):
1167
           self.note = ''
1168 1169 1170
           if self.translateMeFlag:
               self.note += 'The "%s" found in a comment.' % self.translateMeText
           if self.note != '':
1171
               self.note += '\n\t\t'
1172 1173
           if self.txtMAX_DOT_GRAPH_HEIGHT_flag:
                self.note += 'The MAX_DOT_GRAPH_HEIGHT found in trLegendDocs()'
1174 1175

        # If everything seems OK, but there are obsolete methods, set
1176 1177 1178 1179
        # the note to clean-up source. This note will be used only when
        # the previous code did not set another note (priority).
        if not self.note and self.status == '' and self.obsoleteMethods:
            self.note = 'Remove the obsolete methods (never used).'
1180 1181


1182 1183
    def report(self, fout):
        """Returns the report part for the source as a multiline string.
1184

1185
        No output for up-to-date translators without problem."""
1186

1187 1188 1189
        # If there is nothing to report, return immediately.
        if self.status == '' and not self.note:
            return
1190

1191 1192 1193
        # Report the number of not implemented methods.
        fout.write('\n\n\n')
        fout.write(self.classId + '   (' + self.baseClassId + ')')
1194
        percentImplemented = 100    # init
1195
        allNum = len(self.manager.requiredMethodsDic)
1196
        if self.missingMethods:
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1197
            num = len(self.missingMethods)
1198
            percentImplemented = 100 * (allNum - num) / allNum
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1199 1200 1201 1202
            fout.write('  %d' % num)
            fout.write(' method')
            if num > 1:
                fout.write('s')
1203
            fout.write(' to implement (%d %%)' % (100 * num / allNum))
1204
        fout.write('\n' + '-' * len(self.classId))
1205

1206 1207
        # Write the info about the implemented required methods.
        fout.write('\n\n  Implements %d' % len(self.implementedMethods))
1208
        fout.write(' of the required methods (%d %%).' % percentImplemented)
1209

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
        # Report the missing method, but only when it is not English-based
        # translator.
        if self.missingMethods and self.status != 'En':
            fout.write('\n\n  Missing methods (should be implemented):\n')
            reqDic = self.manager.requiredMethodsDic
            for p in self.missingMethods:
                fout.write('\n    ' + reqDic[p])

        # Always report obsolete methods.
        if self.obsoleteMethods:
            fout.write('\n\n  Obsolete methods (should be removed, never used):\n')
            myDic = self.prototypeDic
            for p in self.obsoleteMethods:
                fout.write('\n    ' + myDic[p])

        # For English-based translator, report the implemented methods.
        if self.status == 'En' and self.implementedMethods:
            fout.write('\n\n  This English-based translator implements ')
            fout.write('the following methods:\n')
            reqDic = self.manager.requiredMethodsDic
            for p in self.implementedMethods:
                fout.write('\n    ' + reqDic[p])
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1232

1233

1234 1235 1236 1237
    def getmtime(self):
        """Returns the last modification time of the source file."""
        assert(os.path.isfile(self.fname))
        return os.path.getmtime(self.fname)
1238 1239


1240 1241
class TrManager:
    """Collects basic info and builds subordinate Transl objects."""
1242

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1243
    def __init__(self):
1244
        """Determines paths, creates and initializes structures.
1245 1246

        The arguments of the script may explicitly say what languages should
1247 1248
        be processed. Write the two letter identifications that are used
        for composing the source filenames, so...
1249

1250
            python translator.py cz
1251

1252 1253
        this will process only translator_cz.h source.
        """
1254

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1255
        # Determine the path to the script and its name.
1256 1257
        self.script = os.path.abspath(sys.argv[0])
        self.script_path, self.script_name = os.path.split(self.script)
1258
        self.script_path = os.path.abspath(self.script_path)
1259

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1260 1261 1262
        # Determine the absolute path to the Doxygen's root subdirectory.
        # If DOXYGEN environment variable is not found, the directory is
        # determined from the path of the script.
1263
        doxy_default = os.path.join(self.script_path, '..')
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1264
        self.doxy_path = os.path.abspath(os.getenv('DOXYGEN', doxy_default))
1265

1266 1267
        # Get the explicit arguments of the script.
        self.script_argLst = sys.argv[1:]
1268

1269 1270 1271
        # Build the path names based on the Doxygen's root knowledge.
        self.doc_path = os.path.join(self.doxy_path, 'doc')
        self.src_path = os.path.join(self.doxy_path, 'src')
1272

1273
        # Create the empty dictionary for Transl object identitied by the
1274
        # class identifier of the translator.
1275 1276 1277 1278 1279 1280
        self.__translDic = {}

        # Create the None dictionary of required methods. The key is the
        # unified prototype, the value is the full prototype. Set inside
        # the self.__build().
        self.requiredMethodsDic = None
1281

1282 1283 1284
        # Create the empty dictionary that says what method is implemented
        # by what adapter.
        self.adaptMethodsDic = {}
1285

1286
        # The last modification time will capture the modification of this
1287
        # script, of the translator.h, of the translator_adapter.h (see the
1288 1289
        # self.__build() for the last two) of all the translator_xx.h files
        # and of the template for generating the documentation. So, this
1290
        # time can be compared with modification time of the generated
1291 1292
        # documentation to decide, whether the doc should be re-generated.
        self.lastModificationTime = os.path.getmtime(self.script)
1293

1294 1295 1296 1297 1298 1299 1300
        # Set the names of the translator report text file, of the template
        # for generating "Internationalization" document, for the generated
        # file itself, and for the maintainers list.
        self.translatorReportFileName = 'translator_report.txt'
        self.maintainersFileName = 'maintainers.txt'
        self.languageTplFileName = 'language.tpl'
        self.languageDocFileName = 'language.doc'
1301 1302

        # The information about the maintainers will be stored
1303 1304
        # in the dictionary with the following name.
        self.__maintainersDic = None
1305

1306 1307 1308 1309 1310
        # Define the other used structures and variables for information.
        self.langLst = None                   # including English based
        self.supportedLangReadableStr = None  # coupled En-based as a note
        self.numLang = None                   # excluding coupled En-based
        self.doxVersion = None                # Doxygen version
1311

1312 1313 1314
        # Capture the knowledge about translators that are not implemented
        # to use UTF-8 internally.
        self.decodedTranslators = self.getDecodedTranslators()
1315

1316 1317
        # Build objects where each one is responsible for one translator.
        self.__build()
1318 1319


1320 1321 1322
    def getDecodedTranslators(self):
        """Parses language.cpp to find what translators do not use UTF-8 yet"""
        decodedTranslators = []
1323

1324 1325 1326
        # Regular expression to detect the lines like
        #     theTranslator=new TranslatorDecoder(new TranslatorSwedish);
        rex = re.compile(r'^\s*theTranslator\s*=\s*new\s+.*$')
1327

1328 1329
        # Regular expression to get the (optional) TranslatorDecoder and TranslatorXXX
        rex2 = re.compile(r'\bTranslator\w+')
1330

1331 1332 1333 1334 1335 1336 1337 1338
        # Parse the lines in the specific source code.
        f = open(os.path.join(self.src_path, 'language.cpp'), 'rU')
        for line in f:
            if rex.match(line):
                lst = rex2.findall(line)
                if lst[0] == 'TranslatorDecoder':
                    decodedTranslators.append(lst[1])
        f.close()
1339 1340

        # Display warning when all translator implementations were converted
1341 1342 1343 1344 1345
        # to UTF-8.
        if len(decodedTranslators) == 0:
            print 'This script should be updated. All translators do use UTF-8'
            print 'internally.  The TranslatorDecoder adapter should be removed'
            print 'from the code and its usage should not be checked any more.'
1346

1347
        return decodedTranslators
1348 1349


1350 1351
    def __build(self):
        """Find the translator files and build the objects for translators."""
1352

1353 1354 1355 1356 1357 1358 1359 1360
        # The translator.h must exist (the Transl object will check it),
        # create the object for it and let it build the dictionary of
        # required methods.
        tr = Transl(os.path.join(self.src_path, 'translator.h'), self)
        self.requiredMethodsDic = tr.collectPureVirtualPrototypes()
        tim = tr.getmtime()
        if tim > self.lastModificationTime:
            self.lastModificationTime = tim
1361

1362 1363 1364 1365 1366 1367 1368
        # The translator_adapter.h must exist (the Transl object will check it),
        # create the object for it and store the reference in the dictionary.
        tr = Transl(os.path.join(self.src_path, 'translator_adapter.h'), self)
        self.adaptMethodsDic = tr.collectAdapterPrototypes()
        tim = tr.getmtime()
        if tim > self.lastModificationTime:
            self.lastModificationTime = tim
1369

1370 1371 1372 1373 1374 1375 1376 1377 1378
        # Create the list of the filenames with language translator sources.
        # If the explicit arguments of the script were typed, process only
        # those files.
        if self.script_argLst:
            lst = ['translator_' + x + '.h' for x in self.script_argLst]
            for fname in lst:
                if not os.path.isfile(os.path.join(self.src_path, fname)):
                    sys.stderr.write("\a\nFile '%s' not found!\n" % fname)
                    sys.exit(1)
1379
        else:
1380 1381 1382 1383
            lst = os.listdir(self.src_path)
            lst = filter(lambda x: x[:11] == 'translator_'
                                   and x[-2:] == '.h'
                                   and x != 'translator_adapter.h', lst)
1384 1385

        # Build the object for the translator_xx.h files, and process the
1386 1387 1388 1389 1390 1391 1392 1393 1394
        # content of the file. Then insert the object to the dictionary
        # accessed via classId.
        for fname in lst:
            fullname = os.path.join(self.src_path, fname)
            tr = Transl(fullname, self)
            tr.processing()
            assert(tr.classId != 'Translator')
            self.__translDic[tr.classId] = tr

1395
        # Extract the global information of the processed info.
1396
        self.__extractProcessedInfo()
1397 1398


1399
    def __extractProcessedInfo(self):
1400
        """Build lists and strings of the processed info."""
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1401

1402 1403 1404 1405 1406 1407 1408
        # Build the auxiliary list with strings compound of the status,
        # readable form of the language, and classId.
        statLst = []
        for obj in self.__translDic.values():
            assert(obj.classId != 'Translator')
            s = obj.status + '|' + obj.langReadable + '|' + obj.classId
            statLst.append(s)
1409

1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
        # Sort the list and extract the object identifiers (classId's) for
        # the up-to-date translators and English-based translators.
        statLst.sort()
        self.upToDateIdLst = [x.split('|')[2] for x in statLst if x[0] == '|']
        self.EnBasedIdLst = [x.split('|')[2] for x in statLst if x[:2] == 'En']

        # Reverse the list and extract the TranslatorAdapter based translators.
        statLst.reverse()
        self.adaptIdLst = [x.split('|')[2] for x in statLst if x[0].isdigit()]

1420
        # Build the list of tuples that contain (langReadable, obj).
1421 1422 1423 1424 1425
        # Sort it by readable name.
        self.langLst = []
        for obj in self.__translDic.values():
            self.langLst.append((obj.langReadable, obj))
        self.langLst.sort(lambda a, b: cmp(a[0], b[0]))
1426

1427 1428 1429 1430 1431 1432 1433
        # Create the list with readable language names. If the language has
        # also the English-based version, modify the item by appending
        # the note. Number of the supported languages is equal to the length
        # of the list.
        langReadableLst = []
        for name, obj in self.langLst:
            if obj.status == 'En': continue
1434

1435 1436 1437 1438 1439 1440
            # Append the 'En' to the classId to possibly obtain the classId
            # of the English-based object. If the object exists, modify the
            # name for the readable list of supported languages.
            classIdEn = obj.classId + 'En'
            if self.__translDic.has_key(classIdEn):
                name += ' (+En)'
1441

1442 1443 1444
            # Append the result name of the language, possibly with note.
            langReadableLst.append(name)

1445
        # Create the multiline string of readable language names,
1446 1447 1448 1449
        # with punctuation, wrapped to paragraph.
        if len(langReadableLst) == 1:
            s = langReadableLst[0]
        elif len(langReadableLst) == 2:
1450 1451 1452
            s = ' and '.join(langReadableLst)
        else:
            s = ', '.join(langReadableLst[:-1]) + ', and '
1453
            s += langReadableLst[-1]
1454 1455

        self.supportedLangReadableStr = fill(s + '.')
1456 1457 1458 1459 1460 1461 1462 1463 1464

        # Find the number of the supported languages. The English based
        # languages are not counted if the non-English based also exists.
        self.numLang = len(self.langLst)
        for name, obj in self.langLst:
            if obj.status == 'En':
                classId = obj.classId[:-2]
                if self.__translDic.has_key(classId):
                    self.numLang -= 1    # the couple will be counted as one
1465

1466
        # Extract the version of Doxygen.
1467
        f = open(os.path.join(self.doxy_path, 'VERSION'))
1468 1469
        self.doxVersion = f.readline().strip()
        f.close()
1470

1471 1472 1473 1474 1475
        # Update the last modification time.
        for tr in self.__translDic.values():
            tim = tr.getmtime()
            if tim > self.lastModificationTime:
                self.lastModificationTime = tim
1476 1477


Dimitri van Heesch's avatar
Dimitri van Heesch committed
1478 1479
    def __getNoTrSourceFilesLst(self):
        """Returns the list of sources to be checked.
1480

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1481
        All .cpp files and also .h files that do not declare or define
1482
        the translator methods are included in the list. The file names
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1483
        are searched in doxygen/src directory.
1484
        """
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1485
        files = []
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1486
        for item in os.listdir(self.src_path):
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1487 1488 1489
            # Split the bare name to get the extension.
            name, ext = os.path.splitext(item)
            ext = ext.lower()
1490

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1491 1492 1493
            # Include only .cpp and .h files (case independent) and exclude
            # the files where the checked identifiers are defined.
            if ext == '.cpp' or (ext == '.h' and name.find('translator') == -1):
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1494
                fname = os.path.join(self.src_path, item)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1495 1496 1497
                assert os.path.isfile(fname) # assumes no directory with the ext
                files.append(fname)          # full name
        return files
1498 1499


Dimitri van Heesch's avatar
Dimitri van Heesch committed
1500 1501
    def __removeUsedInFiles(self, fname, dic):
        """Removes items for method identifiers that are found in fname.
1502

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1503 1504 1505
        The method reads the content of the file as one string and searches
        for all identifiers from dic. The identifiers that were found in
        the file are removed from the dictionary.
1506

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1507
        Note: If more files is to be checked, the files where most items are
1508
        probably used should be checked first and the resulting reduced
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1509 1510 1511
        dictionary should be used for checking the next files (speed up).
        """
        lst_in = dic.keys()   # identifiers to be searched for
1512

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1513 1514
        # Read content of the file as one string.
        assert os.path.isfile(fname)
1515
        f = open(fname)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1516 1517
        cont = f.read()
        f.close()
1518

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1519 1520 1521 1522 1523 1524
        # Remove the items for identifiers that were found in the file.
        while lst_in:
            item = lst_in.pop(0)
            if cont.find(item) != -1:
                del dic[item]

1525

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1526 1527
    def __checkForNotUsedTrMethods(self):
        """Returns the dictionary of not used translator methods.
1528

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
        The method can be called only after self.requiredMethodsDic has been
        built. The stripped prototypes are the values, the method identifiers
        are the keys.
        """
        # Build the dictionary of the required method prototypes with
        # method identifiers used as keys.
        trdic = {}
        for prototype in self.requiredMethodsDic.keys():
            ri = prototype.split('(')[0]
            identifier = ri.split()[1].strip()
            trdic[identifier] = prototype
1540

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1541 1542 1543
        # Build the list of source files where translator method identifiers
        # can be used.
        files = self.__getNoTrSourceFilesLst()
1544

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1545 1546 1547
        # Loop through the files and reduce the dictionary of id -> proto.
        for fname in files:
            self.__removeUsedInFiles(fname, trdic)
1548

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1549 1550
        # Return the dictionary of not used translator methods.
        return trdic
1551 1552


1553 1554
    def __emails(self, classId):
        """Returns the list of maintainer emails.
1555

1556
        The method returns the list of e-mail adresses for the translator
1557
        class, but only the addresses that were not marked as [xxx]."""
1558 1559
        lst = []
        for m in self.__maintainersDic[classId]:
1560
            if not m[1].startswith('['):
1561
                email = m[1]
1562
                email = email.replace(' at ', '@') # Unmangle the mangled e-mail
1563 1564 1565
                email = email.replace(' dot ', '.')
                lst.append(email)
        return lst
1566 1567


1568 1569
    def generateTranslatorReport(self):
        """Generates the translator report."""
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1570

1571
        output = os.path.join(self.doc_path, self.translatorReportFileName)
1572

1573
        # Open the textual report file for the output.
1574
        f = open(output, 'w')
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1575

1576 1577
        # Output the information about the version.
        f.write('(' + self.doxVersion + ')\n\n')
1578

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
        # Output the information about the number of the supported languages
        # and the list of the languages, or only the note about the explicitly
        # given languages to process.
        if self.script_argLst:
            f.write('The report was generated for the following, explicitly')
            f.write(' identified languages:\n\n')
            f.write(self.supportedLangReadableStr + '\n\n')
        else:
            f.write('Doxygen supports the following ')
            f.write(str(self.numLang))
            f.write(' languages (sorted alphabetically):\n\n')
            f.write(self.supportedLangReadableStr + '\n\n')
1591 1592

            # Write the summary about the status of language translators (how
1593 1594
            # many translators) are up-to-date, etc.
            s = 'Of them, %d translators are up-to-date, ' % len(self.upToDateIdLst)
1595
            s += '%d translators are based on some adapter class, ' % len(self.adaptIdLst)
1596 1597
            s += 'and %d are English based.' % len(self.EnBasedIdLst)
            f.write(fill(s) + '\n\n')
1598 1599

        # The e-mail addresses of the maintainers will be collected to
1600 1601
        # the auxiliary file in the order of translator classes listed
        # in the translator report.
1602
        fmail = open('mailto.txt', 'w')
1603 1604

        # Write the list of up-to-date translator classes.
1605 1606 1607 1608
        if self.upToDateIdLst:
            s = '''The following translator classes are up-to-date (sorted
                alphabetically). This means that they derive from the
                Translator class and they implement all %d of the required
1609
                methods. Anyway, there still may be some details listed even
1610
                for them:'''
1611
            s = s % len(self.requiredMethodsDic)
1612 1613
            f.write('-' * 70 + '\n')
            f.write(fill(s) + '\n\n')
1614

1615
            mailtoLst = []
1616 1617 1618 1619 1620 1621
            for x in self.upToDateIdLst:
                obj = self.__translDic[x]
                f.write('  ' + obj.classId)
                if obj.note:
                    f.write(' -- ' + obj.note)
                f.write('\n')
1622
                mailtoLst.extend(self.__emails(obj.classId))
1623

1624 1625
            fmail.write('up-to-date\n')
            fmail.write('; '.join(mailtoLst))
1626 1627 1628 1629

        # Write the list of the adapter based classes. The very obsolete
        # translators that derive from TranslatorEnglish are included.
        if self.adaptIdLst:
1630
            s = '''The following translator classes need some maintenance
1631 1632 1633 1634 1635 1636
                (the most obsolete at the end). The other info shows the
                estimation of Doxygen version when the class was last
                updated and number of methods that must be implemented to
                become up-to-date:'''
            f.write('\n' + '-' * 70 + '\n')
            f.write(fill(s) + '\n\n')
1637

1638 1639
            # Find also whether some adapter classes may be removed.
            adaptMinVersion = '9.9.99'
1640

1641
            mailtoLst = []
1642
            numRequired = len(self.requiredMethodsDic)
1643 1644 1645 1646
            for x in self.adaptIdLst:
                obj = self.__translDic[x]
                f.write('  %-30s' % obj.classId)
                f.write('  %-6s' % obj.readableStatus)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1647 1648 1649
                numimpl = len(obj.missingMethods)
                pluralS = ''
                if numimpl > 1: pluralS = 's'
1650 1651 1652
                percent = 100 * numimpl / numRequired
                f.write('\t%2d method%s to implement (%d %%)' % (
                        numimpl, pluralS, percent))
1653 1654 1655
                if obj.note:
                    f.write('\n\tNote: ' + obj.note + '\n')
                f.write('\n')
1656
                mailtoLst.extend(self.__emails(obj.classId)) # to maintainer
1657

1658 1659 1660
                # Check the level of required adapter classes.
                if obj.status != '0.0.00' and obj.status < adaptMinVersion:
                    adaptMinVersion = obj.status
1661 1662 1663

            fmail.write('\n\ntranslator based\n')
            fmail.write('; '.join(mailtoLst))
1664 1665

            # Set the note if some old translator adapters are not needed
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1666
            # any more. Do it only when the script is called without arguments,
1667 1668
            # i.e. all languages were checked against the needed translator
            # adapters.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1669
            if not self.script_argLst:
1670
                to_remove = {}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1671 1672
                for version, adaptClassId in self.adaptMethodsDic.values():
                    if version < adaptMinVersion:
1673
                        to_remove[adaptClassId] = True
1674

1675 1676 1677 1678 1679 1680
                if to_remove:
                    lst = to_remove.keys()
                    lst.sort()
                    plural = len(lst) > 1
                    note = 'Note: The adapter class'
                    if plural: note += 'es'
1681 1682
                    note += ' ' + ', '.join(lst)
                    if not plural:
1683 1684 1685 1686 1687
                        note += ' is'
                    else:
                        note += ' are'
                    note += ' not used and can be removed.'
                    f.write('\n' + fill(note) + '\n')
1688

1689 1690
        # Write the list of the English-based classes.
        if self.EnBasedIdLst:
1691 1692 1693 1694
            s = '''The following translator classes derive directly from the
                TranslatorEnglish. The class identifier has the suffix 'En'
                that says that this is intentional. Usually, there is also
                a non-English based version of the translator for
1695 1696 1697
                the language:'''
            f.write('\n' + '-' * 70 + '\n')
            f.write(fill(s) + '\n\n')
1698

1699 1700 1701 1702 1703 1704 1705
            for x in self.EnBasedIdLst:
                obj = self.__translDic[x]
                f.write('  ' + obj.classId)
                f.write('\timplements %d methods' % len(obj.implementedMethods))
                if obj.note:
                    f.write(' -- ' + obj.note)
                f.write('\n')
1706

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1707 1708 1709 1710 1711 1712
        # Check for not used translator methods and generate warning if found.
        # The check is rather time consuming, so it is not done when report
        # is restricted to explicitly given language identifiers.
        if not self.script_argLst:
            dic = self.__checkForNotUsedTrMethods()
            if dic:
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1713
                s = '''WARNING: The following translator methods are declared
1714 1715 1716
                    in the Translator class but their identifiers do not appear
                    in source files. The situation should be checked. The .cpp
                    files and .h files excluding the '*translator*' files
1717
                    in doxygen/src directory were simply searched for occurrence
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1718
                    of the method identifiers:'''
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1719 1720
                f.write('\n' + '=' * 70 + '\n')
                f.write(fill(s) + '\n\n')
1721

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1722 1723 1724 1725 1726
                keys = dic.keys()
                keys.sort()
                for key in keys:
                    f.write('  ' + dic[key] + '\n')
                f.write('\n')
1727

1728 1729 1730
        # Write the details for the translators.
        f.write('\n' + '=' * 70)
        f.write('\nDetails for translators (classes sorted alphabetically):\n')
1731

1732 1733
        cls = self.__translDic.keys()
        cls.sort()
1734

1735 1736
        for c in cls:
            obj = self.__translDic[c]
1737
            assert(obj.classId != 'Translator')
1738
            obj.report(f)
1739 1740

        # Close the report file and the auxiliary file with e-mails.
1741
        f.close()
1742
        fmail.close()
1743 1744


1745 1746
    def __loadMaintainers(self):
        """Load and process the file with the maintainers.
1747

1748
        Fills the dictionary classId -> [(name, e-mail), ...]."""
1749

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1750
        fname = os.path.join(self.doc_path, self.maintainersFileName)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1751

1752
        # Include the maintainers file to the group of files checked with
1753 1754 1755 1756
        # respect to the modification time.
        tim = os.path.getmtime(fname)
        if tim > self.lastModificationTime:
            self.lastModificationTime = tim
1757

1758
        # Process the content of the maintainers file.
1759
        f = codecs.open(fname, 'r', 'utf-8')
1760 1761 1762 1763 1764 1765 1766 1767
        inside = False  # inside the record for the language
        lineReady = True
        classId = None
        maintainersLst = None
        self.__maintainersDic = {}
        while lineReady:
            line = f.readline()            # next line
            lineReady = line != ''         # when eof, then line == ''
1768

1769
            line = line.strip()            # eof should also behave as separator
1770
            if line != u'' and line[0] == u'%':    # skip the comment line
1771 1772
                continue

1773
            if not inside:                 # if outside of the record
1774
                if line != u'':            # should be language identifier
1775 1776 1777
                    classId = line
                    maintainersLst = []
                    inside = True
1778
                # Otherwise skip empty line that do not act as separator.
1779 1780

            else:                          # if inside the record
1781
                if line == u'':            # separator found
1782 1783 1784 1785 1786
                    inside = False
                else:
                    # If it is the first maintainer, create the empty list.
                    if not self.__maintainersDic.has_key(classId):
                        self.__maintainersDic[classId] = []
1787

1788
                    # Split the information about the maintainer and append
1789 1790 1791
                    # the tuple. The address may be prefixed '[unreachable]'
                    # or whatever '[xxx]'. This will be processed later.
                    lst = line.split(u':', 1)
1792 1793 1794
                    assert(len(lst) == 2)
                    t = (lst[0].strip(), lst[1].strip())
                    self.__maintainersDic[classId].append(t)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1795
        f.close()
1796

1797

1798 1799 1800
    def generateLanguageDoc(self):
        """Checks the modtime of files and generates language.doc."""
        self.__loadMaintainers()
1801

1802 1803 1804
        # Check the last modification time of the template file. It is the
        # last file from the group that decide whether the documentation
        # should or should not be generated.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1805
        fTplName = os.path.join(self.doc_path, self.languageTplFileName)
1806 1807 1808 1809
        tim = os.path.getmtime(fTplName)
        if tim > self.lastModificationTime:
            self.lastModificationTime = tim

1810 1811
        # If the generated documentation exists and is newer than any of
        # the source files from the group, do not generate it and quit
1812 1813
        # quietly.
        fDocName = os.path.join(self.doc_path, self.languageDocFileName)
1814
        if os.path.isfile(fDocName):
1815 1816
            if os.path.getmtime(fDocName) > self.lastModificationTime:
                return
1817

1818 1819 1820 1821 1822
        # The document or does not exist or is older than some of the
        # sources. It must be generated again.
        #
        # Read the template of the documentation, and remove the first
        # attention lines.
1823 1824
        f = codecs.open(fTplName, 'r', 'utf-8')
        doctpl = f.read()
1825 1826
        f.close()

1827 1828 1829 1830
        pos = doctpl.find(u'/***')
        assert pos != -1
        doctpl = doctpl[pos:]

1831
        # Fill the tplDic by symbols that will be inserted into the
1832 1833
        # document template.
        tplDic = {}
1834

1835
        s = u'Do not edit this file. It was generated by the %s script.' % self.script_name
1836
        tplDic['editnote'] = s
1837

1838
        tplDic['doxVersion'] = self.doxVersion
1839
        tplDic['supportedLangReadableStr'] = self.supportedLangReadableStr
1840 1841
        tplDic['translatorReportFileName'] = self.translatorReportFileName

1842 1843 1844
        ahref = u'<a href="../doc/' + self.translatorReportFileName
        ahref += u'"\n><code>doxygen/doc/'  + self.translatorReportFileName
        ahref += u'</code></a>'
1845 1846
        tplDic['translatorReportLink'] = ahref
        tplDic['numLangStr'] = str(self.numLang)
1847

1848
        # Define templates for HTML table parts of the documentation.
1849
        htmlTableTpl = u'''\
1850
            \\htmlonly
1851
            <table align="center" cellspacing="0" cellpadding="0" border="0">
1852 1853
            <tr bgcolor="#000000">
            <td>
1854
              <table cellspacing="1" cellpadding="2" border="0">
1855
              <tr bgcolor="#4040c0">
1856 1857 1858 1859 1860
              <td ><b><font size="+1" color="#ffffff"> Language </font></b></td>
              <td ><b><font size="+1" color="#ffffff"> Maintainer </font></b></td>
              <td ><b><font size="+1" color="#ffffff"> Contact address </font>
                      <font size="-2" color="#ffffff">(replace the at and dot)</font></b></td>
              <td ><b><font size="+1" color="#ffffff"> Status </font></b></td>
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
              </tr>
              <!-- table content begin -->
            %s
              <!-- table content end -->
              </table>
            </td>
            </tr>
            </table>
            \\endhtmlonly
            '''
1871
        htmlTableTpl = dedent(htmlTableTpl)
1872 1873
        htmlTrTpl = u'\n  <tr bgcolor="#ffffff">%s\n  </tr>'
        htmlTdTpl = u'\n    <td>%s</td>'
1874 1875 1876 1877 1878 1879 1880 1881

        # Loop through transl objects in the order of sorted readable names
        # and add generate the content of the HTML table.
        trlst = []
        for name, obj in self.langLst:
            # Fill the table data elements for one row. The first element
            # contains the readable name of the language.
            lst = [ htmlTdTpl % obj.langReadable ]
1882 1883

            # The next two elements contain the list of maintainers
1884
            # and the list of their mangled e-mails. For English-based
1885
            # translators that are coupled with the non-English based,
1886
            # insert the 'see' note.
1887 1888
            mm = None  # init -- maintainer
            ee = None  # init -- e-mail address
1889 1890 1891
            if obj.status == 'En':
                # Check whether there is the coupled non-English.
                classId = obj.classId[:-2]
1892
                if classId in self.__translDic:
1893
                    lang = self.__translDic[classId].langReadable
1894 1895
                    mm = u'see the %s language' % lang
                    ee = u'&nbsp;'
1896

1897 1898 1899
            if not mm and obj.classId in self.__maintainersDic:
                # Build a string of names separated by the HTML break element.
                # Special notes used instead of names are highlighted.
1900
                lm = []
1901 1902 1903 1904 1905 1906
                for maintainer in self.__maintainersDic[obj.classId]:
                    name = maintainer[0]
                    if name.startswith(u'--'):
                        name = u'<span style="color: red; background-color: yellow">'\
                               + name + u'</span>'
                    lm.append(name)
1907
                mm = u'<br/>'.join(lm)
1908 1909

                # The marked adresses (they start with the mark '[unreachable]',
1910 1911 1912
                # '[resigned]', whatever '[xxx]') will not be displayed at all.
                # Only the mark will be used instead.
                rexMark = re.compile(ur'(?P<mark>\[.*?\])')
1913
                le = []
1914 1915 1916 1917
                for maintainer in self.__maintainersDic[obj.classId]:
                    address = maintainer[1]
                    m = rexMark.search(address)
                    if m is not None:
1918
                        address = u'<span style="color: brown">'\
1919
                                  + m.group(u'mark') + u'</span>'
1920
                    le.append(address)
1921
                ee = u'<br/>'.join(le)
1922

1923 1924 1925
            # Append the maintainer and e-mail elements.
            lst.append(htmlTdTpl % mm)
            lst.append(htmlTdTpl % ee)
1926

1927 1928
            # The last element contains the readable form of the status.
            lst.append(htmlTdTpl % obj.readableStatus)
1929 1930

            # Join the table data to one table row.
1931
            trlst.append(htmlTrTpl % (''.join(lst)))
1932

1933 1934
        # Join the table rows and insert into the template.
        htmlTable = htmlTableTpl % (''.join(trlst))
1935

1936
        # Define templates for LaTeX table parts of the documentation.
1937
        latexTableTpl = ur'''
1938
            \latexonly
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1939 1940
            \footnotesize
            \begin{longtable}{|l|l|l|l|}
1941
              \hline
1942 1943 1944 1945
              {\bf Language} & {\bf Maintainer} & {\bf Contact address} & {\bf Status} \\
              \hline
            %s
              \hline
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1946 1947
            \end{longtable}
            \normalsize
1948 1949
            \endlatexonly
            '''
1950
        latexTableTpl = dedent(latexTableTpl)
1951
        latexLineTpl = u'\n' + r'  %s & %s & {\tt\tiny %s} & %s \\'
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970

        # Loop through transl objects in the order of sorted readable names
        # and add generate the content of the LaTeX table.
        trlst = []
        for name, obj in self.langLst:
            # For LaTeX, more maintainers for the same language are
            # placed on separate rows in the table.  The line separator
            # in the table is placed explicitly above the first
            # maintainer. Prepare the arguments for the LaTeX row template.
            maintainers = []
            if self.__maintainersDic.has_key(obj.classId):
                maintainers = self.__maintainersDic[obj.classId]

            lang = obj.langReadable
            maintainer = None  # init
            email = None       # init
            if obj.status == 'En':
                # Check whether there is the coupled non-English.
                classId = obj.classId[:-2]
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1971
                if classId in self.__translDic:
1972
                    langNE = self.__translDic[classId].langReadable
1973 1974
                    maintainer = u'see the %s language' % langNE
                    email = u'~'
1975

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1976
            if not maintainer and (obj.classId in self.__maintainersDic):
1977
                lm = [ m[0] for m in self.__maintainersDic[obj.classId] ]
1978 1979 1980 1981 1982 1983 1984
                maintainer = maintainers[0][0]
                email = maintainers[0][1]

            status = obj.readableStatus

            # Use the template to produce the line of the table and insert
            # the hline plus the constructed line into the table content.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1985
            # The underscore character must be escaped.
1986
            trlst.append(u'\n  \\hline')
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1987 1988 1989
            s = latexLineTpl % (lang, maintainer, email, status)
            s = s.replace(u'_', u'\\_')
            trlst.append(s)
1990

1991 1992
            # List the other maintainers for the language. Do not set
            # lang and status for them.
1993 1994
            lang = u'~'
            status = u'~'
1995 1996 1997
            for m in maintainers[1:]:
                maintainer = m[0]
                email = m[1]
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1998 1999 2000
                s = latexLineTpl % (lang, maintainer, email, status)
                s = s.replace(u'_', u'\\_')
                trlst.append(s)
2001

2002
        # Join the table lines and insert into the template.
2003
        latexTable = latexTableTpl % (u''.join(trlst))
2004

2005
        # Put the HTML and LaTeX parts together and define the dic item.
2006
        tplDic['informationTable'] = htmlTable + u'\n' + latexTable
2007 2008

        # Insert the symbols into the document template and write it down.
2009
        f = codecs.open(fDocName, 'w', 'utf-8')
2010 2011
        f.write(doctpl % tplDic)
        f.close()
2012

2013
if __name__ == '__main__':
2014

2015 2016 2017
    # Create the manager, build the transl objects, and parse the related
    # sources.
    trMan = TrManager()
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2018

2019 2020
    # Generate the language.doc.
    trMan.generateLanguageDoc()
2021

2022 2023
    # Generate the translator report.
    trMan.generateTranslatorReport()