blob: ebf2fb1427faa37f9b8e69dd67554588ea6b67e3 [file] [log] [blame]
Lev Walkinf15320b2004-06-03 03:38:44 +00001#include "asn1c_internal.h"
Lev Walkin59004fa2004-08-20 13:37:01 +00002#include "asn1c_out.h"
Lev Walkinf15320b2004-06-03 03:38:44 +00003
4/*
5 * Add an elementary chunk of target language text
6 * into appropriate output stream.
7 */
8int
9asn1c_compiled_output(arg_t *arg, const char *fmt, ...) {
Lev Walkin59004fa2004-08-20 13:37:01 +000010 struct compiler_stream_destination_s *dst;
Lev Walkinf15320b2004-06-03 03:38:44 +000011 const char *p;
12 int lf_found;
13 va_list ap;
14 out_chunk_t *m;
15 char *buf;
16 int ret;
17
Lev Walkin64399722004-08-11 07:17:22 +000018 switch(arg->target->target) {
19 case OT_IGNORE:
20 return 0;
Lev Walkin64399722004-08-11 07:17:22 +000021 default:
Lev Walkin59004fa2004-08-20 13:37:01 +000022 dst = &arg->target->destination[arg->target->target];
Lev Walkin64399722004-08-11 07:17:22 +000023 break;
24 }
25
Lev Walkinf15320b2004-06-03 03:38:44 +000026 /*
27 * Make sure the output has a single LF and only at the end.
28 */
29 for(lf_found = 0, p = fmt; *p; p++) {
30 if(*p == '\n') {
31 lf_found++;
32 assert(p[1] == '\0');
33 }
34 }
35 assert(lf_found <= 1);
36
37 /*
38 * Print out the indentation.
39 */
Lev Walkin59004fa2004-08-20 13:37:01 +000040 if(dst->indented == 0) {
41 int i = dst->indent_level;
42 dst->indented = 1;
Lev Walkinf15320b2004-06-03 03:38:44 +000043 while(i--) {
44 ret = asn1c_compiled_output(arg, "\t");
45 if(ret == -1) return -1;
46 }
47 }
Lev Walkin3dcaafa2004-08-11 05:21:32 +000048 if(lf_found)
Lev Walkin59004fa2004-08-20 13:37:01 +000049 dst->indented = 0;
Lev Walkinf15320b2004-06-03 03:38:44 +000050
51 /*
52 * Estimate necessary size.
53 */
54 buf = "";
55 va_start(ap, fmt);
56 ret = vsnprintf(buf, 0, fmt, ap);
57 va_end(ap);
58 assert(ret >= 0);
59
60 /*
61 * Allocate buffer.
62 */
63 m = calloc(1, sizeof(out_chunk_t));
64 if(m == NULL) return -1;
65 m->len = ret + 1;
66 m->buf = malloc(ret + 1);
67 if(m->buf == NULL) {
68 free(m);
69 return -1;
70 }
71
72 /*
73 * Fill the buffer.
74 */
75 va_start(ap, fmt);
76 ret = vsnprintf(m->buf, m->len, fmt, ap);
77 assert(ret < m->len);
78 m->len = ret;
79 va_end(ap);
80
Lev Walkin3dcaafa2004-08-11 05:21:32 +000081 if(arg->target->target == OT_INCLUDES) {
82 out_chunk_t *v;
Lev Walkin59004fa2004-08-20 13:37:01 +000083 TQ_FOR(v, &dst->chunks, next) {
Lev Walkin3dcaafa2004-08-11 05:21:32 +000084 if(m->len == v->len
85 && !memcmp(m->buf, v->buf, m->len))
86 break;
87 }
88 if(v) {
89 /* Entry is already present. Skip it. */
90 free(m->buf);
91 free(m);
92 return 0;
93 }
94 }
Lev Walkinf15320b2004-06-03 03:38:44 +000095
Lev Walkin59004fa2004-08-20 13:37:01 +000096 TQ_ADD(&dst->chunks, m, next);
Lev Walkinf15320b2004-06-03 03:38:44 +000097
98 return 0;
99}