Upload Tizen:Base source
[external/gmp.git] / demos / expr / exprqa.c
1 /* mpq expression evaluation
2
3 Copyright 2000, 2001, 2004 Free Software Foundation, Inc.
4
5 This file is part of the GNU MP Library.
6
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
11
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
15 License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
19
20
21 #include <stdio.h>
22 #include "gmp.h"
23 #include "expr-impl.h"
24
25
26 static int
27 e_mpq_ulong_p (mpq_srcptr q)
28 {
29   return mpz_fits_ulong_p (mpq_numref (q))
30     && mpz_cmp_ui (mpq_denref (q), 1L) == 0;
31 }
32
33 /* get value as a ui, on the assumption it fits */
34 static int
35 e_mpq_get_ui_fits (mpq_srcptr q)
36 {
37   return mpz_get_ui (mpq_numref (q));
38 }
39
40 static void
41 e_mpq_set_si1 (mpq_ptr q, long num)
42 {
43   mpq_set_si (q, num, 1L);
44 }
45
46 /* The same as mpz, but putting the result in the numerator.  Negatives and
47    fractions aren't parsed here because '-' and '/' are operators. */
48 static size_t
49 e_mpq_number (mpq_ptr res, __gmp_const char *e, size_t elen, int base)
50 {
51   mpz_set_ui (mpq_denref (res), 1L);
52   return mpexpr_mpz_number (mpq_numref (res), e, elen, base);
53 }
54
55
56 /* ignoring prec */
57 static void
58 e_mpq_init (mpq_ptr q, unsigned long prec)
59 {
60   mpq_init (q);
61 }
62
63 int
64 mpq_expr_a (__gmp_const struct mpexpr_operator_t *table,
65             mpq_ptr res, int base,
66             __gmp_const char *e, size_t elen,
67             mpq_srcptr var[26])
68 {
69   struct mpexpr_parse_t  p;
70
71   p.table = table;
72   p.res = (mpX_ptr) res;
73   p.base = base;
74   p.e = e;
75   p.elen = elen;
76   p.var = (mpX_srcptr *) var;
77
78   p.mpX_clear       = (mpexpr_fun_one_t)      mpq_clear;
79   p.mpX_ulong_p     = (mpexpr_fun_i_unary_t)  e_mpq_ulong_p;
80   p.mpX_get_ui      = (mpexpr_fun_get_ui_t)   e_mpq_get_ui_fits;
81   p.mpX_init        = (mpexpr_fun_unary_ui_t) e_mpq_init;
82   p.mpX_number      = (mpexpr_fun_number_t)   e_mpq_number;
83   p.mpX_set         = (mpexpr_fun_unary_t)    mpq_set;
84   p.mpX_set_or_swap = (mpexpr_fun_unary_t)    mpq_swap;
85   p.mpX_set_si      = (mpexpr_fun_set_si_t)   e_mpq_set_si1;
86   p.mpX_swap        = (mpexpr_fun_swap_t)     mpq_swap;
87
88   return mpexpr_evaluate (&p);
89 }