⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lisp_codegen.py

📁 用python写的ide开发环境,巨强大,不过需要wxpython的支持
💻 PY
📖 第 1 页 / 共 4 页
字号:
# lisp_codegen.py: lisp code generator# $Id: lisp_codegen.py,v 1.5 2006/11/30 16:25:33 jkt Exp $## Copyright (c) 2005 Surendra K Singhi <efuzzyone@users.sourceforge.net># License: MIT (see license.txt)# THIS PROGRAM COMES WITH NO WARRANTY"""\How the code is generated: every time the end of an object is reached duringthe parsing of the xml tree, either the function 'add_object' or the function'add_class' is called: the latter when the object is a toplevel one, the formerwhen it is not. In the last case, 'add_object' calls the appropriate ``writer''function for the specific object, found in the 'obj_builders' dict. Suchfunction accepts one argument, the CodeObject representing the object forwhich the code has to be written, and returns 3 lists of strings, representingthe lines to add to the '__init__', '__set_properties' and '__do_layout'methods of the parent object."""import sys, os, os.pathimport common, configimport cStringIOfrom xml_parse import XmlParsingErrorimport retry:    setexcept NameError:    from sets import Set as set# these two globals must be defined for every code generator modulelanguage = 'lisp'writer = sys.modules[__name__] # the writer is the module itself# default extensions for generated files: a list of file extensionsdefault_extensions = ['lisp']"""\dictionary that maps the lines of code of a class to the name of such class:the lines are divided in 3 categories: '__init__', '__set_properties' and'__do_layout'"""classes = None"""dictionary of ``writers'' for the various objects"""obj_builders = {}"""\dictionary of ``property writer'' functions, used to set the properties of atoplevel object"""obj_properties = {}# random number used to be sure that the replaced tags in the sources are# the right ones (see SourceFileContent and add_class)nonce = None# lines common to all the generated files (import of wxCL, ...)header_lines = []class_lines = []init_lines = []# if True, generate a file for each custom classmultiple_files = False# if not None, it is the single source file to write intooutput_file = None# if not None, it is the directory inside which the output files are savedout_dir = Noneimport_packages = []use_new_namespace = Truedef cn(class_name):    if use_new_namespace:        if class_name[:2] == 'wx':             return 'wx' + class_name[2:]        elif class_name[:4] == 'EVT_':            return 'wx' + class_name    return class_namedef cn_f(flags):    if use_new_namespace:        return "|".join([cn(f) for f in str(flags).split('|')])    else:        return str(flags)# ALB 2004-12-05: wx version we are generating code forfor_version = (2, 4)class ClassLines:    """\    Stores the lines of lisp code for a custom class    """    def __init__(self):        self.init = [] # lines of code to insert in the __init__ method            # (for children widgets)        self.parents_init = [] # lines of code to insert in the __init__ for            # container widgets (panels, splitters, ...)        self.sizers_init = [] # lines related to sizer objects declarations        self.props = [] # lines to insert in the __set_properties method        self.layout = [] # lines to insert in the __do_layout method        self.dependencies = {} # names of the modules this class depends on        self.done = False # if True, the code for this class has already            # been generated        # ALB 2004-12-05        self.event_handlers = [] # lines to bind events # end of class ClassLinesclass SourceFileContent:    """\    Keeps info about an existing file that has to be updated, to replace only    the lines inside a wxGlade block, an to keep the rest of the file as it was    """    def __init__(self, name=None, content=None, classes=None):        self.name = name # name of the file        self.content = content # content of the source file, if it existed            # before this session of code generation        self.classes = classes # classes declared in the file        self.new_classes = [] # new classes to add to the file (they are            # inserted BEFORE the old ones)        if classes is None: self.classes = {}        self.spaces = {} # indentation level for each class        # ALB 2004-12-05        self.event_handlers = {} # list of event handlers for each class        if self.content is None:            self.build_untouched_content()    def build_untouched_content(self):        """\        Builds a string with the contents of the file that must be left as is,        and replaces the wxGlade blocks with tags that in turn will be replaced        by the new wxGlade blocks        """        class_name = None        new_classes_inserted = False        # regexp to match class declarations        # jdubery - less precise regex, but matches definitions with base        #           classes having module qualified names        class_decl = re.compile(r'^\s*class\s+([a-zA-Z_]\w*)\s*'                                '(\([\s\w.,]*\))?:\s*$')        # regexps to match wxGlade blocks        block_start = re.compile(r'^(\s*)#\s*begin\s+wxGlade:\s*'                                 '([A-Za-z_]+\w*)??[.]?(\w+)\s*$')        block_end = re.compile(r'^\s*#\s*end\s+wxGlade\s*$')        # regexp to match event handlers        # ALB 2004-12-05        event_handler = re.compile(r'^\s+def\s+([A-Za-z_]+\w*)\s*\(.*\):\s*'                                   '#\s*wxGlade:\s*(\w+)\.<event_handler>\s*$')        inside_block = False        inside_triple_quote = False        triple_quote_str = None        tmp_in = open(self.name)        out_lines = []        for line in tmp_in:            quote_index = -1            if not inside_triple_quote:                triple_dquote_index = line.find('"""')                triple_squote_index = line.find("'''")                if triple_squote_index == -1:                    quote_index = triple_dquote_index                    tmp_quote_str = '"""'                elif triple_dquote_index == -1:                    quote_index = triple_squote_index                    tmp_quote_str = "'''"                else:                    quote_index, tmp_quote_str = min(                        (triple_squote_index, "'''"),                        (triple_dquote_index, '"""'))            if not inside_triple_quote and quote_index != -1:                inside_triple_quote = True                triple_quote_str = tmp_quote_str            if inside_triple_quote:                end_index = line.rfind(triple_quote_str)                if quote_index < end_index and end_index != -1:                    inside_triple_quote = False            result = class_decl.match(line)            if not inside_triple_quote and result is not None:##                 print ">> class %r" % result.group(1)                if class_name is None:                    # this is the first class declared in the file: insert the                    # new ones before this                    out_lines.append('<%swxGlade insert new_classes>' %                                     nonce)                    new_classes_inserted = True                class_name = result.group(1)                self.classes[class_name] = 1 # add the found class to the list                    # of classes of this module                out_lines.append(line)            elif not inside_block:                result = block_start.match(line)                if not inside_triple_quote and result is not None:##                     print ">> block %r %r %r" % (##                         result.group(1), result.group(2), result.group(3))                    # replace the lines inside a wxGlade block with a tag that                    # will be used later by add_class                    spaces = result.group(1)                    which_class = result.group(2)                    which_block = result.group(3)                    if which_class is None: which_class = class_name                    self.spaces[which_class] = spaces                    inside_block = True                    if class_name is None:                        out_lines.append('<%swxGlade replace %s>' % \                                         (nonce, which_block))                    else:                        out_lines.append('<%swxGlade replace %s %s>' % \                                         (nonce, which_class, which_block))                else:                    #- ALB 2004-12-05 ----------                    result = event_handler.match(line)                    if not inside_triple_quote and result is not None:                        which_handler = result.group(1)                        which_class = result.group(2)                        self.event_handlers.setdefault(                            which_class, {})[which_handler] = 1                    if class_name is not None and self.is_end_of_class(line):                        # add extra event handlers here...                        out_lines.append('<%swxGlade event_handlers %s>'                                         % (nonce, class_name))                    #---------------------------                    out_lines.append(line)                    if self.is_import_line(line):                        # add a tag to allow extra modules                        out_lines.append('<%swxGlade extra_modules>\n'                                         % nonce)            else:                # ignore all the lines inside a wxGlade block                if block_end.match(line) is not None:                    inside_block = False        if not new_classes_inserted:            # if we are here, the previous ``version'' of the file did not            # contain any class, so we must add the new_classes tag at the            # end of the file            out_lines.append('<%swxGlade insert new_classes>' % nonce)        tmp_in.close()        # set the ``persistent'' content of the file        self.content = "".join(out_lines)    def is_import_line(self, line):        if use_new_namespace:            return line.startswith('import wx')        else:            return line.startswith('from wxLisp.wx import *')    def is_end_of_class(self, line):        return line.strip().startswith('# end of class ')# end of class SourceFileContent# if not None, it is an instance of SourceFileContent that keeps info about# the previous version of the source to generateprevious_source = None def tabs(number):    return '    ' * number# if True, overwrite any previous version of the source file instead of# updating only the wxGlade blocks_overwrite = False# if True, enable gettext support_use_gettext = False_quote_str_pattern = re.compile(r'\\[natbv"]?')def _do_replace(match):    if match.group(0) == '\\': return '\\\\'    else: return match.group(0)def quote_str(s, translate=True, escape_chars=True):    """\    returns a quoted version of 's', suitable to insert in a lisp source file    as a string object. Takes care also of gettext support    """    if not s: return '""'    s = s.replace('"', r'\"')    if escape_chars: s = _quote_str_pattern.sub(_do_replace, s)    else: s = s.replace('\\', r'\\') # just quote the backslashes    try:        unicode(s, 'ascii')        if _use_gettext and translate: return '_("' + s + '")'        else: return '"' + s + '"'    except UnicodeDecodeError:        if _use_gettext and translate: return '_(u"' + s + '")'        else: return 'u"' + s + '"'def initialize(app_attrs):     """\    Writer initialization function.    - app_attrs: dict of attributes of the application. The following two        are always present:            path: output path for the generated code (a file if multi_files is                False, a dir otherwise)            option: if True, generate a separate file for each custom class    """    out_path = app_attrs['path']    multi_files = app_attrs['option']    global classes, header_lines, multiple_files, previous_source, nonce, \           _current_extra_modules, _use_gettext, _overwrite, import_packages    import time, random    try: _use_gettext = int(app_attrs['use_gettext'])    except (KeyError, ValueError): _use_gettext = False    # overwrite added 2003-07-15    try: _overwrite = int(app_attrs['overwrite'])    except (KeyError, ValueError): _overwrite = False    # this is to be more sure to replace the right tags    nonce = '%s%s' % (str(time.time()).replace('.', ''),                      random.randrange(10**6, 10**7))    # ALB 2004-01-18    global use_new_namespace    try: use_new_namespace = int(app_attrs['use_new_namespace'])    except (KeyError, ValueError): pass # use the default value    # ALB 2004-12-05

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -