~ubuntu-branches/ubuntu/lucid/vala/lucid

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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/* valagerrormodule.vala
 *
 * Copyright (C) 2008-2009  Jürg Billeter
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *
 * Author:
 *	Jürg Billeter <j@bitron.ch>
 *	Thijs Vermeir <thijsvermeir@gmail.com>
 */

using GLib;

internal class Vala.GErrorModule : CCodeDelegateModule {
	private int current_try_id = 0;
	private int next_try_id = 0;
	private bool is_in_catch = false;

	public GErrorModule (CCodeGenerator codegen, CCodeModule? next) {
		base (codegen, next);
	}

	public override void generate_error_domain_declaration (ErrorDomain edomain, CCodeDeclarationSpace decl_space) {
		if (decl_space.add_symbol_declaration (edomain, edomain.get_cname ())) {
			return;
		}

		var cenum = new CCodeEnum (edomain.get_cname ());

		foreach (ErrorCode ecode in edomain.get_codes ()) {
			if (ecode.value == null) {
				cenum.add_value (new CCodeEnumValue (ecode.get_cname ()));
			} else {
				ecode.value.accept (codegen);
				cenum.add_value (new CCodeEnumValue (ecode.get_cname (), (CCodeExpression) ecode.value.ccodenode));
			}
		}

		decl_space.add_type_definition (cenum);

		string quark_fun_name = edomain.get_lower_case_cprefix () + "quark";

		var error_domain_define = new CCodeMacroReplacement (edomain.get_upper_case_cname (), quark_fun_name + " ()");
		decl_space.add_type_definition (error_domain_define);

		var cquark_fun = new CCodeFunction (quark_fun_name, gquark_type.data_type.get_cname ());

		decl_space.add_type_member_declaration (cquark_fun);
	}

	public override void visit_error_domain (ErrorDomain edomain) {
		generate_error_domain_declaration (edomain, source_declarations);

		if (!edomain.is_internal_symbol ()) {
			generate_error_domain_declaration (edomain, header_declarations);
		}
		if (!edomain.is_private_symbol ()) {
			generate_error_domain_declaration (edomain, internal_header_declarations);
		}

		string quark_fun_name = edomain.get_lower_case_cprefix () + "quark";

		var cquark_fun = new CCodeFunction (quark_fun_name, gquark_type.data_type.get_cname ());
		var cquark_block = new CCodeBlock ();

		var cquark_call = new CCodeFunctionCall (new CCodeIdentifier ("g_quark_from_static_string"));
		cquark_call.add_argument (new CCodeConstant ("\"" + edomain.get_lower_case_cname () + "-quark\""));

		cquark_block.add_statement (new CCodeReturnStatement (cquark_call));

		cquark_fun.block = cquark_block;
		source_type_member_definition.append (cquark_fun);
	}

	public override void visit_throw_statement (ThrowStatement stmt) {
		stmt.accept_children (codegen);

		var cfrag = new CCodeFragment ();

		// method will fail
		current_method_inner_error = true;
		var cassign = new CCodeAssignment (get_variable_cexpression ("_inner_error_"), (CCodeExpression) stmt.error_expression.ccodenode);
		cfrag.append (new CCodeExpressionStatement (cassign));

		head.add_simple_check (stmt, cfrag, true);

		stmt.ccodenode = cfrag;

		create_temp_decl (stmt, stmt.error_expression.temp_vars);
	}

	public virtual CCodeStatement return_with_exception (CCodeExpression error_expr)
	{
		var cpropagate = new CCodeFunctionCall (new CCodeIdentifier ("g_propagate_error"));
		cpropagate.add_argument (new CCodeIdentifier ("error"));
		cpropagate.add_argument (error_expr);

		var cerror_block = new CCodeBlock ();
		cerror_block.add_statement (new CCodeExpressionStatement (cpropagate));

		// free local variables
		var free_frag = new CCodeFragment ();
		append_local_free (current_symbol, free_frag, false);
		cerror_block.add_statement (free_frag);

		if (current_method is CreationMethod) {
			var cl = current_method.parent_symbol as Class;
			var unref_call = new CCodeFunctionCall (new CCodeIdentifier (cl.get_unref_function ()));
			unref_call.add_argument (new CCodeIdentifier ("self"));
			cerror_block.add_statement (new CCodeExpressionStatement (unref_call));
			cerror_block.add_statement (new CCodeReturnStatement (new CCodeConstant ("NULL")));
		} else if (current_method != null && current_method.coroutine) {
			cerror_block.add_statement (new CCodeReturnStatement (new CCodeConstant ("FALSE")));
		} else if (current_return_type is VoidType) {
			cerror_block.add_statement (new CCodeReturnStatement ());
		} else {
			cerror_block.add_statement (new CCodeReturnStatement (default_value_for_type (current_return_type, false)));
		}

		return cerror_block;
	}

	CCodeStatement uncaught_error_statement (CCodeExpression inner_error, CCodeBlock? block = null, bool unexpected = false) {
		var cerror_block = block;
		if (cerror_block == null) {
			cerror_block = new CCodeBlock ();
		}

		// free local variables
		var free_frag = new CCodeFragment ();
		append_local_free (current_symbol, free_frag, false);
		cerror_block.add_statement (free_frag);

		var ccritical = new CCodeFunctionCall (new CCodeIdentifier ("g_critical"));
		ccritical.add_argument (new CCodeConstant (unexpected ? "\"file %s: line %d: unexpected error: %s (%s, %d)\"" : "\"file %s: line %d: uncaught error: %s (%s, %d)\""));
		ccritical.add_argument (new CCodeConstant ("__FILE__"));
		ccritical.add_argument (new CCodeConstant ("__LINE__"));
		ccritical.add_argument (new CCodeMemberAccess.pointer (inner_error, "message"));
		var domain_name = new CCodeFunctionCall (new CCodeIdentifier ("g_quark_to_string"));
		domain_name.add_argument (new CCodeMemberAccess.pointer (inner_error, "domain"));
		ccritical.add_argument (domain_name);
		ccritical.add_argument (new CCodeMemberAccess.pointer (inner_error, "code"));

		var cclear = new CCodeFunctionCall (new CCodeIdentifier ("g_clear_error"));
		cclear.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, inner_error));

		var cprint_frag = new CCodeFragment ();
		cprint_frag.append (new CCodeExpressionStatement (ccritical));
		cprint_frag.append (new CCodeExpressionStatement (cclear));

		// print critical message
		cerror_block.add_statement (cprint_frag);

		if (current_method is CreationMethod) {
			cerror_block.add_statement (new CCodeReturnStatement (new CCodeConstant ("NULL")));
		} else if (current_method != null && current_method.coroutine) {
			cerror_block.add_statement (new CCodeReturnStatement (new CCodeConstant ("FALSE")));
		} else if (current_return_type is VoidType) {
			cerror_block.add_statement (new CCodeReturnStatement ());
		} else if (current_return_type != null) {
			cerror_block.add_statement (new CCodeReturnStatement (default_value_for_type (current_return_type, false)));
		}

		return cerror_block;
	}

	bool in_finally_block (CodeNode node) {
		var current_node = node;
		while (current_node != null) {
			var try_stmt = current_node.parent_node as TryStatement;
			if (try_stmt != null && try_stmt.finally_body == current_node) {
				return true;
			}
			current_node = current_node.parent_node;
		}
		return false;
	}

	public override void add_simple_check (CodeNode node, CCodeFragment cfrag, bool always_fails = false) {
		current_method_inner_error = true;

		var inner_error = get_variable_cexpression ("_inner_error_");

		CCodeStatement cerror_handler = null;

		if (current_try != null) {
			// surrounding try found
			var cerror_block = new CCodeBlock ();

			// free local variables
			var free_frag = new CCodeFragment ();
			append_error_free (current_symbol, free_frag, current_try);
			cerror_block.add_statement (free_frag);

			var error_types = new ArrayList<DataType> ();
			foreach (DataType node_error_type in node.get_error_types ()) {
				error_types.add (node_error_type);
			}

			bool has_general_catch_clause = false;

			if (!is_in_catch) {
				var handled_error_types = new ArrayList<DataType> ();
				foreach (CatchClause clause in current_try.get_catch_clauses ()) {
					// keep track of unhandled error types
					foreach (DataType node_error_type in error_types) {
						if (clause.error_type == null || node_error_type.compatible (clause.error_type)) {
							handled_error_types.add (node_error_type);
						}
					}
					foreach (DataType handled_error_type in handled_error_types) {
						error_types.remove (handled_error_type);
					}
					handled_error_types.clear ();

					// go to catch clause if error domain matches
					var cgoto_stmt = new CCodeGotoStatement (clause.clabel_name);

					if (clause.error_type.equals (gerror_type)) {
						// general catch clause, this should be the last one
						has_general_catch_clause = true;
						cerror_block.add_statement (cgoto_stmt);
						break;
					} else {
						var catch_type = clause.error_type as ErrorType;
						var cgoto_block = new CCodeBlock ();
						cgoto_block.add_statement (cgoto_stmt);

						if (catch_type.error_code != null) {
							/* catch clause specifies a specific error code */
							var error_match = new CCodeFunctionCall (new CCodeIdentifier ("g_error_matches"));
							error_match.add_argument (inner_error);
							error_match.add_argument (new CCodeIdentifier (catch_type.data_type.get_upper_case_cname ()));
							error_match.add_argument (new CCodeIdentifier (catch_type.error_code.get_cname ()));

							cerror_block.add_statement (new CCodeIfStatement (error_match, cgoto_block));
						} else {
							/* catch clause specifies a full error domain */
							var ccond = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY,
									new CCodeMemberAccess.pointer (inner_error, "domain"), new CCodeIdentifier
									(clause.error_type.data_type.get_upper_case_cname ()));

							cerror_block.add_statement (new CCodeIfStatement (ccond, cgoto_block));
						}
					}
				}
			}

			if (has_general_catch_clause) {
				// every possible error is already caught
				// as there is a general catch clause
				// no need to do anything else
			} else if (error_types.size > 0) {
				// go to finally clause if no catch clause matches
				// and there are still unhandled error types
				cerror_block.add_statement (new CCodeGotoStatement ("__finally%d".printf (current_try_id)));
			} else if (in_finally_block (node)) {
				// do not check unexpected errors happening within finally blocks
				// as jump out of finally block is not supported
			} else {
				// should never happen with correct bindings
				uncaught_error_statement (inner_error, cerror_block, true);
			}

			cerror_handler = cerror_block;
		} else if (current_method != null && current_method.get_error_types ().size > 0) {
			// current method can fail, propagate error
			CCodeBinaryExpression ccond = null;

			foreach (DataType error_type in current_method.get_error_types ()) {
				// If GLib.Error is allowed we propagate everything
				if (error_type.equals (gerror_type)) {
					ccond = null;
					break;
				}

				// Check the allowed error domains to propagate
				var domain_check = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeMemberAccess.pointer
					(inner_error, "domain"), new CCodeIdentifier (error_type.data_type.get_upper_case_cname ()));
				if (ccond == null) {
					ccond = domain_check;
				} else {
					ccond = new CCodeBinaryExpression (CCodeBinaryOperator.OR, ccond, domain_check);
				}
			}

			if (ccond == null) {
				cerror_handler = return_with_exception (inner_error);
			} else {
				var cerror_block = new CCodeBlock ();
				cerror_block.add_statement (new CCodeIfStatement (ccond,
					return_with_exception (inner_error),
					uncaught_error_statement (inner_error)));
				cerror_handler = cerror_block;
			}
		} else {
			cerror_handler = uncaught_error_statement (inner_error);
		}

		if (always_fails) {
			// inner_error is always set, avoid unnecessary if statement
			// eliminates C warnings
			cfrag.append (cerror_handler);
		} else {
			var ccond = new CCodeBinaryExpression (CCodeBinaryOperator.INEQUALITY, inner_error, new CCodeConstant ("NULL"));
			cfrag.append (new CCodeIfStatement (ccond, cerror_handler));
		}
	}

	public override void visit_try_statement (TryStatement stmt) {
		int this_try_id = next_try_id++;

		var old_try = current_try;
		var old_try_id = current_try_id;
		var old_is_in_catch = is_in_catch;
		current_try = stmt;
		current_try_id = this_try_id;
		is_in_catch = true;

		foreach (CatchClause clause in stmt.get_catch_clauses ()) {
			clause.clabel_name = "__catch%d_%s".printf (this_try_id, clause.error_type.get_lower_case_cname ());
		}

		if (stmt.finally_body != null) {
			stmt.finally_body.accept (codegen);
		}

		is_in_catch = false;
		stmt.body.accept (codegen);
		is_in_catch = true;

		foreach (CatchClause clause in stmt.get_catch_clauses ()) {
			clause.accept (codegen);
		}

		current_try = old_try;
		current_try_id = old_try_id;
		is_in_catch = old_is_in_catch;

		var cfrag = new CCodeFragment ();
		cfrag.append (stmt.body.ccodenode);

		foreach (CatchClause clause in stmt.get_catch_clauses ()) {
			cfrag.append (new CCodeGotoStatement ("__finally%d".printf (this_try_id)));
			cfrag.append (clause.ccodenode);
		}

		cfrag.append (new CCodeLabel ("__finally%d".printf (this_try_id)));
		if (stmt.finally_body != null) {
			cfrag.append (stmt.finally_body.ccodenode);
		}

		// check for errors not handled by this try statement
		// may be handled by outer try statements or propagated
		add_simple_check (stmt, cfrag, !stmt.after_try_block_reachable);

		stmt.ccodenode = cfrag;
	}

	public override void visit_catch_clause (CatchClause clause) {
		if (clause.error_variable != null) {
			clause.error_variable.active = true;
		}

		current_method_inner_error = true;

		var error_type = (ErrorType) clause.error_type;
		if (error_type.error_domain != null) {
			generate_error_domain_declaration (error_type.error_domain, source_declarations);
		}

		clause.accept_children (codegen);

		var cfrag = new CCodeFragment ();
		cfrag.append (new CCodeLabel (clause.clabel_name));

		var cblock = new CCodeBlock ();

		string variable_name;
		if (clause.variable_name != null) {
			variable_name = get_variable_cname (clause.variable_name);
		} else {
			variable_name = "__err";
		}

		if (current_method != null && current_method.coroutine) {
			closure_struct.add_field ("GError *", variable_name);
			cblock.add_statement (new CCodeExpressionStatement (new CCodeAssignment (get_variable_cexpression (variable_name), get_variable_cexpression ("_inner_error_"))));
		} else {
			if (clause.variable_name != null) {
				var cdecl = new CCodeDeclaration ("GError *");
				cdecl.add_declarator (new CCodeVariableDeclarator (variable_name, get_variable_cexpression ("_inner_error_")));
				cblock.add_statement (cdecl);
			} else {
				// error object is not used within catch statement, clear it
				var cclear = new CCodeFunctionCall (new CCodeIdentifier ("g_clear_error"));
				cclear.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression ("_inner_error_")));
				cblock.add_statement (new CCodeExpressionStatement (cclear));
			}
		}
		cblock.add_statement (new CCodeExpressionStatement (new CCodeAssignment (get_variable_cexpression ("_inner_error_"), new CCodeConstant ("NULL"))));

		cblock.add_statement (clause.body.ccodenode);

		cfrag.append (cblock);

		clause.ccodenode = cfrag;
	}

	public override void append_local_free (Symbol sym, CCodeFragment cfrag, bool stop_at_loop = false) {
		var finally_block = (Block) null;
		if (sym.parent_node is TryStatement) {
			finally_block = (sym.parent_node as TryStatement).finally_body;
		} else if (sym.parent_node is CatchClause) {
			finally_block = (sym.parent_node.parent_node as TryStatement).finally_body;
		}

		if (finally_block != null) {
			cfrag.append (finally_block.ccodenode);
		}

		base.append_local_free (sym, cfrag, stop_at_loop);
	}
}

// vim:sw=8 noet