Ticket #3485: trac3485-sage_input.patch

File trac3485-sage_input.patch, 55.0 kB (added by cwitty, 7 months ago)
  • a/sage/misc/all.py

    old new  
    6363from interpreter import preparser 
    6464 
    6565from sage_eval import sage_eval, sageobj 
     66 
     67from sage_input import sage_input 
    6668 
    6769from cython import cython_lambda 
    6870from cython_c import cython 
  • /dev/null

    old new  
     1r""" 
     2Sage Input Formatting 
     3 
     4AUTHORS: 
     5    -- Carl Witty (2008-04): new file 
     6 
     7This module provides a function \function{sage_input}.  This function 
     8takes an arbitrary \sage value and produces a sequence of commands 
     9that, if typed at the \code{sage:} prompt, will recreate the value. 
     10(If this is not implemented for a particular value, then an exception 
     11is raised instead.)  We attempt to produce commands that are readable  
     12and idiomatic. 
     13 
     14sage: sage_input(3) 
     153 
     16sage: sage_input((polygen(RR) + RR(pi))^2, verify=True) 
     17# Verified 
     18R.<x> = RR[] 
     19x^2 + 6.2831853071795862*x + 9.8696044010893580 
     20 
     21With \code{verify=True}, \function{sage_input} also verifies the 
     22results, by calling sage_eval on the result and verifying that it is 
     23equal to the input. 
     24 
     25sage: sage_input(GF(2)(1), verify=True) 
     26# Verified 
     27GF(2)(1) 
     28 
     29We can generate code that works without the preparser, with 
     30\code{preparse=False}; or we can generate code that will work 
     31whether or not the preparser is enabled, with \code{preparse=None}. 
     32 
     33sage: sage_input(5, verify=True) 
     34# Verified 
     355 
     36sage: sage_input(5, preparse=False) 
     37ZZ(5) 
     38sage: sage_input(5, preparse=None) 
     39ZZ(5) 
     40sage: sage_input(5r, verify=True) 
     41# Verified 
     425r 
     43sage: sage_input(5r, preparse=False) 
     445 
     45sage: sage_input(5r, preparse=None) 
     46int(5) 
     47 
     48Adding \function{sage_input} support to your own classes is 
     49straightforward.  You need to add a \method{_sage_input_} method which 
     50returns a \class{SageInputExpression} (henceforth abbreviated as SIE) 
     51which will reconstruct this instance of your class. 
     52 
     53A \method{_sage_input_} method takes two parameters, conventionally 
     54named \var{sib} and \var{coerced}.  The first argument is a 
     55\class{SageInputBuilder}; it has methods to build SIEs.  The second 
     56argument, \var{coerced}, is a boolean.  This is only useful if your 
     57class is a subclass of \class{Element} (although it is always 
     58present).  If \var{coerced} is \code{False}, then your method must 
     59generate an expression which will evaluate to a value of the correct  
     60type with the correct parent.  If \var{coerced} is \code{True}, then 
     61your method may generate an expression of a type that has a canonical 
     62coercion to your type. 
     63 
     64Let's work through some examples.  We'll build a sequence of functions 
     65that would be acceptable as \method{_sage_input_} methods for the 
     66\class{Rational} class. 
     67 
     68Here's the first and simplest version. 
     69 
     70sage: def qq_sage_input_v1(self, sib, coerced): 
     71...       return sib(self.numerator())/sib(self.denominator()) 
     72 
     73We see that given a \class{SageInputBuilder} \var{sib}, you can 
     74construct a SIE for a value \var{v} simply with \code{sib(v)}, and you 
     75can construct a SIE for a quotient with the division operator.  Of course, 
     76the other operators also work, and so do function calls, method calls, 
     77subscripts, etc. 
     78 
     79We'll test with the following code, which you don't need to understand. 
     80(It produces a list of 8 results, showing the formatted versions of 
     81-5/7 and 3, with the preparser either enabled or disabled and either 
     82with or without an automatic coercion to QQ.) 
     83 
     84sage: from sage.misc.sage_input import SageInputBuilder 
     85sage: def test_qq_formatter(fmt): 
     86...       results = [] 
     87...       for v in [-5/7, QQ(3)]: 
     88...           for pp in [False, True]: 
     89...               for coerced in [False, True]: 
     90...                   sib = SageInputBuilder(preparse=pp) 
     91...                   results.append(sib.result(fmt(v, sib, coerced))) 
     92...       return results 
     93 
     94sage: test_qq_formatter(qq_sage_input_v1) 
     95[-ZZ(5)/ZZ(7), -ZZ(5)/ZZ(7), -5/7, -5/7, ZZ(3)/ZZ(1), ZZ(3)/ZZ(1), 3/1, 3/1] 
     96 
     97Let's try for some shorter, perhaps nicer-looking output.  We'll start 
     98by getting rid of the \code{ZZ} in the denominators; even without the 
     99preparser, \code{-ZZ(5)/7 == -ZZ(5)/ZZ(7)}. 
     100 
     101sage: def qq_sage_input_v2(self, sib, coerced): 
     102...       return sib(self.numerator())/sib.int(self.denominator()) 
     103 
     104The \method{int} method on \class{SageInputBuilder} returns a SIE for 
     105an integer that is always represented in the simple way, without 
     106coercions.  (So, depending on the preparser mode, it might read in as an 
     107\class{Integer}, an \class{int}, or a \class{long}.) 
     108 
     109sage: test_qq_formatter(qq_sage_input_v2) 
     110[-ZZ(5)/7, -ZZ(5)/7, -5/7, -5/7, ZZ(3)/1, ZZ(3)/1, 3/1, 3/1] 
     111 
     112Next let's get rid of the divisions by 1.  These are more complicated, 
     113since if we're not careful we'll get results in \ZZ instead of \QQ. 
     114 
     115sage: def qq_sage_input_v3(self, sib, coerced): 
     116...       if self.denominator() == 1: 
     117...           if coerced: 
     118...               return sib.int(self.numerator()) 
     119...           else: 
     120...               return sib.name('QQ')(sib.int(self.numerator())) 
     121...       return sib(self.numerator())/sib.int(self.denominator()) 
     122 
     123We see that the \method{name} method gives an SIE representing a \sage 
     124constant or function. 
     125 
     126sage: test_qq_formatter(qq_sage_input_v3) 
     127[-ZZ(5)/7, -ZZ(5)/7, -5/7, -5/7, QQ(3), 3, QQ(3), 3] 
     128 
     129This is the prettiest output we're going to get, but let's make one 
     130further refinement.  Other \class{_sage_input_} methods, like the one 
     131for polynomials, analyze the structure of SIEs; they work better (give 
     132prettier output) if negations are at the outside. 
     133 
     134sage: def qq_sage_input_v4(self, sib, coerced): 
     135...       num = self.numerator() 
     136...       neg = (num < 0) 
     137...       if neg: num = -num 
     138...       if self.denominator() == 1: 
     139...           if coerced: 
     140...               v = sib.int(num) 
     141...           else: 
     142...               v = sib.name('QQ')(sib.int(num)) 
     143...       else: 
     144...           v = sib(num)/sib.int(self.denominator()) 
     145...       if neg: v = -v 
     146...       return v 
     147 
     148sage: test_qq_formatter(qq_sage_input_v4) 
     149[-ZZ(5)/7, -ZZ(5)/7, -5/7, -5/7, QQ(3), 3, QQ(3), 3] 
     150 
     151""" 
     152 
     153from sage.misc.functional import parent 
     154 
     155########################################################################## 
     156# 
     157#       Copyright (C) 2008 Carl Witty <Carl.Witty@gmail.com> 
     158# 
     159#  Distributed under the terms of the GNU General Public License (GPL) 
     160# 
     161#                  http://www.gnu.org/licenses/ 
     162# 
     163########################################################################## 
     164 
     165def sage_input(x, preparse=True, verify=False, allow_locals=False): 
     166    r""" 
     167    INPUTS: 
     168        x -- the value we want to find an ``input form'' for 
     169        preparse -- (default \code{True}) Whether to generate code 
     170            that requires the preparser.  With \code{True}, generated 
     171            code requires the preparser.  With \code{False}, generated 
     172            code requires that the preparser not be used.  With \code{None}, 
     173            generated code will work whether or not the preparser is used. 
     174        verify -- (default \code{False}) If \code{True}, then the  
     175            answer will be evaluated with \function{sage_eval}, and  
     176            an exception will be raised if the result is not equal to 
     177            the original value.  (In fact, for \code{verify=True}, 
     178            \function{sage_input} is effectively run three times, 
     179            with \var{preparse} set to \code{True}, \code{False}, and  
     180            \code{None}, and all three results are checked.)  This is 
     181            particularly useful for doctests. 
     182        allow_locals -- (default \code{False}) If \code{True}, then 
     183            values that \function{sage_input} cannot handle are returned 
     184            in a dictionary, and the returned code assumes that this  
     185            dictionary is passed as the \var{locals} parameter of  
     186            \function{sage_eval}.  (Otherwise, if \function{sage_input} 
     187            cannot handle a value, an exception is raised.) 
     188 
     189    EXAMPLES: 
     190        sage: sage_input(GF(2)(1)) 
     191        GF(2)(1) 
     192        sage: sage_input((GF(2)(0), GF(2)(1)), verify=True) 
     193        # Verified 
     194        GF_2 = GF(2) 
     195        (GF_2(0), GF_2(1)) 
     196 
     197    When the preparser is enabled, we use the \sage generator syntax. 
     198 
     199        sage: K.<x> = GF(5)[] 
     200        sage: sage_input(x^3 + 2*x, verify=True) 
     201        # Verified 
     202        R.<x> = GF(5)[] 
     203        x^3 + 2*x 
     204        sage: sage_input(x^3 + 2*x, preparse=False) 
     205        R = GF(5)['x'] 
     206        x = R.gen() 
     207        x**3 + 2*x 
     208 
     209    The result of \function{sage_input} is actually a pair of strings with 
     210    a special \method{__repr__} method to print nicely. 
     211 
     212        sage: r = sage_input(RealField(20)(pi), verify=True) 
     213        sage: r 
     214        # Verified 
     215        RealField(20)(3.1415939) 
     216        sage: isinstance(r, tuple) 
     217        True 
     218        sage: len(r) 
     219        2 
     220        sage: tuple(r) 
     221        ('# Verified\n', 'RealField(20)(3.1415939)') 
     222 
     223    We cannot find an input form for a function. 
     224 
     225        sage: sage_input((3, lambda x: x)) 
     226        Traceback (most recent call last): 
     227        ... 
     228        ValueError: Can't convert <function <lambda> at 0x...> to sage_input form 
     229 
     230    But we can have \function{sage_input} continue anyway, and return 
     231    an input form for the rest of the expression, with  
     232    \code{allow_locals=True}. 
     233 
     234        sage: r = sage_input((3, lambda x: x), verify=True, allow_locals=True) 
     235        sage: r 
     236        LOCALS: 
     237            _sil1: <function <lambda> at 0x...> 
     238        # Verified 
     239        (3, _sil1) 
     240        sage: tuple(r) 
     241        ('# Verified\n', '(3, _sil1)', {'_sil1': <function <lambda> at 0x...>}) 
     242    """ 
     243    if not verify: 
     244        sib = SageInputBuilder(allow_locals=allow_locals, preparse=preparse) 
     245        return sib.result(sib(x)) 
     246 
     247    # In verify mode, we actually compute and verify the answer with 
     248    # all three settings of preparse. 
     249 
     250    for pp in (True, False, None): 
     251        sib = SageInputBuilder(allow_locals=allow_locals, preparse=pp) 
     252        ans = sib.result(sib(x)) 
     253        verify_si_answer(x, ans, pp) 
     254        if pp == preparse: 
     255            ans_l = list(ans) 
     256            ans_l[0] = '# Verified\n' + ans_l[0] 
     257            final_answer = SageInputAnswer(*ans_l) 
     258 
     259    return final_answer 
     260 
     261class SageInputBuilder: 
     262    r""" 
     263    An instance of this class is passed to \method{_sage_input_} methods. 
     264    It keeps track of the current state of the \method{_sage_input_} process, 
     265    and contains many utility methods for building \class{SageInputExpression} 
     266    objects. 
     267 
     268    In normal use, instances of \class{SageInputBuilder} are created 
     269    internally by \function{sage_input}, but it may be useful to create 
     270    an instance directly for testing or doctesting. 
     271 
     272    EXAMPLES: 
     273        sage: from sage.misc.sage_input import SageInputBuilder 
     274         
     275    We can create a \class{SageInputBuilder}, use it to create some 
     276    \class{SageInputExpression}s, and get a result.  (As mentioned 
     277    above, this is only useful for testing or doctesting; normally 
     278    you would just use \function{sage_input}.) 
     279 
     280        sage: sib = SageInputBuilder() 
     281        sage: sib.result((sib(3) + sib(4)) * (sib(5) + sib(6))) 
     282        (3 + 4)*(5 + 6) 
     283    """ 
     284 
     285    def __init__(self, allow_locals=False, preparse=True): 
     286        r""" 
     287        Construct an instance of \class{SageInputBuilder}. 
     288 
     289        In normal use, instances of \class{SageInputBuilder} are created 
     290        internally by \function{sage_input}, but it may be useful to create 
     291        an instance directly for testing or doctesting. 
     292 
     293        INPUTS: 
     294            allow_locals -- (default \code{False}) If true, then values 
     295                that cannot be converted to input form will be stored in 
     296                a dictionary, which must be passed as the \var{locals} 
     297                when evaluating the result. 
     298            preparse -- (default \code{True}) If true, then the result 
     299                will assume that the preparser is enabled.  If false, then 
     300                the result will assume that the preparser is disabled. 
     301                If \code{None}, then the result will work whether or 
     302                not the preparser is enabled. 
     303 
     304        EXAMPLES: 
     305            sage: from sage.misc.sage_input import SageInputBuilder 
     306            sage: SageInputBuilder().preparse() 
     307            True 
     308            sage: SageInputBuilder(preparse=False).preparse() 
     309            False 
     310        """ 
     311        self._allow_locals = allow_locals 
     312        self._preparse = preparse 
     313        self._cached_types = set() 
     314        self._cache = {} 
     315        self._parent_gens = {} 
     316        self._next_local = 1 
     317        self._locals = {} 
     318 
     319    def __call__(self, x, coerced=False): 
     320        r""" 
     321        Tries to convert an arbitrary value \var{x} into a 
     322        \class{SageInputExpression} (an SIE). 
     323 
     324        We first check to see if an SIE has been cached for \var{x}; 
     325        if so, we return it.  If \var{x} is already an SIE, we return 
     326        it unchanged. 
     327 
     328        If \var{x} has a \method{_sage_input_} method, we call that 
     329        method. 
     330 
     331        Otherwise, if \var{x} is a value of some Python type that 
     332        we know how to deal with, we convert it directly. 
     333 
     334        Finally, for values we don't know how to convert, if 
     335        \code{self._allow_locals} is true, we add it to a 
     336        ``locals'' dictionary. 
     337 
     338        EXAMPLES: 
     339            sage: from sage.misc.sage_input import SageInputBuilder 
     340 
     341            sage: sib = SageInputBuilder() 
     342            sage: sib.result(sib(sib(3))) 
     343            3 
     344 
     345            sage: sib = SageInputBuilder() 
     346            sage: sib.result(sib(GF(17)(5))) 
     347            GF(17)(5) 
     348 
     349        The argument \code{coerced=True} will get passed to the 
     350        \method{_sage_input_} method of the argument. 
     351            sage: sib = SageInputBuilder() 
     352            sage: sib.result(sib(GF(17)(5), True)) 
     353            5 
     354 
     355        Since \function{sage_input} directly calls this method, all 
     356        of the following are indirect doctests. 
     357            sage: sage_input(True) 
     358            True 
     359            sage: sage_input(-5r) 
     360            -5r 
     361            sage: sage_input(7r, preparse=False) 
     362            7 
     363            sage: sage_input(-11r, preparse=None) 
     364            -int(11) 
     365            sage: sage_input(long(-5)) 
     366            -long(5) 
     367            sage: sage_input(long(-7), preparse=False) 
     368            -7L 
     369            sage: sage_input(long(11), preparse=None) 
     370            long(11) 
     371            sage: sage_input(long(2^70)) 
     372            1180591620717411303424r 
     373            sage: sage_input(-long(2^80), preparse=False) 
     374            -1208925819614629174706176 
     375            sage: sage_input(long(2^75), preparse=None) 
     376            long(37778931862957161709568) 
     377            sage: sage_input("Hello, world\n") 
     378            'Hello, world\n' 
     379            sage: sage_input((2, 3.5, 'Hi')) 
     380            (2, RR(3.5000000000000000), 'Hi') 
     381            sage: sage_input(lambda x: x) 
     382            Traceback (most recent call last): 
     383            ... 
     384            ValueError: Can't convert <function <lambda> at 0x...> to sage_input form 
     385            sage: sage_input(lambda x: x, allow_locals=True) 
     386            LOCALS: 
     387              _sil1: <function <lambda> at 0x...> 
     388            _sil1 
     389        """ 
     390        if type(x) in self._cached_types: 
     391            v = self._cache.get((parent(x), x)) 
     392            if v is not None: return v 
     393 
     394        if isinstance(x, SageInputExpression): 
     395            return x 
     396 
     397        if hasattr(x, '_sage_input_'): 
     398            return x._sage_input_(self, coerced) 
     399 
     400        if isinstance(x, bool): 
     401            return SIE_literal_stringrep(self, str(x)) 
     402 
     403        if isinstance(x, int) or \ 
     404                (isinstance(x, long) and isinstance(int(x), long)): 
     405            # For longs that don't fit in an int, we just use the int 
     406            # code; it will get extended to long automatically.             
     407            if self._preparse == True: 
     408                if x < 0: 
     409                    return -SIE_literal_stringrep(self, str(-x) + 'r') 
     410                else: 
     411                    return SIE_literal_stringrep(self, str(x) + 'r') 
     412            elif self._preparse == False: 
     413                return self.int(x) 
     414            else: 
     415                tyname = 'int' if isinstance(x, int) else 'long' 
     416                if x < 0: 
     417                    return -self.name(tyname)(self.int(-x)) 
     418                else: 
     419                    return self.name(tyname)(self.int(x)) 
     420 
     421        if isinstance(x, long): 
     422            # This must be a long that does fit in an int, so we need either 
     423            # long(x) or an 'L' suffix. 
     424            # With the current preparser, 1Lr does not work. 
     425            # 1rL does work; but that's just ugly, so I don't use it. 
     426            if self._preparse == False: 
     427                if x < 0: 
     428                    return -SIE_literal_stringrep(self, str(-x) + 'L') 
     429                else: 
     430                    return SIE_literal_stringrep(self, str(x) + 'L') 
     431            else: 
     432                if x < 0: 
     433                    return -self.name('long')(self.int(-x)) 
     434                else: 
     435                    return self.name('long')(self.int(x))             
     436 
     437        if isinstance(x, str): 
     438            return SIE_literal_stringrep(self, repr(x)) 
     439 
     440        if isinstance(x, tuple): 
     441            return SIE_tuple(self, map(self, x)) 
     442 
     443        if self._allow_locals: 
     444            loc = self._next_local 
     445            self._next_local += 1 
     446            loc_name = '_sil%d' % loc 
     447            self._locals[loc_name] = x 
     448            return SIE_literal_stringrep(self, loc_name) 
     449        else: 
     450            raise ValueError, "Can't convert %r to sage_input form"%x 
     451 
     452    def preparse(self): 
     453        r""" 
     454        Checks the preparse status of this \class{SageInputBuilder}. 
     455        (\code{True} if the preparser will be enabled, \code{False} 
     456        if it will be disabled, and \code{None} if the result must 
     457        work whether or not the preparser is enabled.) 
     458 
     459        For example, this is useful in the \method{_sage_input_} 
     460        methods of \class{Integer} and \class{RealNumber}; but most 
     461        \method{_sage_input_} methods will not need to examine this. 
     462 
     463        EXAMPLES: 
     464            sage: from sage.misc.sage_input import SageInputBuilder 
     465            sage: SageInputBuilder().preparse() 
     466            True 
     467            sage: SageInputBuilder(preparse=False).preparse() 
     468            False 
     469        """ 
     470        return self._preparse 
     471 
     472    def int(self, n): 
     473        r""" 
     474        Given an integer (an \class{Integer}, an \class{int}, or a 
     475        \class{long}), produce a \class{SageInputExpression} that displays 
     476        the integer with no marking for what kind of integer it is 
     477        (so it may read back as an \class{Integer}, an \class{int}, or 
     478        a \class{long}, depending on its size and whether the preparser 
     479        is enabled). 
     480 
     481        EXAMPLES: 
     482            sage: from sage.misc.sage_input import SageInputBuilder 
     483 
     484            sage: sib = SageInputBuilder() 
     485            sage: sib.result(sib.int(-3^50)) 
     486            -717897987691852588770249 
     487             
     488            sage: sib = SageInputBuilder() 
     489            sage: sib.result(sib.int(long(2^65))) 
     490            36893488147419103232 
     491 
     492            sage: sib = SageInputBuilder() 
     493            sage: sib.result(sib.int(-42r)) 
     494            -42 
     495        """ 
     496        if n < 0: 
     497            return -SIE_literal_stringrep(self, -n) 
     498        else: 
     499            return SIE_literal_stringrep(self, n) 
     500 
     501    def float_str(self, n): 
     502        r""" 
     503        Given a string representing a floating-point number, 
     504        produces a \class{SageInputExpression} that formats as that 
     505        string. 
     506 
     507        EXAMPLES: 
     508            sage: from sage.misc.sage_input import SageInputBuilder 
     509 
     510            sage: sib = SageInputBuilder() 
     511            sage: sib.result(sib.float_str(repr(RR(e)))) 
     512            2.71828182845905 
     513        """ 
     514        return SIE_literal_stringrep(self, n) 
     515 
     516    def name(self, n): 
     517        r""" 
     518        Given a string representing a Python name, 
     519        produces a \class{SageInputExpression} for that name. 
     520 
     521        EXAMPLES: 
     522            sage: from sage.misc.sage_input import SageInputBuilder 
     523 
     524            sage: sib = SageInputBuilder() 
     525            sage: sib.result(sib.name('pi') + sib.name('e')) 
     526            pi + e 
     527        """ 
     528        return SIE_literal_stringrep(self, n) 
     529 
     530    def cache(self, x, sie, name): 
     531        r""" 
     532        INPUTS: 
     533            x -- an arbitrary value 
     534            sie -- a \class{SageInputExpression} 
     535            name -- a requested variable name 
     536 
     537        Enters \var{x} and \var{sie} in a cache, so that subsequent calls 
     538        \code{self(x)} will directly return \var{sie}.  Also, marks the 
     539        requested name of this \var{sie} to be \var{name}. 
     540 
     541        This should almost always be called as part of the  
     542        \method{_sage_input_} method of a parent.  It may also be called 
     543        on values of an arbitrary type, which may be useful if the values 
     544        are both large and likely to be used multiple times in a single 
     545        expression. 
     546 
     547        EXAMPLES: 
     548            sage: from sage.misc.sage_input import SageInputBuilder 
     549 
     550            sage: sib = SageInputBuilder() 
     551            sage: sie42 = sib(GF(101)(42)) 
     552            sage: sib.cache(GF(101)(42), sie42, 'the_ultimate_answer') 
     553            sage: sib.result(sib(GF(101)(42)) + sib(GF(101)(42))) 
     554            the_ultimate_answer = GF(101)(42) 
     555            the_ultimate_answer + the_ultimate_answer 
     556 
     557        Note that we don't assign the result to a variable if the value 
     558        is only used once. 
     559            sage: sib = SageInputBuilder() 
     560            sage: sie42 = sib(GF(101)(42)) 
     561            sage: sib.cache(GF(101)(42), sie42, 'the_ultimate_answer') 
     562            sage: sib.result(sib(GF(101)(42)) + sib(GF(101)(43))) 
     563            GF_101 = GF(101) 
     564            GF_101(42) + GF_101(43) 
     565        """ 
     566        self._cached_types.add(type(x)) 
     567        self._cache[(parent(x), x)] = sie 
     568        sie._sie_preferred_varname = name 
     569 
     570    def empty_subscript(self, parent): 
     571        r""" 
     572        Given a \class{SageInputExpression} representing \code{foo}, 
     573        produces a \class{SageInputExpression} representing \code{foo[]}. 
     574        Since this is not legal Python syntax, it is useful only for 
     575        producing the \sage generator syntax for a polynomial ring. 
     576 
     577        EXAMPLES: 
     578            sage: from sage.misc.sage_input import SageInputBuilder 
     579 
     580            sage: sib = SageInputBuilder() 
     581            sage: sib.result(sib.empty_subscript(sib(2) + sib(3))) 
     582            (2 + 3)[] 
     583 
     584        The following calls this method indirectly. 
     585            sage: sage_input(polygen(ZZ['y'])) 
     586            R.<x> = ZZ['y'][] 
     587            x 
     588        """ 
     589        return SIE_subscript(self, parent, None) 
     590 
     591    def parent_with_gens(self, parent, sie, gen_names, name, gens_syntax=None): 
     592        r""" 
     593        This method is used for parents with generators, to manage the 
     594        \sage preparser generator syntax (like \code{K.<x> = QQ[]}). 
     595 
     596        The \method{_sage_input_} method of a parent class with 
     597        generators should construct a \class{SageInputExpression} for 
     598        the parent, and then call this method with the parent itself, 
     599        the constructed SIE, a sequence containing the names of the 
     600        generators, and (optionally) another SIE to use if the \sage 
     601        generator syntax is used; typically this will be the same as 
     602        the first SIE except omitting a \var{names} parameter. 
     603 
     604        EXAMPLES: 
     605            sage: from sage.misc.sage_input import SageInputBuilder 
     606 
     607 
     608            sage: def test_setup(use_gens=True, preparse=True): 
     609            ...       sib = SageInputBuilder(preparse=preparse) 
     610            ...       gen_names=('foo', 'bar') 
     611            ...       parent = "some parent" 
     612            ...       normal_sie = sib.name('make_a_parent')(names=gen_names) 
     613            ...       if use_gens: 
     614            ...           gens_sie = sib.name('make_a_parent')() 
     615            ...       else: 
     616            ...           gens_sie = None 
     617            ...       name = 'the_thing' 
     618            ...       result = sib.parent_with_gens(parent, normal_sie,  
     619            ...                                     gen_names, name, 
     620            ...                                     gens_syntax=gens_sie) 
     621            ...       return sib, result 
     622 
     623            sage: sib, par_sie = test_setup() 
     624            sage: sib.result(par_sie) 
     625            make_a_parent(names=('foo', 'bar')) 
     626 
     627            sage: sib, par_sie = test_setup() 
     628            sage: sib.result(sib(3) * sib.gen("some parent", 0)) 
     629            the_thing.<foo,bar> = make_a_parent() 
     630            3*foo 
     631 
     632            sage: sib, par_sie = test_setup(preparse=False) 
     633            sage: sib.result(par_sie) 
     634            make_a_parent(names=('foo', 'bar')) 
     635 
     636            sage: sib, par_sie = test_setup(preparse=False) 
     637            sage: sib.result(sib(3) * sib.gen("some parent", 0)) 
     638            the_thing = make_a_parent(names=('foo', 'bar')) 
     639            foo,bar = the_thing.gens() 
     640            ZZ(3)*foo 
     641 
     642            sage: sib, par_sie = test_setup(use_gens=False) 
     643            sage: sib.result(par_sie) 
     644            make_a_parent(names=('foo', 'bar')) 
     645 
     646            sage: sib, par_sie = test_setup(use_gens=False) 
     647            sage: sib.result(sib(3) * sib.gen("some parent", 0)) 
     648            the_thing = make_a_parent(names=('foo', 'bar')) 
     649            foo,bar = the_thing.gens() 
     650            3*foo 
     651 
     652            sage: sib, par_sie = test_setup() 
     653            sage: sib.result(par_sie - sib.gen("some parent", 1)) 
     654            the_thing.<foo,bar> = make_a_parent() 
     655            the_thing - bar             
     656        """ 
     657        v = SIE_gens_constructor(self, sie, gen_names, gens_syntax=gens_syntax) 
     658        self.cache(parent, v, name) 
     659        gens = [SIE_gen(self, v, n) for n in gen_names] 
     660        self._parent_gens[parent] = gens 
     661        v._sie_gens = gens 
     662        return v 
     663 
     664    def gen(self, parent, n=0): 
     665        r""" 
     666        Given a parent, returns a \class{SageInputExpression} for 
     667        the $n$th (default 0) generator of the parent. 
     668 
     669        EXAMPLES: 
     670            sage: from sage.misc.sage_input import SageInputBuilder 
     671 
     672            sage: sib = SageInputBuilder() 
     673            sage: sib.result(sib.gen(ZZ['y'])) 
     674            R.<y> = ZZ[] 
     675            y 
     676        """ 
     677        if not parent in self._parent_gens: 
     678            self(parent) 
     679            if not parent in self._parent_gens: 
     680                raise ValueError, "%s did not register generators for sage_input" % parent 
     681 
     682        gens = self._parent_gens[parent] 
     683 
     684        if n > len(gens): 
     685            raise ValueError, "%s registered only %d generators for sage_input" % (parent, len(gens)) 
     686 
     687        return gens[n] 
     688         
     689    def prod(self, factors, simplify=False): 
     690        r""" 
     691        Given a sequence, returns a \class{SageInputExpression} 
     692        for the product of the elements. 
     693 
     694        With \code{simplify=True}, performs some simplifications 
     695        first.  If any element is formatted as a string \code{'0'}, 
     696        then that element is returned directly.  If any element is 
     697        formatted as a string \code{'1'}, then it is removed 
     698        from the sequence (unless it is the only element in the sequence). 
     699        And any negations are removed from the elements and moved to the 
     700        outside of the product. 
     701 
     702        EXAMPLES: 
     703            sage: from sage.misc.sage_input import SageInputBuilder 
     704 
     705            sage: sib = SageInputBuilder() 
     706            sage: sib.result(sib.prod([-1, 0, 1, -2])) 
     707            -1*0*1*-2 
     708 
     709            sage: sib = SageInputBuilder() 
     710            sage: sib.result(sib.prod([-1, 0, 1, 2], simplify=True)) 
     711            0 
     712 
     713            sage: sib = SageInputBuilder() 
     714            sage: sib.result(sib.prod([-1, 2, -3, -4], simplify=True)) 
     715            -2*3*4 
     716 
     717            sage: sib = SageInputBuilder() 
     718            sage: sib.result(sib.prod([-1, 1, -1, -1], simplify=True)) 
     719            -1 
     720 
     721            sage: sib = SageInputBuilder() 
     722            sage: sib.result(sib.prod([1, 1, 1], simplify=True)) 
     723            1 
     724        """ 
     725        neg = False 
     726        factors = [self(factor) for factor in factors] 
     727        if simplify: 
     728            i = 0 
     729            while i < len(factors): 
     730                factor = factors[i] 
     731                while isinstance(factor, SIE_unary) and factor._sie_op == '-': 
     732                    neg = not neg 
     733                    factor = factor._sie_operand 
     734                    factors[i] = factor 
     735                if isinstance(factor, SIE_literal_stringrep) and factor._sie_value == '0': 
     736                    factors = [factor] 
     737                    neg = False 
     738                    break 
     739                if isinstance(factor, SIE_literal_stringrep) and factor._sie_value == '1': 
     740                    factors[i:i+1] = [] 
     741                else: 
     742                    i += 1 
     743            if len(factors) == 0: 
     744                factors.append(SIE_literal_stringrep(self, '1')) 
     745 
     746        prod = factors[0] 
     747        for factor in factors[1:]: 
     748            prod = prod * factor 
     749        if neg: 
     750            prod = -prod 
     751        return prod 
     752 
     753    def sum(self, terms, simplify=False): 
     754        r""" 
     755        Given a sequence, returns a \class{SageInputExpression} 
     756        for the product of the elements. 
     757 
     758        With \code{simplify=True}, performs some simplifications 
     759        first.  If any element is formatted as a string \code{'1'}, 
     760        then it is removed from the sequence (unless it is the only 
     761        element in the sequence); and any instances of \code{a + -b}  
     762        are changed to \code{a - b}. 
     763 
     764        EXAMPLES: 
     765            sage: from sage.misc.sage_input import SageInputBuilder 
     766 
     767            sage: sib = SageInputBuilder() 
     768            sage: sib.result(sib.sum([-1, 0, 1, 0, -1])) 
     769            -1 + 0 + 1 + 0 + -1 
     770 
     771            sage: sib = SageInputBuilder() 
     772            sage: sib.result(sib.sum([-1, 0, 1, 0, -1], simplify=True)) 
     773            -1 + 1 - 1 
     774 
     775            sage: sib = SageInputBuilder() 
     776            sage: sib.result(sib.sum([0, 0, 0], simplify=True)) 
     777            0 
     778        """ 
     779        terms = [self(term) for term in terms] 
     780        if simplify: 
     781            i = 0 
     782            while i < len(terms): 
     783                term = terms[i] 
     784                if isinstance(term, SIE_literal_stringrep) and term._sie_value == '0': 
     785                    terms[i:i+1] = [] 
     786                else: 
     787                    i += 1 
     788            if len(terms) == 0: 
     789                terms.append(SIE_literal_stringrep(self, '0')) 
     790 
     791        sum = terms[0] 
     792        for term in terms[1:]: 
     793            if simplify and isinstance(term, SIE_unary) and term._sie_op == '-': 
     794                sum = sum - term._sie_operand 
     795            else: 
     796                sum = sum + term 
     797        return sum 
     798 
     799    def result(self, e): 
     800        r""" 
     801        Given a \class{SageInputExpression} constructed using \code{self}, 
     802        returns a tuple of a list of commands and an expression 
     803        (and possibly a dictionary of local variables) suitable for 
     804        \function{sage_eval}. 
     805 
     806        EXAMPLES: 
     807            sage: from sage.misc.sage_input import SageInputBuilder 
     808 
     809            sage: sib = SageInputBuilder() 
     810            sage: r = sib.result(sib(6) * sib(7)); r 
     811            6*7 
     812            sage: tuple(r) 
     813            ('', '6*7') 
     814        """ 
     815        sif = SageInputFormatter() 
     816 
     817        e._sie_prepare(sif) 
     818 
     819        s = sif.format(e, 0) 
     820 
     821        locals = self._locals 
     822        if len(locals): 
     823            return SageInputAnswer(sif._commands, sif.format(e, 0), locals) 
     824        else: 
     825            return SageInputAnswer(sif._commands, sif.format(e, 0)) 
     826 
     827# Python's precedence levels.  Hand-transcribed from section 5.14 of  
     828# the Python reference manual. 
     829_prec_lambda = 2 
     830_prec_or = 4 
     831_prec_and = 6 
     832_prec_not = 8 
     833_prec_membership = 10 
     834_prec_identity = 12 
     835_prec_comparison = 14 
     836_prec_bitor = 16 
     837_prec_bitxor = 18 
     838_prec_bitand = 20 
     839_prec_shift = 22 
     840_prec_addsub = 24 
     841_prec_muldiv = 26 
     842_prec_negate = 28 
     843_prec_not = 30 
     844_prec_exponent = 32 
     845_prec_attribute = 34 
     846_prec_subscript = 36 
     847_prec_slicing = 38 
     848_prec_funcall = 40 
     849_prec_atomic = 42 
     850 
     851class SageInputExpression(object): 
     852    r""" 
     853    Subclasses of this class represent expressions for \function{sage_input}. 
     854    \sage classes should define a \method{_sage_input_} method, which 
     855    will return an instance of \class{SageInputExpression}, created using 
     856    methods of \class{SageInputBuilder}. 
     857 
     858    To the extent possible, operations on \class{SageInputExpression} objects 
     859    construct a new \class{SageInputExpression} representing that operation. 
     860    That is, if \var{a} is a \class{SageInputExpression}, then \code{a + b} 
     861    constructs a \class{SageInputExpression} representing this sum. 
     862    This also works for attribute access, function calls, subscripts, etc. 
     863    Since arbitrary attribute accesses might be used to construct a new 
     864    attribte-access expression, all internal attributes and methods 
     865    have names that begin with \code{_sie_} to reduce the chance of 
     866    collisions. 
     867 
     868    It is expected that instances of this class will not be directly 
     869    created outside this module; instead, instances will be created 
     870    using methods of \class{SageInputBuilder} and \class{SageInputExpression}. 
     871    """ 
     872 
     873    def __init__(self, sib): 
     874        r""" 
     875        Initialize a \class{SageInputExpression}. 
     876 
     877        EXAMPLES: 
     878            sage: from sage.misc.sage_input import SageInputBuilder 
     879 
     880            sage: sib = SageInputBuilder() 
     881            sage: sie = sib(3) # indirect doctest 
     882            sage: sie._sie_builder is sib 
     883            True 
     884        """ 
     885        self._sie_refcount = 0 
     886        self._sie_builder = sib 
     887        self._sie_context = None 
     888        self._sie_preferred_varname = None 
     889        self._sie_varname = None 
     890        self._sie_use_var = False 
     891        self._sie_requested_varname = False 
     892 
     893    def _sie_is_simple(self): 
     894        r""" 
     895        Returns \code{True} if this \class{SageInputExpression} is simple 
     896        enough that duplicate uses are not worth caching.  Normally 
     897        this will be true if the expression represents a single token. 
     898 
     899        EXAMPLES: 
     900            sage: from sage.misc.sage_input import SageInputBuilder 
     901 
     902            sage: sib = SageInputBuilder() 
     903            sage: sib.name('QQ')._sie_is_simple() 
     904            True 
     905            sage: sib(GF(2))._sie_is_simple() 
     906            False 
     907        """ 
     908        return False 
     909 
     910    def _sie_referenced(self): 
     911        r""" 
     912        Returns a list of the immediate subexpressions of this 
     913        \class{SageInputExpression}. 
     914 
     915        EXAMPLES: 
     916            sage: from sage.misc.sage_input import SageInputBuilder 
     917 
     918            sage: sib = SageInputBuilder() 
     919            sage: len(sib(GF(2))._sie_referenced()) 
     920            2 
     921            sage: sib(5)._sie_referenced() 
     922            [] 
     923        """ 
     924        return [] 
     925 
     926    def _sie_prepare(self, sif): 
     927        r""" 
     928        We traverse the entire expression DAG to prepare for printing. 
     929        Here, we notice nodes with more than one parent, and mark them 
     930        to replace with a variable (rather than generating the value 
     931        multiple times). 
     932 
     933        EXAMPLES: 
     934            sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 
     935 
     936            sage: sib = SageInputBuilder() 
     937            sage: sif = SageInputFormatter() 
     938            sage: pair = sib((GF(2), GF(2))) 
     939            sage: single = sib(GF(2)) 
     940            sage: single._sie_refcount 
     941            0 
     942            sage: single._sie_use_var 
     943            False 
     944            sage: sib((GF(2), GF(2)))._sie_prepare(sif) 
     945            sage: single._sie_refcount 
     946            2 
     947            sage: single._sie_use_var 
     948            True 
     949        """ 
     950        if self._sie_context is not sif: 
     951            self._sie_context = sif 
     952            self._sie_refcount = 0 
     953        self._sie_refcount += 1 
     954        if not self._sie_is_simple(): 
     955            if self._sie_refcount == 2: 
     956                self._sie_require_varname(sif) 
     957                self._sie_use_var = True 
     958        if self._sie_refcount == 1: 
     959            for r in self._sie_referenced(): 
     960                r._sie_prepare(sif) 
     961 
     962    def _sie_require_varname(self, sif): 
     963        if not self._sie_requested_varname: 
     964            sif.register_name(self._sie_preferred_varname) 
     965            self._sie_requested_varname = True 
     966            self._sie_generated = False 
     967 
     968    def _sie_get_varname(self, sif): 
     969        if self._sie_varname is None: 
     970            self._sie_varname = sif.get_name(self._sie_preferred_varname) 
     971 
     972        return self._sie_varname 
     973 
     974    def __call__(self, *args, **kwargs): 
     975        args = map(self._sie_builder, args) 
     976        for k in kwargs: 
     977            kwargs[k] = self._sie_builder(kwargs[k]) 
     978        return SIE_call(self._sie_builder, self, args, kwargs) 
     979             
     980    def __getitem__(self, key): 
     981        skey = self._sie_builder(key) 
     982        return SIE_subscript(self._sie_builder, self, skey) 
     983 
     984    def __pow__(self, other): 
     985        return self._sie_binop('**', other) 
     986 
     987    def __mul__(self, other): 
     988        return self._sie_binop('*', other) 
     989 
     990    def __div__(self, other): 
     991        return self._sie_binop('/', other) 
     992 
     993    def __add__(self, other): 
     994        return self._sie_binop('+', other) 
     995 
     996    def __sub__(self, other): 
     997        return self._sie_binop('-', other) 
     998