Ticket #3485: trac3485-sage_input.patch

File trac3485-sage_input.patch, 55.0 KB (added by Carl Witty, 14 years ago)
  • sage/misc/all.py

    # HG changeset patch
    # User Carl Witty <cwitty@newtonlabs.com>
    # Date 1213949780 25200
    # Node ID a2684035955c2768673b1022ee8c9bdc9f8d8b25
    # Parent  c6e08573f2aa9661f9d90c34e76c4e1191a80b83
    new sage_input framework
    
    diff -r c6e08573f2aa -r a2684035955c sage/misc/all.py
    a b  
    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
  • new file sage/misc/sage_input.py

    diff -r c6e08573f2aa -r a2684035955c sage/misc/sage_input.py
    - +  
     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
     999    def _sie_binop(self, op, other):
     1000        return SIE_binary(self._sie_builder, op, self, self._sie_builder(other))
     1001
     1002    def __neg__(self):
     1003        return self._sie_unop('-')
     1004
     1005    def _sie_unop(self, op):
     1006        return SIE_unary(self._sie_builder, op, self)
     1007
     1008class SIE_literal(SageInputExpression):
     1009    def _sie_is_simple(self):
     1010        return True
     1011
     1012class SIE_literal_stringrep(SIE_literal):
     1013    def __init__(self, sib, n):
     1014        super(SIE_literal_stringrep, self).__init__(sib)
     1015        self._sie_value = str(n)
     1016
     1017    def _sie_format(self, sif):
     1018        return self._sie_value, _prec_atomic
     1019       
     1020class SIE_call(SageInputExpression):
     1021    def __init__(self, sib, func, args, kwargs):
     1022        super(SIE_call, self).__init__(sib)
     1023        self._sie_func = func
     1024        self._sie_args = args
     1025        self._sie_kwargs = kwargs
     1026
     1027    def _sie_referenced(self):
     1028        refs = self._sie_args[:]
     1029        refs.append(self._sie_func)
     1030        refs.extend(self._sie_kwargs.itervalues())
     1031        return refs
     1032
     1033    def _sie_format(self, sif):
     1034        func = sif.format(self._sie_func, _prec_attribute)
     1035        args = [sif.format(arg, 0) for arg in self._sie_args]
     1036        kwargs = sorted(k + '=' + sif.format(v, 0) for k, v in self._sie_kwargs.iteritems())
     1037        all_args = ', '.join(args + kwargs)
     1038        return ('%s(%s)' % (func, all_args), _prec_funcall)
     1039
     1040class SIE_subscript(SageInputExpression):
     1041    def __init__(self, sib, coll, key):
     1042        super(SIE_subscript, self).__init__(sib)
     1043        self._sie_coll = coll
     1044        self._sie_key = key
     1045
     1046    def _sie_referenced(self):
     1047        refs = [self._sie_coll]
     1048        if self._sie_key is not None:
     1049            refs.append(self._sie_key)
     1050        return refs
     1051
     1052    def _sie_format(self, sif):
     1053        coll = sif.format(self._sie_coll, _prec_attribute)
     1054        if self._sie_key is None:
     1055            key = ''
     1056        else:
     1057            key = sif.format(self._sie_key, 0)
     1058        return '%s[%s]' % (coll, key), _prec_subscript
     1059
     1060class SIE_tuple(SageInputExpression):
     1061    def __init__(self, sib, values):
     1062        super(SIE_tuple, self).__init__(sib)
     1063        self._sie_values = values
     1064
     1065    def _sie_referenced(self):
     1066        return self._sie_values
     1067
     1068    def _sie_format(self, sif):
     1069        values = [sif.format(val, 0) for val in self._sie_values]
     1070        if len(values) == 1:
     1071            return '(%s,)' % values[0], _prec_atomic
     1072        else:
     1073            return '(%s)' % ', '.join(values), _prec_atomic
     1074
     1075class SIE_binary(SageInputExpression):
     1076    def __init__(self, sib, op, lhs, rhs):
     1077        super(SIE_binary, self).__init__(sib)
     1078        self._sie_op = op
     1079        self._sie_operands = (lhs, rhs)
     1080
     1081    def _sie_referenced(self):
     1082        return self._sie_operands
     1083
     1084    def _sie_format(self, sif):
     1085        op = self._sie_op
     1086        fop = op
     1087        if op == '**':
     1088            lhs = sif.format(self._sie_operands[0], _prec_exponent+1)
     1089            rhs = sif.format(self._sie_operands[1], _prec_exponent)
     1090            if self._sie_builder.preparse():
     1091                return '%s^%s' % (lhs, rhs), _prec_exponent
     1092            else:
     1093                return '%s**%s' % (lhs, rhs), _prec_exponent
     1094
     1095        if op == '*':
     1096            prec = _prec_muldiv
     1097        elif op == '/':
     1098            prec = _prec_muldiv
     1099        elif op == '+':
     1100            fop = ' + '
     1101            prec = _prec_addsub
     1102        elif op == '-':
     1103            fop = ' - '
     1104            prec = _prec_addsub
     1105        else:
     1106            raise ValueError, 'Unhandled op %s in SIE_binary' % op
     1107
     1108        lhs = sif.format(self._sie_operands[0], prec)
     1109        rhs = sif.format(self._sie_operands[1], prec+1)
     1110        return '%s%s%s' % (lhs, fop, rhs), prec
     1111
     1112class SIE_unary(SageInputExpression):
     1113    def __init__(self, sib, op, operand):
     1114        super(SIE_unary, self).__init__(sib)
     1115        self._sie_op = op
     1116        self._sie_operand = operand
     1117
     1118    def _sie_referenced(self):
     1119        return [self._sie_operand]
     1120
     1121    def _sie_format(self, sif):
     1122        op = self._sie_op
     1123        fop = op
     1124        rprec = None
     1125        if op == '-':
     1126            # We print -(a*b) as -a*b, even though that will parse as
     1127            # (-a)*b.
     1128            prec = _prec_muldiv
     1129            rprec = _prec_negate
     1130        else:
     1131            raise ValueError, 'Unhandled op %s in SIE_unary' % op
     1132           
     1133        if rprec is None: rprec = prec
     1134
     1135        return '%s%s' % (fop, sif.format(self._sie_operand, prec)), rprec
     1136
     1137class SIE_gens_constructor(SageInputExpression):
     1138    def __init__(self, sib, constr, gen_names, gens_syntax=None):
     1139        super(SIE_gens_constructor, self).__init__(sib)
     1140        self._sie_constr = constr
     1141        self._sie_gen_names = gen_names
     1142        self._sie_gens = None # will be overwritten from .parent_with_gens()
     1143        self._sie_gens_constr = gens_syntax
     1144        self._sie_assign_gens = False
     1145        self._sie_generated = False
     1146
     1147    def _sie_referenced(self):
     1148        return [self._sie_constr]
     1149           
     1150    def _sie_gens_referenced(self, sif):
     1151        self._sie_assign_gens = True
     1152        self._sie_require_varname(sif)
     1153        for gen in self._sie_gens:
     1154            gen._sie_require_varname(sif)
     1155
     1156    def _sie_add_command(self, sif):
     1157        if not self._sie_generated:
     1158            if self._sie_builder.preparse() and \
     1159                    self._sie_gens_constr is not None and \
     1160                    all(g._sie_got_preferred(sif) for g in self._sie_gens):
     1161                s, _ = self._sie_gens_constr._sie_format(sif)
     1162                sif._commands += '%s.<%s> = %s\n' % (self._sie_get_varname(sif), ','.join(self._sie_gen_names), s)
     1163            else:
     1164                s, _ = self._sie_constr._sie_format(sif)
     1165                sif._commands += '%s = %s\n' % (self._sie_get_varname(sif), s)
     1166                if self._sie_assign_gens:
     1167                    if len(self._sie_gens) == 1:
     1168                        sif._commands += '%s = %s.gen()\n' % (self._sie_gens[0]._sie_get_varname(sif), self._sie_get_varname(sif))
     1169                    else:
     1170                        sif._commands += '%s = %s.gens()\n' % (','.join([g._sie_get_varname(sif) for g in self._sie_gens]), self._sie_get_varname(sif))
     1171            self._sie_generated = True
     1172       
     1173    def _sie_format(self, sif):
     1174        if self._sie_assign_gens:
     1175            self._sie_add_command(sif)
     1176            return self._sie_get_varname(sif), _prec_atomic
     1177
     1178        return self._sie_constr._sie_format(sif)
     1179
     1180class SIE_gen(SageInputExpression):
     1181    def __init__(self, sib, parent, name):
     1182        super(SIE_gen, self).__init__(sib)
     1183        self._sie_parent = parent
     1184        self._sie_preferred_varname = name
     1185
     1186    def _sie_is_simple(self):
     1187        return True
     1188
     1189    def _sie_prepare(self, sif):
     1190        super(SIE_gen, self)._sie_prepare(sif)
     1191        self._sie_parent._sie_gens_referenced(sif)
     1192
     1193    def _sie_referenced(self):
     1194        return []
     1195
     1196    def _sie_format(self, sif):
     1197        self._sie_parent._sie_add_command(sif)
     1198        return self._sie_get_varname(sif), _prec_atomic
     1199
     1200    def _sie_got_preferred(self, sif):
     1201        return self._sie_get_varname(sif) == self._sie_preferred_varname
     1202
     1203class SageInputFormatter:
     1204    def __init__(self):
     1205        self._commands = ''
     1206        self._names = set()
     1207        self._dup_names = {}
     1208
     1209    def format(self, e, prec):
     1210        if e._sie_use_var:
     1211            if not e._sie_generated:
     1212                s, _ = e._sie_format(self)
     1213                self._commands += '%s = %s\n' % (e._sie_get_varname(self), s)
     1214                e._sie_generated = True
     1215
     1216            return e._sie_get_varname(self)
     1217
     1218        s, iprec = e._sie_format(self)
     1219        if iprec < prec:
     1220            s = '(' + s + ')'
     1221        return s
     1222
     1223    def register_name(self, name):
     1224        if name is None: name = 'si'
     1225
     1226        if name in self._names:
     1227            self._dup_names[name] = 0
     1228        else:
     1229            self._names.add(name)
     1230
     1231    def get_name(self, name):
     1232        if name is None: name = 'si'
     1233
     1234        if name in self._dup_names:
     1235            next = self._dup_names[name] + 1
     1236            self._dup_names[name] = next
     1237            return name + str(next)
     1238        else:
     1239            return name
     1240
     1241def verify_same(a, b):
     1242    from sage.structure.element import is_Element
     1243    if is_Element(a):
     1244        assert(a.parent() == b.parent())
     1245    else:
     1246        assert(type(a) == type(b))
     1247    assert(a == b)               
     1248
     1249def verify_si_answer(x, answer, preparse):
     1250    from sage.misc.sage_eval import sage_eval
     1251    if preparse is None:
     1252        verify_same(x, sage_eval(answer, preparse=True))
     1253        verify_same(x, sage_eval(answer, preparse=False))
     1254    else:
     1255        verify_same(x, sage_eval(answer, preparse=preparse))
     1256
     1257class SageInputAnswer(tuple):
     1258    def __new__(cls, cmds, expr, locals=None):
     1259        if locals:
     1260            return tuple.__new__(cls, (cmds, expr, locals))
     1261        else:
     1262            return tuple.__new__(cls, (cmds, expr))
     1263
     1264    def __repr__(self):
     1265        if len(self) == 2:
     1266            return self[0] + self[1]
     1267
     1268        locals = self[2]
     1269        locals_text = ''.join('  %s: %r\n' % (k, v) for k, v in locals.iteritems())
     1270        return 'LOCALS:\n' + locals_text + self[0] + self[1]
     1271   
  • sage/rings/integer.pyx

    diff -r c6e08573f2aa -r a2684035955c sage/rings/integer.pyx
    a b  
    29272927        """
    29282928        return str(self)
    29292929
     2930    def _sage_input_(self, sib, coerced):
     2931        if coerced or sib.preparse():
     2932            return sib.int(self)
     2933        else:
     2934            if self < 0:
     2935                return -sib.name('ZZ')(sib.int(-self))
     2936            else:
     2937                return sib.name('ZZ')(sib.int(self))
     2938
    29302939    def isqrt(self):
    29312940        r"""
    29322941        Returns the integer floor of the square root of self, or raises
  • sage/rings/integer_mod.pyx

    diff -r c6e08573f2aa -r a2684035955c sage/rings/integer_mod.pyx
    a b  
    362362            1
    363363        """
    364364        return '%s!%s'%(self.parent()._magma_init_(), self)
     365
     366    def _sage_input_(self, sib, coerced):
     367        v = sib.int(self.lift())
     368        if coerced:
     369            return v
     370        else:
     371            return sib(self.parent())(v)
    365372
    366373    def log(self, b=None):
    367374        r"""
  • sage/rings/integer_ring.pyx

    diff -r c6e08573f2aa -r a2684035955c sage/rings/integer_ring.pyx
    a b  
    815815        """
    816816        return 'IntegerRing()'
    817817
     818    def _sage_input_(self, sib, coerced):
     819        return sib.name('ZZ')
     820
    818821ZZ = IntegerRing_class()
    819822Z = ZZ
    820823
  • sage/rings/polynomial/polynomial_element.pyx

    diff -r c6e08573f2aa -r a2684035955c sage/rings/polynomial/polynomial_element.pyx
    a b  
    11351135            return "0"
    11361136        return s[1:].lstrip().rstrip()
    11371137       
     1138    def _sage_input_(self, sib, coerced):
     1139        if self.degree() > 0:
     1140            gen = sib.gen(self.parent())
     1141            coeffs = self.list()
     1142            terms = []
     1143            for i in range(len(coeffs)-1, -1, -1):
     1144                if i > 0:
     1145                    if i > 1:
     1146                        gen_pow = gen**sib.int(i)
     1147                    else:
     1148                        gen_pow = gen
     1149                    terms.append(sib.prod((sib(coeffs[i], True), gen_pow), simplify=True))
     1150                else:
     1151                    terms.append(sib(coeffs[i], True))
     1152            return sib.sum(terms, simplify=True)
     1153        elif coerced:
     1154            return sib(self.constant_coefficient(), True)
     1155        else:
     1156            return sib(self.parent())(sib(self.constant_coefficient(), True))
    11381157       
    11391158    def __setitem__(self, n, value):
    11401159        """
  • sage/rings/polynomial/polynomial_ring.py

    diff -r c6e08573f2aa -r a2684035955c sage/rings/polynomial/polynomial_ring.py
    a b  
    375375
    376376    def _gap_init_(self):
    377377        return 'PolynomialRing(%s, ["%s"])'%(self.base_ring()._gap_init_(), self.variable_name())
     378
     379    def _sage_input_(self, sib, coerced):
     380        base = sib(self.base_ring())
     381        sie = base[self.variable_name()]
     382        gens_syntax = sib.empty_subscript(base)
     383        return sib.parent_with_gens(self, sie, self.variable_names(), 'R',
     384                                    gens_syntax=gens_syntax)
    378385
    379386    def _is_valid_homomorphism_(self, codomain, im_gens):
    380387        try:
  • sage/rings/real_mpfr.pyx

    diff -r c6e08573f2aa -r a2684035955c sage/rings/real_mpfr.pyx
    a b  
    268268
    269269    def _latex_(self):
    270270        return "\\mathbf{R}"
     271
     272    def _sage_input_(self, sib, coerce):
     273        if self.rnd == GMP_RNDN and self.prec() == 53:
     274            return sib.name('RR')
     275
     276        if self.rnd != GMP_RNDN:
     277            rnd_abbrev = self.rnd_str[-1:].lower()
     278            v = sib.name('RealField')(sib.int(self.prec()), rnd=self.rnd_str)
     279        else:
     280            rnd_abbrev = ''
     281            v = sib.name('RealField')(sib.int(self.prec()))
     282
     283        name = 'RR%d%s' % (self.prec(), rnd_abbrev)
     284        sib.cache(self, v, name)
     285        return v
    271286
    272287    def is_exact(self):
    273288        return False
     
    912927            True
    913928        """
    914929        return self.str(10, no_sci=True, truncate=False)
     930
     931    def _sage_input_(self, sib, coerced):
     932        # We have a bewildering array of conditions to deal with:
     933        # 1) number, or NaN or infinity
     934        # 2) rounding direction: up, down, or nearest
     935        # 3) preparser enabled: yes, no, or maybe
     936        # 4) is this number equal to some Python float: yes or no
     937        # 5) coerced
     938
     939        # First, handle NaN and infinity
     940        if not mpfr_number_p(self.value):
     941            if mpfr_inf_p(self.value):
     942                v = sib.name('Infinity')
     943                if mpfr_sgn(self.value) < 0:
     944                    v = -v
     945            else:
     946                v = sib.name('NaN')
     947            if not coerced:
     948                v = sib(self._parent)(v)
     949            return v
     950               
     951        from sage.rings.integer_ring import ZZ
     952
     953        cdef mpfr_rnd_t rnd = (<RealField>self._parent).rnd
     954
     955        cdef bint negative = mpfr_sgn(self.value) < 0
     956        if negative:
     957            self = -self
     958
     959        # There are five possibilities for printing this floating-point
     960        # number, ordered from prettiest to ugliest (IMHO).
     961        # 1) An integer: 42
     962        # 2) A simple literal: 3.14159
     963        # 3) A coerced integer: RR(42)
     964        # 4) A coerced literal: RR(3.14159)
     965        # 5) A coerced string literal: RR('3.14159')
     966
     967        # To use choice 1 or choice 3, this number must be an integer.
     968        cdef bint can_use_int_literal = \
     969            self.abs() < (Integer(1) << self.prec()) and self in ZZ
     970
     971        # To use choice 2 or choice 4, we must be able to read
     972        # numbers of this precision as a literal.
     973        cdef bint can_use_float_literal = sib.preparse() or float(self) == self
     974
     975        if can_use_int_literal or can_use_float_literal:
     976            if can_use_int_literal:
     977                v = sib.int(self._integer_())
     978            else:
     979                # If we use a floating-point literal, then it will actually be
     980                # read in round-to-nearest mode.
     981                if rnd != GMP_RNDN:
     982                    s = RealField(self.prec())(self).str(truncate=False)
     983                else:
     984                    s = self.str(truncate=False)
     985                v = sib.float_str(s)
     986            if not coerced:
     987                v = sib(self.parent())(v)
     988        else:
     989            if rnd == GMP_RNDN:
     990                s = self.str(truncate=False)
     991            else:
     992                # This is tricky.  str() uses mpfr_get_str() with
     993                # reqdigits=0; this guarantees to give enough digits
     994                # to recreate the input, if we print and read with
     995                # round-to-nearest.  However, we are not going to
     996                # read with round-to-nearest, so we might need more digits.
     997                # If we're going to read with round-down, then we need
     998                # to print with round-up; and we'll use one more bit
     999                # to make sure we have enough digits.
     1000                # Since we always read nonnegative numbers, reading with
     1001                # RNDZ is the same as reading with RNDD.
     1002                if rnd == GMP_RNDD or rnd == GMP_RNDZ:
     1003                    fld = RealField(self.prec() + 1, 'RNDU')
     1004                else:
     1005                    fld = RealField(self.prec() + 1, 'RNDD')
     1006                s = fld(self).str(truncate=False)
     1007            v = sib(self.parent())(sib.str(s))
     1008
     1009        if negative:
     1010            v = -v
     1011
     1012        return v           
    9151013
    9161014    def __hash__(self):
    9171015        """
  • sage/rings/ring.pyx

    diff -r c6e08573f2aa -r a2684035955c sage/rings/ring.pyx
    a b  
    15051505        p = self.polynomial()
    15061506        return "ext< %s | %s >"%(B._magma_init_(),p._magma_init_())
    15071507   
     1508    def _sage_input_(self, sib, coerced):
     1509        if self.degree() == 1:
     1510            v = sib.name('GF')(sib.int(self.characteristic()))
     1511            name = 'GF_%d' % self.characteristic()
     1512        else:
     1513            v = sib.name('GF')(sib.int(self.characteristic()) ** sib.int(self.degree()),
     1514                               self.variable_name(),
     1515                               self.modulus())
     1516            name = 'GF_%d_%d' % (self.characteristic(), self.degree())
     1517        sib.cache(self, v, name)
     1518        return v
     1519
    15081520    cdef int _cmp_c_impl(left, Parent right) except -2:
    15091521        """
    15101522        Compares this finite field with other.