Ticket #3485: trac3485-sage_input-v2.patch

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