summaryrefslogtreecommitdiff
path: root/src/runtime/c/utils/pgf-service.c
blob: bc9d8f9237b3b229c2a43fa5d278474f2fc4a832 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#include <stdarg.h>
#include <gu/map.h>
#include <gu/dump.h>
#include <gu/log.h>
#include <gu/enum.h>
#include <gu/file.h>
#include <pgf/pgf.h>
#include <pgf/data.h>
#include <pgf/parser.h>
#include <pgf/lexer.h>
#include <pgf/literals.h>
#include <pgf/linearize.h>
#include <pgf/expr.h>

#define NO_FCGI_DEFINES
#include <fcgi_stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define ISXDIGIT(c) ( \
    (c >= 48 && c <= 57) || \
    ((c & ~0x20) >= 65 && (c & ~0x20) <= 70) \
)
  
void
url_escape(char *str)
{
    char *pr = str, *pw = str;
    size_t len = strlen(str);
    
    for (;;) {
        if ((pr - str) >= len)
            break;

        if (*pr == '%' &&
            ((pr - str)+2) < len &&
            ISXDIGIT(*(pr+1)) &&
            ISXDIGIT(*(pr+2))) 
		{
            pr++;

			char hexstr[3];
            hexstr[0] = *pr++;
            hexstr[1] = *pr++;
            hexstr[2] = 0;

			char *ptr;
            int ch = strtoul(hexstr, &ptr, 16);
            *pw++ = (char) (ch & 0x7f);
        }
        else if(*pr == '+') {
            *pw++ = ' ';
        }
        else {
			*pw++ = *pr++;
		}
	}

    *pw++ = 0;
}

static int
generate_graphviz_expr(PgfExpr expr, int *pid,
                       GuWriter* wtr, GuExn* err, GuPool* pool)
{
	int id;
	
	GuVariantInfo ei = gu_variant_open(expr);
	switch (ei.tag) {
	case PGF_EXPR_FUN: {
		PgfExprFun* fun = ei.data;
		id = (*pid)++;
		gu_printf(wtr, err, "n%d[label = \"", id);
		gu_string_write(fun->fun, wtr, err);
		gu_puts("\", style = \"solid\", shape = \"plaintext\"]\n", wtr, err);
		break;
	}
	case PGF_EXPR_APP: {
		PgfExprApp* app = ei.data;
		id = generate_graphviz_expr(app->fun, pid, wtr, err, pool);
		int arg_id = generate_graphviz_expr(app->arg, pid, wtr, err, pool);
		gu_printf(wtr, err, "n%d -- n%d [style = \"solid\"]\n", id, arg_id);
		break;
	}
	case PGF_EXPR_ABS:
	case PGF_EXPR_LIT: {
		PgfExprLit* lit = ei.data;
		id = (*pid)++;
		gu_printf(wtr, err, "n%d[label = \"", id);
		
		GuVariantInfo ei = gu_variant_open(lit->lit);
		switch (ei.tag) {
		case PGF_LITERAL_STR: {
			PgfLiteralStr* lit = ei.data;
			gu_puts("\\\"", wtr, err);
			gu_string_write(lit->val, wtr, err);
			gu_puts("\\\"", wtr, err);
			break;
		}
		case PGF_LITERAL_INT: {
			PgfLiteralInt* lit = ei.data;
			gu_printf(wtr, err, "%d", lit->val);
			break;
		}
		case PGF_LITERAL_FLT: {
			PgfLiteralFlt* lit = ei.data;
			gu_printf(wtr, err, "%lf", lit->val);
			break;
		}
		default:
			gu_impossible();
		}

		gu_puts("\", style = \"solid\", shape = \"plaintext\"]\n", wtr, err);
		break;
	}
	case PGF_EXPR_META:
		id = (*pid)++;
		gu_printf(wtr, err, "n%d[label = \"?\", style = \"solid\", shape = \"plaintext\"]\n", id);
		break;
	case PGF_EXPR_VAR:
	case PGF_EXPR_TYPED:
	case PGF_EXPR_IMPL_ARG:
		gu_impossible();
		break;
	default:
		gu_impossible();
	}
	
	return id;
}

static void
generate_graphviz(PgfExpr expr, GuWriter* wtr, GuExn* err, GuPool* pool)
{
	int id = 0;

	gu_puts("graph {\n", wtr, err);
	generate_graphviz_expr(expr, &id, wtr, err, pool);
	gu_puts("}", wtr, err);
}

static int
render(PgfExpr expr, GuPool* pool)
{
	int pid;
	int pc[2]; /* Parent to child pipe */
	int cp[2]; /* Child to parent pipe */
	char ch;

	/* Make pipes */
	if (pipe(pc) < 0)
		return 0;
	if (pipe(cp) < 0)
		return 0;

	/* Create a child to run command. */
	switch (pid = fork())
	{
	case -1: 
		return 0;
	case 0:
		/* Child. */
		dup2(cp[1], 1); /* Make stdout go to write
					       end of pipe. */
		dup2(pc[0], 0); /* Make stdin come from read
			 		       end of pipe. */
		close(pc[1]);
		close(cp[0]);

		char *args[] = {"dot", "-Tsvg", NULL};
		execvp(args[0], args);

		exit(1);
	default: {
		/* Parent. */
		FILE* fstream = fdopen(pc[1], "w");
		GuOut* out = gu_file_out(fstream, pool);
		GuWriter* wtr = gu_new_utf8_writer(out, pool);
		GuExn* err = gu_new_exn(NULL, gu_kind(type), pool);

		generate_graphviz(expr, wtr, err, pool);
		fclose(fstream);

		close(cp[1]);
		while (read(cp[0], &ch, 1) == 1)
		{
			FCGI_putchar(ch);
		}
		return 1;
	}
	}
}

int main ()
{
	// Create the pool that is used to allocate everything
	GuPool* pool = gu_new_pool();
	int status = EXIT_SUCCESS;

	FILE* infile = fopen("/home/krasimir/www.grammaticalframework.org/examples/PennTreebank/ParseEngAbs.pgf", "r");
	if (infile == NULL) {
		fprintf(stderr, "couldn't open the grammar\n");
		status = EXIT_FAILURE;
		goto fail;
	}

	// Create an input stream from the input file
	GuIn* in = gu_file_in(infile, pool);

	// Create an exception frame that catches all errors.
	GuExn* err = gu_new_exn(NULL, gu_kind(type), pool);

	// Read the PGF grammar.
	PgfPGF* pgf = pgf_read(in, pool, err);

	// If an error occured, it shows in the exception frame
	if (!gu_ok(err)) {
		fprintf(stderr, "Reading PGF failed\n");
		status = EXIT_FAILURE;
		goto fail_read;
	}

	GuString cat = gu_str_string("Utt", pool);
	GuString lang = gu_str_string("ParseEng", pool);
	PgfConcr* concr =
		gu_map_get(pgf->concretes, &lang, PgfConcr*);
	if (!concr) {
		status = EXIT_FAILURE;
		goto fail;
	}

	// Register a callback for the literal category Symbol
	pgf_parser_add_literal(concr, gu_str_string("Symb", pool),
	                       &pgf_nerc_literal_callback);

    while (FCGI_Accept() >= 0) {
		char* sentence = getenv("QUERY_STRING");
		if (sentence == NULL ||
		    (sentence = strchr(sentence, '=')) == NULL) {
			FCGI_printf("Content-type: text/html\r\n"
				        "\r\n"
				        "<body>Please specify a sentence to parse</body>\r\n");
		} else {
			sentence++;

			// We create a temporary pool for translating a single
			// sentence, so our memory usage doesn't increase over time.
			GuPool* ppool = gu_new_pool();

			char* tmp = gu_malloc(ppool, strlen(sentence)+2);
			strcpy(tmp, sentence);
			url_escape(tmp);
			int len = strlen(tmp);
			tmp[len] = '\n';
			tmp[len+1] = '\0';
			sentence = tmp;

			// Begin parsing a sentence of the specified category
			PgfParseState* state =
				pgf_parser_init_state(concr, cat, 0, pool);
			if (state == NULL) {
				FCGI_printf("Content-type: text/html\r\n"
				            "\r\n"
				            "<body>Couldn't begin parsing</body>");
				goto fail_request;
			}
		
			GuReader *rdr =
				gu_string_reader(gu_str_string(sentence, ppool), ppool);
			PgfLexer *lexer =
				pgf_new_lexer(rdr, ppool);

			// Tokenization
			GuExn* lex_err = gu_new_exn(NULL, gu_kind(type), ppool);
			PgfToken tok = pgf_lexer_next_token(lexer, lex_err, ppool);
			while (!gu_exn_is_raised(lex_err)) {
				// feed the token to get a new parse state
				state = pgf_parser_next_state(state, tok, ppool);
				if (!state) {
					FCGI_printf("Content-type: text/html\r\n"
								"\r\n"
								"<body>Unexpected token</body>");
					goto fail_request;
				}
				
				tok = pgf_lexer_next_token(lexer, lex_err, ppool);
			}

			// Now begin enumerating the resulting syntax trees
			GuEnum* result = pgf_parse_result(state, ppool);

			PgfExprProb* ep = gu_next(result, PgfExprProb*, ppool);

			FCGI_printf("Content-type: image/svg+xml\r\n\r\n");

			render(ep->expr, ppool);

fail_request:
			gu_pool_free(ppool);
		}
    }
    
fail_read:
	fclose(infile);
fail:
    gu_pool_free(pool);
    return status;
}