Makefileの修正
[YACASL2.git] / src / cerr.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <stdbool.h>
6 #include "cerr.h"
7
8 /**
9  * エラーの初期化
10  */
11 void cerr_init()
12 {
13     cerr = malloc_chk(sizeof(CERR), "cerr");
14     cerr->num = 0;
15 }
16
17 /**
18  * 現在のエラー
19  */
20 CERR *cerr;
21
22 /**
23  * エラーリスト
24  */
25 CERRLIST *cerrlist = NULL;
26
27 /**
28  * エラーリストを作成または追加する
29  */
30 void addcerrlist(int errc, CERR errv[])
31 {
32     int i;
33     CERRLIST *p = NULL, *q = malloc_chk(sizeof(CERRLIST), "cerrlist");
34
35     assert(errc > 0 && errv != NULL);
36     for(i = 0; i < errc; i++) {
37         if(p == NULL) {
38             p = q;
39         } else {
40             p = p->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
41         }
42         p->cerr = &errv[i];
43         p->next = NULL;
44     }
45     p->next = cerrlist;
46     cerrlist = q;
47 }
48
49 /**
50  * エラーリストを表示する
51  */
52 void printcerrlist()
53 {
54     CERRLIST *p;
55
56     if(cerrlist == NULL) {
57         puts("error list is null.");
58     } else {
59         for(p = cerrlist; p != NULL; p = p->next) {
60             printf("%d: %s\n", p->cerr->num, p->cerr->msg);
61         }
62     }
63 }
64
65 /**
66  * 現在のエラーを設定する
67  */
68 void setcerr(int num, const char *str)
69 {
70     /* 現在のエラー番号を設定  */
71     cerr->num = num;
72     /* 現在のエラーメッセージを設定 */
73     cerr->msg = malloc_chk(CERRMSGSIZE + 1, "cerr.msg");
74     if(0 < strlen(str) && strlen(str) <= CERRSTRSIZE) {
75         sprintf(cerr->msg, "%s: %s", str, getcerrmsg(cerr->num));
76     } else {
77         strcpy(cerr->msg, getcerrmsg(cerr->num));
78     }
79 }
80
81 /**
82  * エラーリストから、エラー番号に対応するメッセージを返す
83  */
84 char *getcerrmsg(int num)
85 {
86     CERRLIST *p;
87     char *msg = "unknown error";
88
89     for(p = cerrlist; p != NULL; p = p->next) {
90         if(num == p->cerr->num) {
91             msg = p->cerr->msg;
92             break;
93         }
94     }
95     return msg;
96 }
97
98 /**
99  * エラーリストと現在のエラーを解放する
100  */
101 void freecerr()
102 {
103     CERRLIST *p = cerrlist, *q;
104
105     /* 現在のエラーメッセージを解放 */
106     FREE(cerr->msg);
107     /* 現在のエラーを解放 */
108     FREE(cerr);
109     /* エラーリストを解放 */
110     for(p = cerrlist; p != NULL; p = q) {
111         q = p->next;
112         FREE(p);
113     }
114 }