xref: /freebsd/usr.bin/dc/bcode.h (revision 7899f917b1c0ea178f1d2be0cfb452086d079d23)
1 /*	$OpenBSD: bcode.h,v 1.7 2012/11/07 11:06:14 otto Exp $	*/
2 
3 /*
4  * Copyright (c) 2003, Otto Moerbeek <otto@drijf.net>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <openssl/bn.h>
21 
22 struct number {
23 	BIGNUM	*number;
24 	u_int	 scale;
25 };
26 
27 enum stacktype {
28 	BCODE_NONE,
29 	BCODE_NUMBER,
30 	BCODE_STRING
31 };
32 
33 enum bcode_compare {
34 	BCODE_EQUAL,
35 	BCODE_NOT_EQUAL,
36 	BCODE_LESS,
37 	BCODE_NOT_LESS,
38 	BCODE_GREATER,
39 	BCODE_NOT_GREATER
40 };
41 
42 struct array;
43 
44 struct value {
45 	union {
46 		struct number	*num;
47 		char		*string;
48 	} u;
49 	struct array	*array;
50 	enum stacktype	 type;
51 };
52 
53 struct array {
54 	struct value	*data;
55 	size_t		 size;
56 };
57 
58 struct stack {
59 	struct value	*stack;
60 	ssize_t		 size;
61 	ssize_t		 sp;
62 };
63 
64 struct source;
65 
66 struct vtable {
67 	int	(*readchar)(struct source *);
68 	void	(*unreadchar)(struct source *);
69 	char	*(*readline)(struct source *);
70 	void	(*free)(struct source *);
71 };
72 
73 struct source {
74 	union {
75 			struct {
76 				u_char	*buf;
77 				size_t	 pos;
78 			} string;
79 			FILE	*stream;
80 	} u;
81 	struct vtable	*vtable;
82 	int		 lastchar;
83 };
84 
85 void			init_bmachine(bool);
86 void			reset_bmachine(struct source *);
87 u_int			bmachine_scale(void);
88 void			scale_number(BIGNUM *, int);
89 void			normalize(struct number *, u_int);
90 void			eval(void);
91 void			pn(const char *, const struct number *);
92 void			pbn(const char *, const BIGNUM *);
93 void			negate(struct number *);
94 void			split_number(const struct number *, BIGNUM *, BIGNUM *);
95 void			bmul_number(struct number *, struct number *,
96 			    struct number *, u_int scale);
97 
98 static __inline u_int
99 max(u_int a, u_int b)
100 {
101 
102 	return (a > b ? a : b);
103 }
104