2 from latexparser import latexparser, TexCmd
3 import distutils.dep_util
5 import cPickle as pickle
8 from qfile import QOpen
9 from string import Template
11 # useful things for pyparsing
13 def listify(s, loc, toks):
15 x.setParseAction(listify)
18 def listify(s, loc, toks):
20 x.setParseAction(listify)
23 return returnList(pp.Optional(word + pp.ZeroOrMore(pp.Suppress(',') + word)))
25 return pp.Suppress(pp.Literal(s))
29 python_api = pythonapi.reader("../../interfaces/python/api")
33 def __init__(self, filename, language, abspath):
34 assert language in ['py', 'c', 'cpp']
35 self.language = language
37 self.abspath = abspath
38 os.path.abspath(os.path.dirname(filename))
40 self.f_index = QOpen(os.path.join(self.language, filename), 'wt')
48 self.errors = open('errors.%s' % language, 'wt')
49 self.unhandled_commands = set()
51 self.function_props = {}
52 self.covered = set() # covered functions, used for error report
56 self.freshline = len(s) > 0 and (s[-1] == '\n')
57 self.f.write(s.replace('\n', '\n' + self.indent * " "))
59 def appendspace(self):
60 """ append a space to the output - if we're not at the start of a line """
61 if not self.freshline:
65 if (len(s) > 1) and (s[0] == '$' and s[-1] == '$') and self.state != 'math':
66 s = ":math:`%s`" % s[1:-1].strip()
67 elif self.state != 'math':
69 if len(s) > 0 and s[-1] == '\n':
71 if self.state == 'fpreamble':
77 if self.state == 'math':
89 meth = self.cmd_gomath
91 cname = "cmd_" + c.cmd
92 meth = getattr(self, cname, self.unrecognized_cmd)
95 def cmd_gomath(self, c):
97 print >>self, "\n\n.. math::"
101 def cmd_chapter(self, c):
102 filename = str(c.params[0]).lower().replace(' ', '_').replace('/','_')
103 self.f_index.write(" %s\n" % filename)
104 self.f_chapter = QOpen(os.path.join(self.language, filename + '.rst'), 'wt')
105 self.f_section = None
106 self.f = self.f_chapter
108 title = str(c.params[0])
109 print >>self, '*' * len(title)
111 print >>self, '*' * len(title)
113 self.chapter_intoc = False
115 def cmd_section(self, c):
116 filename = str(c.params[0]).lower().replace(' ', '_').replace('/','_')
117 if not self.chapter_intoc:
118 self.chapter_intoc = True
119 print >>self.f_chapter
120 print >>self.f_chapter, '.. toctree::'
121 print >>self.f_chapter, ' :maxdepth: 2'
122 print >>self.f_chapter
123 self.f_chapter.write(" %s\n" % filename)
124 self.f_section = QOpen(os.path.join(self.language, filename + '.rst'), 'wt')
125 self.f = self.f_section
127 title = self.render(c.params[0].str)
129 print >>self, '=' * len(title)
131 print >>self, '.. highlight:: %s' % {'c': 'c', 'cpp': 'cpp', 'py': 'python'}[self.language]
134 def cmd_subsection(self, c):
136 print >>self, str(c.params[0])
137 print >>self, '-' * len(str(c.params[0]))
139 self.function_props = {}
141 def cmd_includegraphics(self, c):
142 filename = os.path.join('..', '..', str(c.params[0]))
143 print >>self, "\n\n.. image:: %s\n\n" % filename
145 def cmd_cvCppCross(self, c):
146 self.write(":ref:`%s`" % str(c.params[0]))
148 def cmd_cvCPyCross(self, c):
149 self.write(":ref:`%s`" % str(c.params[0]))
151 def cmd_cross(self, c):
152 self.write(":ref:`%s`" % str(c.params[0]))
154 def cmd_cvCross(self, c):
155 self.write(":ref:`%s`" % str(c.params[0]))
157 def cmd_cvclass(self, c):
160 nm = self.render(list(c.params[0].str))
161 print >>self, "\n.. index:: %s\n" % nm
162 print >>self, ".. _%s:\n" % nm
164 print >>self, '-' * len(nm)
166 if self.language == 'py':
167 print >>self, ".. class:: " + nm + "\n"
169 print >>self, ".. ctype:: " + nm + "\n"
174 def addtag(self, nm, c):
176 self.report_error(c, "empty name")
177 self.tags[nm] = "%s\t%s\t%d" % (nm, os.path.join(os.getcwd(), c.filename), c.lineno)
179 def cmd_cvfunc(self, c):
180 self.cmd_cvCPyFunc(c)
182 def cmd_cvCPyFunc(self, c):
184 nm = self.render(c.params[0].str)
185 print >>self, "\n.. index:: %s\n" % nm
186 print >>self, ".. _%s:\n" % nm
188 print >>self, '-' * len(nm)
190 self.state = 'fpreamble'
191 if self.description != "":
192 self.report_error(c, "overflow - preceding cvfunc (starting %s) not terminated?" % repr(self.description[:30]))
193 self.description = ""
196 self.function_props = {'name' : nm}
199 def cmd_cvCppFunc(self, c):
201 nm = self.render(c.params[0].str)
202 print >>self, "\n.. index:: %s\n" % nm
203 print >>self, ".. _%s:\n" % nm
205 print >>self, '-' * len(nm)
207 self.state = 'fpreamble'
208 if self.description != "":
209 self.report_error(c, "overflow - preceding cvfunc (starting %s) not terminated?" % repr(self.description[:30]))
210 self.description = ""
213 self.function_props = {'name' : nm}
216 def cmd_cvdefC(self, c):
217 if self.language != 'c':
219 s = str(c.params[0]).replace('\\_', '_')
220 s = s.replace('\\par', '')
221 s = s.replace('\n', ' ')
222 s = s.replace(';', '')
224 for proto in s.split('\\newline'):
225 if proto.strip() != "":
226 print >>self, "\n\n.. cfunction:: " + proto.strip() + "\n"
227 # print >>self, "=", repr(c.params[0].str)
228 print >>self, ' ' + self.description
229 self.description = ""
232 self.function_props['defpy'] = s
234 def cmd_cvdefCpp(self, c):
235 if self.language != 'cpp':
237 s = str(c.params[0]).replace('\\_', '_')
238 s = s.replace('\\par', '')
239 s = s.replace('\n', ' ')
240 s = s.replace(';', '')
242 for proto in s.split('\\newline'):
243 if proto.strip() != "":
244 print >>self, "\n\n.. cfunction:: " + proto.strip() + "\n"
245 # print >>self, "=", repr(c.params[0].str)
246 if self.description != "":
247 print >>self, ' ' + self.description
249 self.report_error(c, 'empty description')
250 self.description = ""
253 self.function_props['defpy'] = s
255 def cmd_cvdefPy(self, c):
256 if self.language != 'py':
258 s = str(c.params[0]).replace('\\_', '_')
260 print >>self, ".. function:: " + s + "\n"
261 # print >>self, "=", repr(c.params[0].str)
262 print >>self, ' ' + self.description
264 self.description = ""
266 self.function_props['defpy'] = s
268 pp.ParserElement.setDefaultWhitespaceChars(" \n\t")
270 ident = pp.Word(pp.alphanums + "_.+-")
271 ident_or_tuple = ident | (sl('(') + CommaList(ident) + sl(')'))
272 initializer = ident_or_tuple
273 arg = returnList(ident + pp.Optional(sl('=') + initializer))
275 decl = ident + sl('(') + CommaList(arg) + sl(')') + sl("->") + ident_or_tuple + pp.StringEnd()
278 l = decl.parseString(s)
279 if str(l[0]) != self.function_props['name']:
280 self.report_error(c, 'Decl "%s" does not match function name "%s"' % (str(l[0]), self.function_props['name']))
281 self.function_props['signature'] = l
282 if l[0] in python_api:
283 (ins, outs) = python_api[l[0]]
284 ins = [a for a in ins if not 'O' in a.flags]
286 outs = outs.split(',')
287 if len(ins) != len(l[1]):
288 self.report_error(c, "function %s documented arity %d, code arity %d" % (l[0], len(l[1]), len(ins)))
291 self.report_error(c, "function %s documented None, but code has %s" % (l[0], l[2]))
293 if isinstance(l[2], str):
297 if len(outs) != len(doc_outs):
298 self.report_error(c, "function %s output documented tuple %d, code %d" % (l[0], len(outs), len(doc_outs)))
300 # self.report_error(c, "function %s documented but not found in code" % l[0])
302 except pp.ParseException, pe:
303 self.report_error(c, str(pe))
307 def report_error(self, c, msg):
308 print >>self.errors, "%s:%d: [%s] Error %s" % (c.filename, c.lineno, self.language, msg)
310 def cmd_begin(self, c):
311 if len(c.params) == 0:
312 self.report_error(c, "Malformed begin")
316 self.envstack.append((s, (c.filename, c.lineno)))
317 if s == 'description':
318 if self.language == 'py' and 'name' in self.function_props and not 'defpy' in self.function_props:
319 self.report_error(c, "No cvdefPy for function %s" % self.function_props['name'])
321 elif s == 'lstlisting':
322 # Set indent to zero while collecting code; so later write will not double-indent
323 self.saved_f = self.f
324 self.saved_indent = self.indent
325 self.f = StringIO.StringIO()
327 elif s in ['itemize', 'enumerate']:
330 self.f = StringIO.StringIO()
334 def cmd_item(self, c):
335 if len(self.ee()) == 0:
336 self.report_error(c, "item without environment")
339 markup = {'itemize' : '*', 'enumerate' : '#.', 'description' : '*'}[self.ee()[-1]]
341 markup += " " + self.render([c.args[0].str])
342 if len(c.params) > 0:
343 markup += " " + self.render(c.params[0].str)
344 self.write("\n\n" + markup)
347 def cmd_end(self, c):
348 if len(c.params) != 1:
349 self.report_error(c, "Malformed end")
351 if len(self.envstack) == 0:
352 self.report_error(c, "end with no env")
356 if self.envstack == []:
357 print "Cannot pop at", (c.filename, c.lineno)
358 if self.envstack[-1][0] != s:
359 self.report_error(c, "end{%s} does not match current stack %s" % (s, repr(self.envstack)))
361 if s == 'description':
364 self.function_props['done'] = True
365 elif s in ['itemize', 'enumerate']:
368 tabletxt = self.f.getvalue()
369 self.f = self.f_section
370 self.f.write(self.handle_table(tabletxt))
371 elif s == 'lstlisting':
372 listing = self.f.getvalue()
374 self.f = self.saved_f
375 self.indent = self.saved_indent
377 if self.language == 'py':
378 ckeys = ['#define', 'void', '#include', ';\n']
379 found = [repr(k) for k in ckeys if k in listing]
381 self.report_error(c, 'listing is probably C, found %s' % ",".join(found))
382 if (self.language == 'py') and ('>>>' in listing):
383 print >>self, "\n.. doctest::\n"
385 print >>self, "\n::\n"
392 print >>self, ".." # otherwise a following :param: gets treated as more listing
393 elif s == 'document':
398 def cmd_label(self, c):
401 def cmd_lstinputlisting(self, c):
403 print >>self.f, ".. include:: %s" % os.path.normpath(os.path.join(self.abspath, s))
404 print >>self.f, " :literal:"
408 def cmd_cvC(self, c):
409 self.do_conditional(['c'], c)
410 def cmd_cvCpp(self, c):
411 self.do_conditional(['cpp'], c)
412 def cmd_cvPy(self, c):
413 self.do_conditional(['py'], c)
414 def cmd_cvCPy(self, c):
415 self.do_conditional(['c', 'py'], c)
416 def do_conditional(self, langs, c):
417 if self.language in langs:
418 self.doL(c.params[0].str, False)
421 """ return L rendered as a string """
423 self.f = StringIO.StringIO()
425 if isinstance(x, TexCmd):
429 r = self.f.getvalue()
433 def cmd_cvarg(self, c):
434 if len(c.params) != 2:
435 self.report_error(c, "Malformed cvarg")
438 if self.state == 'class':
439 nm = self.render(c.params[0].str)
441 print >>self, "\n\n.. method:: %s\n\n" % nm
443 print >>self, "\n\n.. attribute:: %s\n\n" % nm
446 self.doL(c.params[1].str, False)
450 is_func_arg = (e == ['description']) and (not 'done' in self.function_props)
452 nm = self.render(c.params[0].str)
453 print >>self, '\n:param %s: ' % nm,
454 type = None # Try to figure out the argument type
455 # For now, multiple args get a pass
456 if (self.language == 'py') and ('signature' in self.function_props) and (not ',' in nm):
457 sig = self.function_props['signature']
458 argnames = [a[0] for a in sig[1]]
459 if isinstance(sig[2], str):
462 resnames = list(sig[2])
463 if not nm in argnames + resnames:
464 self.report_error(c, "Argument %s is not mentioned in signature (%s) (%s)" % (nm, ", ".join(argnames), ", ".join(resnames)))
466 api = python_api.get(self.function_props['name'], None)
469 adict = dict([(a.nm, a) for a in ins])
470 arg = adict.get(nm, None)
474 self.report_error(c, 'cannot find arg %s in code' % nm)
475 elif len(e) > 0 and e[-1] == 'description':
476 print >>self, '\n* **%s** ' % self.render(c.params[0].str),
478 self.report_error(c, "unexpected env (%s) for cvarg" % ",".join(e))
480 self.doL(c.params[1].str, False)
483 if is_func_arg and type:
484 type = type.replace('*', '')
486 "ints" : "sequence of int",
487 "floats" : "sequence of int",
488 "IplImages" : "sequence of :class:`IplImage`",
493 "cvarrseq" : ":class:`CvArr` or :class:`CvSeq`",
494 "CvPoint2D32fs" : "sequence of (float, float)",
495 "pts_npts_contours" : "list of lists of (x,y) pairs",
496 "CvSeqOfCvSURFPoint" : ":class:`CvSeq` of :class:`CvSURFPoint`",
497 "CvSeqOfCvSURFDescriptor" : ":class:`CvSeq` of list of float",
498 "cvpoint2d32f_count" : "int",
500 print >>self, "\n:type %s: %s" % (nm, translate.get(type, ':class:`%s`' % type))
502 def cmd_genc(self, c): pass
503 def cmd_genpy(self, c): pass
504 def cmd_author(self, c): pass
505 def cmd_date(self, c): pass
506 def cmd_def(self, c): pass
507 def cmd_documentclass(self, c): pass
508 def cmd_maketitle(self, c): pass
509 def cmd_newcommand(self, c): pass
510 def cmd_newline(self, c): pass
511 def cmd_setcounter(self, c): pass
512 def cmd_tableofcontents(self, c): pass
513 def cmd_targetlang(self, c): pass
514 def cmd_usepackage(self, c): pass
515 def cmd_title(self, c): pass
516 def cmd_par(self, c): pass
517 def cmd_hline(self, c):
518 print >>self, "\\hline"
520 def cmd_cite(self, c):
521 self.write("[%s]_" % str(c.params[0]))
523 def cmd_href(self, c):
524 if len(c.params) == 2:
525 self.write("`%s <%s>`_" % (str(c.params[1]), self.render(c.params[0].str)))
527 self.report_error(c, "href should have two params")
529 def cmd_url(self, c):
530 self.write(str(c.params[0]))
532 def cmd_emph(self, c):
533 self.write("*" + self.render(c.params[0].str) + "*")
535 def cmd_textit(self, c):
536 self.write("*" + self.render(c.params[0].str) + "*")
538 def cmd_textbf(self, c):
539 self.write("**" + self.render(c.params[0].str) + "**")
541 def cmd_texttt(self, c):
542 self.write("``" + self.render(c.params[0].str) + "``")
544 def default_cmd(self, c):
545 if self.f == self.f_section:
548 def unrecognized_cmd(self, c):
549 # if writing the index or chapter heading, anything goes
550 if not self.f in [self.f_index, self.f_chapter]:
552 if (not 'lstlisting' in self.ee()) and (not c.cmd in "#{}%&*\\_"):
553 if not c.cmd in self.unhandled_commands:
554 self.report_error(c, 'unhandled command %s' % c.cmd)
555 self.unhandled_commands.add(c.cmd)
557 def doL(self, L, newlines = True):
560 if isinstance(x, TexCmd):
563 if 'lstlisting' in self.ee() or not newlines:
566 self.doplain(x.lstrip())
569 if self.state in ['math'] or not newlines:
572 if not 'lstlisting' in self.ee():
575 def handle_table(self, s):
576 oneline = s.replace('\n', ' ').strip()
577 rows = [r.strip() for r in oneline.split('\\hline')]
581 cols = [c.strip() for c in r.split('&')]
583 widths = [max([len(r[i]) for r in tab]) for i in range(len(tab[0]))]
585 st = "" # Sphinx table
588 sep = "+" + "+".join(["-" * w for w in widths]) + "+"
591 st += "|" + "|".join([c.center(w) for (c, w) in zip(r, widths)]) + "|" + '\n'
594 st = '.. table::\n\n'
595 sep = " ".join(["=" * w for w in widths])
596 st += ' ' + sep + '\n'
597 for y,r in enumerate(tab):
598 st += ' ' + " ".join([c.ljust(w) for (c, w) in zip(r, widths)]) + '\n'
600 st += ' ' + sep + '\n'
601 st += ' ' + sep + '\n'
605 """ Return tags of the envstack. envstack[0] is 'document', so skip it """
606 return [n for (n,_) in self.envstack[1:]]
613 if self.envstack != []:
614 print >>self.errors, "Error envstack not empty at end of doc: " + repr(self.envstack)
615 print >>self.errors, "Unrecognized commands:"
616 for c in sorted(self.unhandled_commands):
617 print >>self.errors, "\n " + c
619 if self.language == 'py':
620 print >>self.errors, "The following functions are undocumented"
621 for f in sorted(set(python_api) - self.covered):
622 print >>self.errors, ' ', f
624 print >>self.f_index, " bibliography"
625 print >>self.f_index, """
634 # Quick and dirty bibtex parser
636 def parseBib(filename, language):
637 pp.ParserElement.setDefaultWhitespaceChars(" \n\t")
638 entry = returnList(pp.Word('@', pp.alphanums) + sl('{') +
639 pp.Word(pp.alphanums + "_") + sl(',') +
640 CommaList(returnTuple(pp.Word(pp.alphanums) + sl('=') + pp.QuotedString('{', endQuoteChar = '}'))) +
641 pp.Suppress(pp.Optional(',')) +
643 r = (pp.ZeroOrMore(entry) | pp.Suppress('#' + pp.ZeroOrMore(pp.CharsNotIn('\n'))) + pp.StringEnd()).parseFile(filename)
645 bibliography = QOpen(os.path.join(language, "bibliography.rst"), 'wt')
646 print >>bibliography, "Bibliography"
647 print >>bibliography, "============"
650 for _,e in sorted([(str(x[1]), x) for x in r]):
651 (etype, tag, attrs) = str(e[0][1:]), str(e[1]), dict([(str(a), str(b)) for (a,b) in e[2]])
654 'article' : '$author, "$title". $journal $volume $number, pp $pages ($year)',
655 'inproceedings' : '$author "$title", $booktitle, $year',
656 'misc' : '$author "$title", $year',
657 'techreport' : '$author "$title", $edition, $edition ($year)',
659 if etype in representations:
661 print >>bibliography, tag
662 print >>bibliography, "^" * len(tag)
665 print >>bibliography, ".. [%s] %s" % (tag, Template(representations[etype]).safe_substitute(attrs))
670 fulldoc = latexparser(sys.argv[1])
672 abspath = os.path.abspath(os.path.dirname(sys.argv[1]))
674 raw = open('raw.full', 'w')
679 # Filter on target language
680 def preprocess_conditionals(fd, conditionals):
684 if isinstance(x, TexCmd):
686 loc = (x.filename, x.lineno)
687 if ll.startswith("if"):
688 # print " " * len(ifstack), '{', loc
689 ifstack.append((conditionals.get(ll[2:], False), loc))
690 elif ll.startswith("else"):
691 ifstack[-1] = (not ifstack[-1][0], ifstack[-1][1])
692 elif ll.startswith("fi"):
694 # print " " * len(ifstack), '}', loc
695 elif not False in [p for (p,_) in ifstack]:
698 if not False in [p for (p,_) in ifstack]:
701 print "unterminated if", ifstack
706 for language in sys.argv[2:]:
707 doc = preprocess_conditionals(fulldoc, {
709 'Python' : language=='py',
710 'Py' : language=='py',
711 'CPy' : (language=='py' or language == 'c'),
712 'Cpp' : language=='cpp',
715 raw = open('raw.%s' % language, 'w')
719 sr = SphinxWriter('index.rst', language, abspath)
721 OpenCV |version| %s Reference
722 =================================
724 The OpenCV Wiki is here: http://opencv.willowgarage.com/
731 """ % {'c': 'C', 'cpp': 'C++', 'py': 'Python'}[language]
734 parseBib('../opencv.bib', language)
735 tags.update(sr.get_tags())
736 open('TAGS', 'w').write("\n".join(sorted(tags.values())) + "\n")