1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
|
#
# FILE $Id: ParseCollect.py,v 1.8 1996/09/06 09:58:44 omfadmin Exp $
#
# DESCRIPTION Collect doctrings from Python modules, and generate Manual page.
#
# AUTHOR SEISY/LKSB Daniel Larsson
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of ABB Industrial Systems
# not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior permission.
#
# ABB INDUSTRIAL SYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS, IN NO EVENT SHALL ABB INDUSTRIAL SYSTEMS BE LIABLE
# FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Copyright (C) ABB Industrial Systems AB, 1996
# Unpublished work. All Rights Reserved.
#
# HISTORY: $Log: /Gendoc/ParseCollect.py $
#
# 1 98-04-01 13:15 Daniel
# Revision 1.8 1996/09/06 09:58:44 omfadmin
# Replaced setext markup with structured text markup.
#
# Revision 1.7 1996/08/26 20:37:17 omfadmin
# Removed unnecessary code.
#
# Revision 1.6 1996/07/11 16:45:59 omfadmin
# Moved docstring parsing code to the new docutil module.
#
# Revision 1.5 1996/07/10 03:14:27 omfadmin
# Changed definition of __version__.
#
# Revision 1.4 1996/07/08 05:17:55 omfadmin
# Fixed handling of bullet lists.
# The hook method module() is now called file_input since
# Fred Drake's changes.
#
# Revision 1.3 1996/06/24 09:54:16 omfadmin
# Added support for setext style hyperlinks.
# Fixed bug in _stripleadingtabs (Removed internal whitespace too, sometimes!).
# Previously I forgot doing setext substitution and paragraph splitting
# on function docstrings. That has been corrected.
#
# Revision 1.2 1996/06/21 00:04:01 omfadmin
# - Improved docstrings
# - Only include modules imported at global scope
# - Added list of global functions in synopsis for module
# - Optionally skip ~internal~ names (beginning with single '_')
#
# Revision 1.1 1996/06/13 17:52:11 omfadmin
# Initial revision
#
#
"""Generates manual pages from Python source code.
This module defines classes that traverse a Python source
file and generates manual pages in an abstract form. These
pages can then be rendered in various formats.
"""
__version__ = "$Revision: 1 $"
import regex
import string
import ASTWalker
import symbol
import ManualPage
import docutil
VERBOSE = 0
def message(string, level=1):
if VERBOSE >= level:
print string
class ScopeTracker(ASTWalker.ASTWalker):
"""Keeps track of the declaration scope.
To figure out to what class/function a function belongs,
this AST walker keeps a stack of declarations while
trodding along the tree. The stack is available
as ~self.decl_stack~, where each element is a list
[node, level].
In subclasses, be sure to call this class' ~classdef~
and ~funcdef~ methods to push them on the stack."""
def __init__(self, node_builder=None):
ASTWalker.ASTWalker.__init__(self, node_builder)
# Python indent level is used to figure out
# when a class declaration ends, etc.
self.indent = 0
self.decl_stack = []
def is_global(self):
"""Returns true if we are at the global scope"""
return len(self.decl_stack) == 0
def top_declaration(self):
"""Return topmost declaration."""
return self.decl_stack[-1]
# Overridden methods from base class
def classdef(self, ref_classdef):
"""Override this to handle class definition nodes."""
# Push class and indentation level on declaration stack
self.decl_stack.append([ref_classdef, self.indent])
message(' '*self.indent + ref_classdef.name, 2)
def funcdef(self, ref_funcdef):
"""Override this to handle function definition nodes."""
# Push function and indentation level on declaration stack
self.decl_stack.append([ref_funcdef, self.indent])
message(' '*self.indent + ref_funcdef.name, 2)
def indent(self, ref_indent):
"""Override this to handle indent nodes."""
message(' '*self.indent + '>', 2)
self.indent = self.indent+1
def dedent(self, ref_dedent):
"""Override this to handle dedent nodes."""
self.indent = self.indent-1
message(' '*self.indent + '<', 2)
# Check if topmost declaration on stack is finished
if len(self.decl_stack) > 0 and self.decl_stack[-1][1] == self.indent:
top, self.decl_stack = self.decl_stack[-1], self.decl_stack[:-1]
return top
else:
return None
def _manpage_init(manpage, type_str, name, doc, marker=None):
title = type_str + ' ' + name
if doc:
doc = eval(doc) # doc is a string containing a string!
oneliner, doc = docutil.split_doc(doc)
if oneliner:
title = title + ' - ' + oneliner
args = (title, name+', '+type_str,)
if marker:
args = args + (marker,)
apply(manpage.title, args)
synopsis = manpage.section('SYNOPSIS')
# Write module description
description = manpage.section('DESCRIPTION')
if doc:
docutil.docregex_parse(manpage, description, doc)
see_also = manpage.section('SEE ALSO')
class ParseCollector(ScopeTracker):
"""Collect docstrings from parse tree.
Traverses a module's abstract syntax tree (AST), collects docstrings,
and generates manual pages. To use this class you must have
Fred Drake's parser module built into your python interpreter.
To get the AST of a module, do something like this:
> import parser
> module = open(module_file).read()
> ast_tuple = parser.ast2tuple(parser.suite(module))
To generate a set of manual pages, you create a ~ParseCollector~
and let it walk the tree:
> module_name = splitfields(basename(module_file), '.')[0]
> pc = ParseCollector(module_name)
> manpages = pc.walk(ast_tuple)
To generate manual pages, create a formatter for a particular
output format:
> import ManFormatter
> html = ManFormatter.HTMLFormatter()
> for manpage in manpages:
> text = manpage.render(html)
> file = open(manpage.name() + html.file_ext, 'w')
> file.write(text)
> file.close()
> # Voila!
"""
def __init__(self, module_name, skip_internal=1, node_builder=None):
"""Constructor.
~module_name~ is the python module name to parse.
If ~skip_internal~ is set, names beginning with a single '_'
are skipped (conventionally they are treated as non-public
objects).
_ADVANCED_: ~node_builder~ allows you to use a custom node builder
when traversing the AST. I have no idea why you would want to
do that ;-)."""
ScopeTracker.__init__(self, node_builder)
# Python indent level is used to figure out
# when a class declaration ends, etc.
self.indent = 0
self.name = module_name
self.skip_internal = skip_internal
def walk(self, ast):
"""Walk the ast and generate manual pages.
Walks ~ast~ and generates a list of manual pages, one
for the module, and one for each class in the module."""
self.manpage = ManualPage.ManualPage(self.name)
self.classes = []
self.functions = []
self.see_also = []
self.manpgs = [self.manpage]
ASTWalker.ASTWalker.walk(self, ast)
synopsis = self.manpage.section('SYNOPSIS')
if self.classes:
code = '# Classes\n' + string.joinfields(self.classes, '\n')
self.manpage.code(code, synopsis)
if self.functions:
code = '# Functions\n' + string.joinfields(self.functions, '\n')
self.manpage.code(code, synopsis)
if self.see_also:
# Get reference to the "SEE ALSO" section
see_also = self.manpage.section('SEE ALSO')
# Spit out the text into the "SEE ALSO" section
list = map(self.manpage.reference, self.see_also)
list = string.joinfields(list, ', ')
self.manpage.paragraph(list, see_also)
return self.manpgs
def render(self, formatter):
"""Render manual pages.
~formatter~ is an instance (or a sequence of instances)
capable of formatting a ManualPage into some format.
Formatters are available for at least HTML, FrameMaker
MIF and ASCII."""
try:
formatter[0]
except:
formatter = [formatter]
for form in formatter:
for manpage in self.manpgs:
file = open(manpage.name()+form.file_ext, 'w')
file.write(manpage.render(form))
file.close()
# Overridden methods from base class
def file_input(self, ref_module):
"""Handles module nodes.
Each module is put in a separate file."""
message("*** Start handling %s" % self.name)
if ref_module:
_manpage_init(self.manpage,
type_str = 'module',
name = self.name,
doc = ref_module.doc)
# Navigation button to module index page
self.manpage.top('index.html')
def import_stmt(self, ref_import):
"""Handles import nodes.
Each import on global level ends up in the SEE ALSO section."""
message("--- Import stmnt %s" % ref_import.name)
# Create a hyperlink reference
if self.is_global() and ref_import.name not in self.see_also:
self.see_also.append(ref_import.name)
def classdef(self, ref_classdef):
""" Override this to handle class definition nodes. """
message("--- Class def %s" % ref_classdef.name)
# Only generate doc for classes in the global scope
is_global = self.is_global()
# Skip ~internal~ classes, maybe?
if self.skip_internal and ref_classdef.name[0] == '_':
is_global = 0
if is_global:
ref = self.name + '-' + ref_classdef.name
text = self.manpage.reference(ref, str(ref_classdef)[:-1])
self.classes.append(text)
# Push my declaration on stack
ScopeTracker.classdef(self, ref_classdef)
if is_global:
manpage = ManualPage.ManualPage(self.name + '-' + ref_classdef.name)
marker = self.name+', module'
_manpage_init(manpage,
type_str = 'class',
name = ref_classdef.name,
doc = ref_classdef.doc,
marker = marker)
# Set up link to module page
manpage.top(self.manpage)
decl = self.top_declaration()
decl.append(manpage)
decl.append(str(ref_classdef))
def funcdef(self, ref_funcdef):
""" Override this to handle function definition nodes. """
message("--- Func def %s" % ref_funcdef.name)
# Unless skip_internal is false, skip functions
# beginning with a single underscore.
if not self.skip_internal or \
ref_funcdef.name[0] != '_' or \
ref_funcdef.name[1] == '_':
doc = ref_funcdef.doc
if doc:
doc = eval(doc) # doc is a string containing a string!
oneliner, doc = docutil.split_doc(doc)
signature = str(ref_funcdef)[:-1]
manpage = self.manpage
# Create hyperlink if it has a docstring (apart from the
# oneliner).
if doc:
ref_signature = manpage.reference(signature)
else:
ref_signature = signature
if self.is_global():
self.functions.append(ref_signature)
mark_mod = self.name + ', module'
else:
top = self.top_declaration()
# Is this a member function of a global function?
if top[0].ast[0] == symbol.classdef and len(top) > 2:
# Yes, insert the function in the class
# declaration element on the stack. The manpage
# is updated when we reach the end of the
# class' scope.
manpage = top[2]
top.append(ref_signature)
if oneliner:
top.append(' # '+oneliner)
mark_mod = top[0].name + ', class'
# If we have a doc string, generate a hyperlink
# to it, and put the oneliner with the function
# declaration.
if doc:
mark_me = ref_funcdef.name + ', function'
description = manpage.section('DESCRIPTION')
fundesc = manpage.section(signature, description, mark_me, mark_mod)
docutil.docregex_parse(manpage, fundesc, doc)
#manpage.paragraph(doc, fundesc)
ScopeTracker.funcdef(self, ref_funcdef)
def dedent(self, ref_dedent):
""" Override this to handle dedent nodes. """
top = ScopeTracker.dedent(self, ref_dedent)
if top and len(top) > 2:
manpage = top[2]
synopsis = manpage.section('SYNOPSIS')
# If it is a classdef, collect the member function
# strings and put them in the manual page.
if top[0].ast[0] == symbol.classdef:
decl_str = string.joinfields(top[3:], '\n ')
manpage.code(decl_str, synopsis)
self.manpgs.append(manpage)
|