valaccodebasemodule.vala 132 KB
Newer Older
1 2
/* valaccodebasemodule.vala
 *
3 4
 * Copyright (C) 2006-2009  Jürg Billeter
 * Copyright (C) 2006-2008  Raffaele Sandrini
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * 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>
22
 * 	Raffaele Sandrini <raffaele@sandrini.ch>
23 24
 */

25 26
using Gee;

27 28 29
/**
 * Code visitor generating C Code.
 */
30
internal class Vala.CCodeBaseModule : CCodeModule {
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
	public CodeContext context { get; set; }

	public Symbol root_symbol;
	public Symbol current_symbol;
	public TypeSymbol current_type_symbol;
	public Class current_class;
	public Method current_method;
	public DataType current_return_type;
	public TryStatement current_try;
	public PropertyAccessor current_property_accessor;

	public CCodeFragment header_begin;
	public CCodeFragment header_type_declaration;
	public CCodeFragment header_type_definition;
	public CCodeFragment header_type_member_declaration;
	public CCodeFragment header_constant_declaration;
	public CCodeFragment source_begin;
	public CCodeFragment source_include_directives;
	public CCodeFragment source_type_declaration;
	public CCodeFragment source_type_definition;
	public CCodeFragment source_type_member_declaration;
	public CCodeFragment source_constant_declaration;
	public CCodeFragment source_signal_marshaller_declaration;
	public CCodeFragment source_type_member_definition;
	public CCodeFragment class_init_fragment;
56
	public CCodeFragment base_init_fragment;
57
	public CCodeFragment class_finalize_fragment;
58
	public CCodeFragment base_finalize_fragment;
59 60 61 62 63 64 65 66 67
	public CCodeFragment instance_init_fragment;
	public CCodeFragment instance_finalize_fragment;
	public CCodeFragment source_signal_marshaller_definition;
	public CCodeFragment module_init_fragment;
	
	public CCodeStruct param_spec_struct;
	public CCodeStruct instance_struct;
	public CCodeStruct type_struct;
	public CCodeStruct instance_priv_struct;
68
	public CCodeStruct type_priv_struct;
69
	public CCodeStruct closure_struct;
70 71 72
	public CCodeEnum prop_enum;
	public CCodeEnum cenum;
	public CCodeFunction function;
73 74 75 76 77

	// code nodes to be inserted before the current statement
	// used by async method calls in coroutines
	public CCodeFragment pre_statement_fragment;

78 79 80 81 82 83 84 85 86 87 88 89 90
	/* all temporary variables */
	public ArrayList<LocalVariable> temp_vars = new ArrayList<LocalVariable> ();
	/* temporary variables that own their content */
	public ArrayList<LocalVariable> temp_ref_vars = new ArrayList<LocalVariable> ();
	/* cache to check whether a certain marshaller has been created yet */
	public Gee.Set<string> user_marshal_set;
	/* (constant) hash table with all predefined marshallers */
	public Gee.Set<string> predefined_marshal_set;
	/* (constant) hash table with all C keywords */
	public Gee.Set<string> c_keywords;
	
	public int next_temp_var_id = 0;
	public bool in_creation_method = false;
91
	public bool in_constructor = false;
92 93
	public bool in_static_or_class_ctor = false;
	public bool current_method_inner_error = false;
94
	public int next_coroutine_state = 1;
95 96 97 98 99 100 101 102 103 104 105 106 107

	public DataType bool_type;
	public DataType char_type;
	public DataType uchar_type;
	public DataType unichar_type;
	public DataType short_type;
	public DataType ushort_type;
	public DataType int_type;
	public DataType uint_type;
	public DataType long_type;
	public DataType ulong_type;
	public DataType int8_type;
	public DataType uint8_type;
108 109
	public DataType int16_type;
	public DataType uint16_type;
110 111 112 113 114 115 116 117 118 119 120 121 122 123
	public DataType int32_type;
	public DataType uint32_type;
	public DataType int64_type;
	public DataType uint64_type;
	public DataType string_type;
	public DataType float_type;
	public DataType double_type;
	public TypeSymbol gtype_type;
	public TypeSymbol gobject_type;
	public ErrorType gerror_type;
	public Class glist_type;
	public Class gslist_type;
	public TypeSymbol gstringbuilder_type;
	public TypeSymbol garray_type;
124
	public TypeSymbol gbytearray_type;
125
	public DataType gquark_type;
126
	public Struct gvalue_type;
127 128 129 130 131 132 133 134 135 136 137 138 139
	public Struct mutex_type;
	public TypeSymbol type_module_type;
	public TypeSymbol dbus_object_type;

	public bool in_plugin = false;
	public string module_init_param_name;
	
	public bool string_h_needed;
	public bool gvaluecollector_h_needed;
	public bool gio_h_needed;
	public bool requires_free_checked;
	public bool requires_array_free;
	public bool requires_array_move;
140
	public bool requires_array_length;
141 142
	public bool requires_strcmp0;
	public bool dbus_glib_h_needed;
143
	public bool dbus_glib_h_needed_in_header;
144 145 146

	public Set<string> wrappers;

147
	public Map<string,string> variable_name_map = new HashMap<string,string> (str_hash, str_equal);
148

149 150
	public CCodeBaseModule (CCodeGenerator codegen, CCodeModule? next) {
		base (codegen, next);
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
		predefined_marshal_set = new HashSet<string> (str_hash, str_equal);
		predefined_marshal_set.add ("VOID:VOID");
		predefined_marshal_set.add ("VOID:BOOLEAN");
		predefined_marshal_set.add ("VOID:CHAR");
		predefined_marshal_set.add ("VOID:UCHAR");
		predefined_marshal_set.add ("VOID:INT");
		predefined_marshal_set.add ("VOID:UINT");
		predefined_marshal_set.add ("VOID:LONG");
		predefined_marshal_set.add ("VOID:ULONG");
		predefined_marshal_set.add ("VOID:ENUM");
		predefined_marshal_set.add ("VOID:FLAGS");
		predefined_marshal_set.add ("VOID:FLOAT");
		predefined_marshal_set.add ("VOID:DOUBLE");
		predefined_marshal_set.add ("VOID:STRING");
		predefined_marshal_set.add ("VOID:POINTER");
		predefined_marshal_set.add ("VOID:OBJECT");
		predefined_marshal_set.add ("STRING:OBJECT,POINTER");
		predefined_marshal_set.add ("VOID:UINT,POINTER");
		predefined_marshal_set.add ("BOOLEAN:FLAGS");

		c_keywords = new HashSet<string> (str_hash, str_equal);

		// C99 keywords
		c_keywords.add ("_Bool");
		c_keywords.add ("_Complex");
		c_keywords.add ("_Imaginary");
		c_keywords.add ("auto");
		c_keywords.add ("break");
		c_keywords.add ("case");
		c_keywords.add ("char");
		c_keywords.add ("const");
		c_keywords.add ("continue");
		c_keywords.add ("default");
		c_keywords.add ("do");
		c_keywords.add ("double");
		c_keywords.add ("else");
		c_keywords.add ("enum");
		c_keywords.add ("extern");
		c_keywords.add ("float");
		c_keywords.add ("for");
		c_keywords.add ("goto");
		c_keywords.add ("if");
		c_keywords.add ("inline");
		c_keywords.add ("int");
		c_keywords.add ("long");
		c_keywords.add ("register");
		c_keywords.add ("restrict");
		c_keywords.add ("return");
		c_keywords.add ("short");
		c_keywords.add ("signed");
		c_keywords.add ("sizeof");
		c_keywords.add ("static");
		c_keywords.add ("struct");
		c_keywords.add ("switch");
		c_keywords.add ("typedef");
		c_keywords.add ("union");
		c_keywords.add ("unsigned");
		c_keywords.add ("void");
		c_keywords.add ("volatile");
		c_keywords.add ("while");

		// MSVC keywords
		c_keywords.add ("cdecl");
215 216 217 218 219 220 221 222 223 224
	}

	public override CCodeIdentifier get_value_setter_function (DataType type_reference) {
		if (type_reference.data_type != null) {
			return new CCodeIdentifier (type_reference.data_type.get_set_value_function ());
		} else {
			return new CCodeIdentifier ("g_value_set_pointer");
		}
	}

225
	private CCodeIncludeDirective get_internal_include (string filename) {
226
		return new CCodeIncludeDirective (filename, context.library == null);
227 228
	}

229
	public virtual void append_vala_array_free () {
230 231
	}

232
	public virtual void append_vala_array_move () {
233 234
	}

235 236 237
	public virtual void append_vala_array_length () {
	}

238 239 240 241 242
	private void append_vala_strcmp0 () {
		var fun = new CCodeFunction ("_vala_strcmp0", "int");
		fun.modifiers = CCodeModifiers.STATIC;
		fun.add_parameter (new CCodeFormalParameter ("str1", "const char *"));
		fun.add_parameter (new CCodeFormalParameter ("str2", "const char *"));
243
		source_type_member_declaration.append (fun.copy ());
244 245

		// (str1 != str2)
246
		var cineq = new CCodeBinaryExpression (CCodeBinaryOperator.INEQUALITY, new CCodeIdentifier ("str1"), new CCodeIdentifier ("str2"));
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

		fun.block = new CCodeBlock ();

		var cblock = new CCodeBlock ();
		// if (str1 == NULL)
		var cif = new CCodeIfStatement (new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("str1"), new CCodeConstant ("NULL")), cblock);
		// return -(str1 != str2);
		cblock.add_statement (new CCodeReturnStatement (new CCodeUnaryExpression (CCodeUnaryOperator.MINUS, cineq)));
		fun.block.add_statement (cif);

		cblock = new CCodeBlock ();
		// if (str2 == NULL)
		cif = new CCodeIfStatement (new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("str2"), new CCodeConstant ("NULL")), cblock);
		// return (str1 != str2);
		cblock.add_statement (new CCodeReturnStatement (cineq));
		fun.block.add_statement (cif);

		// strcmp (str1, str2)
		var ccall = new CCodeFunctionCall (new CCodeIdentifier ("strcmp"));
		ccall.add_argument (new CCodeIdentifier ("str1"));
		ccall.add_argument (new CCodeIdentifier ("str2"));
		// return strcmp (str1, str2);
		fun.block.add_statement (new CCodeReturnStatement (ccall));

271
		source_type_member_definition.append (fun);
272 273 274
	}

	public override void visit_source_file (SourceFile source_file) {
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
		header_begin = new CCodeFragment ();
		header_type_declaration = new CCodeFragment ();
		header_type_definition = new CCodeFragment ();
		header_type_member_declaration = new CCodeFragment ();
		header_constant_declaration = new CCodeFragment ();
		source_begin = new CCodeFragment ();
		source_include_directives = new CCodeFragment ();
		source_type_declaration = new CCodeFragment ();
		source_type_definition = new CCodeFragment ();
		source_type_member_declaration = new CCodeFragment ();
		source_constant_declaration = new CCodeFragment ();
		source_type_member_definition = new CCodeFragment ();
		source_signal_marshaller_definition = new CCodeFragment ();
		source_signal_marshaller_declaration = new CCodeFragment ();
		
		user_marshal_set = new HashSet<string> (str_hash, str_equal);
		
		next_temp_var_id = 0;
293
		variable_name_map.clear ();
294 295 296 297 298
		
		string_h_needed = false;
		gvaluecollector_h_needed = false;
		gio_h_needed = false;
		dbus_glib_h_needed = false;
299
		dbus_glib_h_needed_in_header = false;
300 301 302
		requires_free_checked = false;
		requires_array_free = false;
		requires_array_move = false;
303
		requires_array_length = false;
304 305 306 307 308 309
		requires_strcmp0 = false;

		wrappers = new HashSet<string> (str_hash, str_equal);

		header_begin.append (new CCodeIncludeDirective ("glib.h"));
		header_begin.append (new CCodeIncludeDirective ("glib-object.h"));
310 311 312 313 314 315 316

		if (context.legacy_headers) {
			if (context.basedir != null || context.library != null) {
				source_include_directives.append (new CCodeIncludeDirective (source_file.get_cinclude_filename ()));
			} else {
				source_include_directives.append (new CCodeIncludeDirective (source_file.get_cinclude_filename (), true));
			}
317 318 319 320 321
		}
		
		Gee.List<string> used_includes = new ArrayList<string> (str_equal);
		used_includes.add ("glib.h");
		used_includes.add ("glib-object.h");
322 323 324

		if (context.legacy_headers) {
			used_includes.add (source_file.get_cinclude_filename ());
325
		
326 327 328 329 330
			foreach (string filename in source_file.get_header_external_includes ()) {
				if (!used_includes.contains (filename)) {
					header_begin.append (new CCodeIncludeDirective (filename));
					used_includes.add (filename);
				}
331
			}
332 333 334 335 336
			foreach (string filename in source_file.get_header_internal_includes ()) {
				if (!used_includes.contains (filename)) {
					header_begin.append (get_internal_include (filename));
					used_includes.add (filename);
				}
337
			}
338 339 340 341 342
			foreach (string filename in source_file.get_source_external_includes ()) {
				if (!used_includes.contains (filename)) {
					source_include_directives.append (new CCodeIncludeDirective (filename));
					used_includes.add (filename);
				}
343
			}
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
			foreach (string filename in source_file.get_source_internal_includes ()) {
				if (!used_includes.contains (filename)) {
					source_include_directives.append (get_internal_include (filename));
					used_includes.add (filename);
				}
			}
			if (source_file.is_cycle_head) {
				foreach (SourceFile cycle_file in source_file.cycle.files) {
					foreach (CodeNode node in cycle_file.get_nodes ()) {
						if (node is Struct) {
							var st = (Struct) node;
							header_type_declaration.append (new CCodeTypeDefinition ("struct _%s".printf (st.get_cname ()), new CCodeVariableDeclarator (st.get_cname ())));
						} else if (node is Class) {
							var cl = (Class) node;
							header_type_declaration.append (new CCodeTypeDefinition ("struct _%s".printf (cl.get_cname ()), new CCodeVariableDeclarator (cl.get_cname ())));
							header_type_declaration.append (new CCodeTypeDefinition ("struct _%sClass".printf (cl.get_cname ()), new CCodeVariableDeclarator ("%sClass".printf (cl.get_cname ()))));
						} else if (node is Interface) {
							var iface = (Interface) node;
							header_type_declaration.append (new CCodeTypeDefinition ("struct _%s".printf (iface.get_cname ()), new CCodeVariableDeclarator (iface.get_cname ())));
							header_type_declaration.append (new CCodeTypeDefinition ("struct _%s".printf (iface.get_type_cname ()), new CCodeVariableDeclarator (iface.get_type_cname ())));
						}
					}
				}
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
			}
		}
		foreach (Symbol symbol in source_file.get_source_symbol_dependencies ()) {
			if (!symbol.external && symbol.external_package) {
				symbol.accept (codegen);
			}
		}

		source_file.accept_children (codegen);

		if (Report.get_errors () > 0) {
			return;
		}

		var header_define = get_define_for_filename (source_file.get_cinclude_filename ());
		
		/* generate hardcoded "well-known" macros */
384 385
		if (requires_free_checked) {
			source_begin.append (new CCodeMacroReplacement ("VALA_FREE_CHECKED(o,f)", "((o) == NULL ? NULL : ((o) = (f (o), NULL)))"));
386
		}
387
		if (requires_array_free) {
388 389
			append_vala_array_free ();
		}
390
		if (requires_array_move) {
391 392
			append_vala_array_move ();
		}
393 394 395
		if (requires_array_length) {
			append_vala_array_length ();
		}
396
		if (requires_strcmp0) {
397 398 399
			append_vala_strcmp0 ();
		}
		
400 401
		if (string_h_needed) {
			source_include_directives.append (new CCodeIncludeDirective ("string.h"));
402 403
		}

404 405
		if (gvaluecollector_h_needed) {
			source_include_directives.append (new CCodeIncludeDirective ("gobject/gvaluecollector.h"));
406 407
		}

408 409
		if (gio_h_needed) {
			header_begin.append (new CCodeIncludeDirective ("gio/gio.h"));
410 411
		}

412
		if (dbus_glib_h_needed_in_header) {
413
			header_begin.append (new CCodeIncludeDirective ("dbus/dbus.h"));
414 415
			header_begin.append (new CCodeIncludeDirective ("dbus/dbus-glib.h"));
		} else if (dbus_glib_h_needed) {
416
			source_include_directives.append (new CCodeIncludeDirective ("dbus/dbus.h"));
417
			source_include_directives.append (new CCodeIncludeDirective ("dbus/dbus-glib.h"));
418
		}
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
		if (dbus_glib_h_needed_in_header || dbus_glib_h_needed) {
			var dbusvtable = new CCodeStruct ("_DBusObjectVTable");
			dbusvtable.add_field ("void", "(*register_object) (DBusConnection*, const char*, void*)");
			source_type_definition.append (dbusvtable);

			source_type_declaration.append (new CCodeTypeDefinition ("struct _DBusObjectVTable", new CCodeVariableDeclarator ("_DBusObjectVTable")));

			var cfunc = new CCodeFunction ("_vala_dbus_register_object", "void");
			cfunc.add_parameter (new CCodeFormalParameter ("connection", "DBusConnection*"));
			cfunc.add_parameter (new CCodeFormalParameter ("path", "const char*"));
			cfunc.add_parameter (new CCodeFormalParameter ("object", "void*"));

			cfunc.modifiers |= CCodeModifiers.STATIC;
			source_type_member_declaration.append (cfunc.copy ());

			var block = new CCodeBlock ();
			cfunc.block = block;

			var cdecl = new CCodeDeclaration ("const _DBusObjectVTable *");
			cdecl.add_declarator (new CCodeVariableDeclarator ("vtable"));
			block.add_statement (cdecl);

			var quark = new CCodeFunctionCall (new CCodeIdentifier ("g_quark_from_static_string"));
			quark.add_argument (new CCodeConstant ("\"DBusObjectVTable\""));

			var get_qdata = new CCodeFunctionCall (new CCodeIdentifier ("g_type_get_qdata"));
			get_qdata.add_argument (new CCodeIdentifier ("G_TYPE_FROM_INSTANCE (object)"));
			get_qdata.add_argument (quark);

			block.add_statement (new CCodeExpressionStatement (new CCodeAssignment (new CCodeIdentifier ("vtable"), get_qdata)));

			var cregister = new CCodeFunctionCall (new CCodeMemberAccess.pointer (new CCodeIdentifier ("vtable"), "register_object"));
			cregister.add_argument (new CCodeIdentifier ("connection"));
			cregister.add_argument (new CCodeIdentifier ("path"));
			cregister.add_argument (new CCodeIdentifier ("object"));
454 455 456 457 458 459 460 461 462 463 464 465

			var ifblock = new CCodeBlock ();
			ifblock.add_statement (new CCodeExpressionStatement (cregister));

			var elseblock = new CCodeBlock ();

			var warn = new CCodeFunctionCall (new CCodeIdentifier ("g_warning"));
			warn.add_argument (new CCodeConstant ("\"Object does not implement any D-Bus interface\""));

			elseblock.add_statement (new CCodeExpressionStatement(warn));

			block.add_statement (new CCodeIfStatement (new CCodeIdentifier ("vtable"), ifblock, elseblock));
466 467 468

			source_type_member_definition.append (cfunc);
		}
469 470 471 472 473 474

		CCodeComment comment = null;
		if (source_file.comment != null) {
			comment = new CCodeComment (source_file.comment);
		}

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
		if (context.legacy_headers) {
			var writer = new CCodeWriter (source_file.get_cheader_filename ());
			if (!writer.open ()) {
				Report.error (null, "unable to open `%s' for writing".printf (writer.filename));
				return;
			}
			if (comment != null) {
				comment.write (writer);
			}
			writer.write_newline ();
			var once = new CCodeOnceSection (header_define);
			once.append (new CCodeNewline ());
			once.append (header_begin);
			once.append (new CCodeNewline ());
			once.append (new CCodeIdentifier ("G_BEGIN_DECLS"));
			once.append (new CCodeNewline ());
			once.append (new CCodeNewline ());
			once.append (header_type_declaration);
			once.append (new CCodeNewline ());
			once.append (header_type_definition);
			once.append (new CCodeNewline ());
			once.append (header_type_member_declaration);
			once.append (new CCodeNewline ());
			once.append (header_constant_declaration);
			once.append (new CCodeNewline ());
			once.append (new CCodeIdentifier ("G_END_DECLS"));
			once.append (new CCodeNewline ());
			once.append (new CCodeNewline ());
			once.write (writer);
			writer.close ();
505 506
		}
		
507
		var writer = new CCodeWriter (source_file.get_csource_filename ());
508 509 510 511
		if (!writer.open ()) {
			Report.error (null, "unable to open `%s' for writing".printf (writer.filename));
			return;
		}
512
		writer.line_directives = context.debug;
513 514 515
		if (comment != null) {
			comment.write (writer);
		}
516
		source_begin.write (writer);
517
		writer.write_newline ();
518
		source_include_directives.write (writer);
519
		writer.write_newline ();
520
		source_type_declaration.write_combined (writer);
521
		writer.write_newline ();
522
		source_type_definition.write_combined (writer);
523
		writer.write_newline ();
524
		source_type_member_declaration.write_declaration (writer);
525
		writer.write_newline ();
526
		source_type_member_declaration.write (writer);
527
		writer.write_newline ();
528
		source_constant_declaration.write (writer);
529
		writer.write_newline ();
530 531
		source_signal_marshaller_declaration.write_declaration (writer);
		source_signal_marshaller_declaration.write (writer);
532
		writer.write_newline ();
533
		source_type_member_definition.write (writer);
534
		writer.write_newline ();
535
		source_signal_marshaller_definition.write (writer);
536 537 538
		writer.write_newline ();
		writer.close ();

539 540 541 542 543 544 545 546 547 548 549 550 551 552
		header_begin = null;
		header_type_declaration = null;
		header_type_definition = null;
		header_type_member_declaration = null;
		header_constant_declaration = null;
		source_begin = null;
		source_include_directives = null;
		source_type_declaration = null;
		source_type_definition = null;
		source_type_member_declaration = null;
		source_constant_declaration = null;
		source_type_member_definition = null;
		source_signal_marshaller_definition = null;
		source_signal_marshaller_declaration = null;
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
	}
	
	private static string get_define_for_filename (string filename) {
		var define = new StringBuilder ("__");
		
		var i = filename;
		while (i.len () > 0) {
			var c = i.get_char ();
			if (c.isalnum  () && c < 0x80) {
				define.append_unichar (c.toupper ());
			} else {
				define.append_c ('_');
			}
		
			i = i.next_char ();
		}
		
		define.append ("__");
		
		return define.str;
	}
574 575 576

	public override void emit (CodeContext context) {
		this.context = context;
577 578 579 580

		if (context.legacy_headers) {
			context.find_header_cycles ();
		}
581 582 583

		root_symbol = context.root;

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
		bool_type = new BooleanType ((Struct) root_symbol.scope.lookup ("bool"));
		char_type = new IntegerType ((Struct) root_symbol.scope.lookup ("char"));
		uchar_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uchar"));
		unichar_type = new IntegerType ((Struct) root_symbol.scope.lookup ("unichar"));
		short_type = new IntegerType ((Struct) root_symbol.scope.lookup ("short"));
		ushort_type = new IntegerType ((Struct) root_symbol.scope.lookup ("ushort"));
		int_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int"));
		uint_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint"));
		long_type = new IntegerType ((Struct) root_symbol.scope.lookup ("long"));
		ulong_type = new IntegerType ((Struct) root_symbol.scope.lookup ("ulong"));
		int8_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int8"));
		uint8_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint8"));
		int16_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int16"));
		uint16_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint16"));
		int32_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int32"));
		uint32_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint32"));
		int64_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int64"));
		uint64_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint64"));
		float_type = new FloatingType ((Struct) root_symbol.scope.lookup ("float"));
		double_type = new FloatingType ((Struct) root_symbol.scope.lookup ("double"));
604 605 606 607 608 609 610 611 612 613 614
		string_type = new ObjectType ((Class) root_symbol.scope.lookup ("string"));

		var glib_ns = root_symbol.scope.lookup ("GLib");

		gtype_type = (TypeSymbol) glib_ns.scope.lookup ("Type");
		gobject_type = (TypeSymbol) glib_ns.scope.lookup ("Object");
		gerror_type = new ErrorType (null, null);
		glist_type = (Class) glib_ns.scope.lookup ("List");
		gslist_type = (Class) glib_ns.scope.lookup ("SList");
		gstringbuilder_type = (TypeSymbol) glib_ns.scope.lookup ("StringBuilder");
		garray_type = (TypeSymbol) glib_ns.scope.lookup ("Array");
615
		gbytearray_type = (TypeSymbol) glib_ns.scope.lookup ("ByteArray");
616

617
		gquark_type = new IntegerType ((Struct) glib_ns.scope.lookup ("Quark"));
618
		gvalue_type = (Struct) glib_ns.scope.lookup ("Value");
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
		mutex_type = (Struct) glib_ns.scope.lookup ("StaticRecMutex");
		
		type_module_type = (TypeSymbol) glib_ns.scope.lookup ("TypeModule");

		if (context.module_init_method != null) {
			module_init_fragment = new CCodeFragment ();
			foreach (FormalParameter parameter in context.module_init_method.get_parameters ()) {
				if (parameter.parameter_type.data_type == type_module_type) {
					in_plugin = true;
					module_init_param_name = parameter.name;
					break;
				}
			}
		}

		var dbus_ns = root_symbol.scope.lookup ("DBus");
		if (dbus_ns != null) {
			dbus_object_type = (TypeSymbol) dbus_ns.scope.lookup ("Object");
		}
	
		/* we're only interested in non-pkg source files */
		var source_files = context.get_source_files ();
		foreach (SourceFile file in source_files) {
			if (!file.external_package) {
				file.accept (codegen);
			}
		}
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

		// generate C header file for public API
		if (context.header_filename != null) {
			var writer = new CCodeWriter (context.header_filename);
			if (!writer.open ()) {
				Report.error (null, "unable to open `%s' for writing".printf (writer.filename));
				return;
			}
			writer.write_newline ();
			var once = new CCodeOnceSection (get_define_for_filename (writer.filename));
			once.append (new CCodeNewline ());
			once.append (new CCodeIdentifier ("G_BEGIN_DECLS"));
			once.append (new CCodeNewline ());
			once.append (new CCodeNewline ());
			once.append (new CCodeIdentifier ("G_END_DECLS"));
			once.append (new CCodeNewline ());
			once.append (new CCodeNewline ());
			once.write (writer);
			writer.close ();
		}
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
	}

	public override void visit_enum (Enum en) {
		cenum = new CCodeEnum (en.get_cname ());

		CCodeFragment decl_frag;
		CCodeFragment def_frag;
		if (en.access != SymbolAccessibility.PRIVATE) {
			decl_frag = header_type_declaration;
			def_frag = header_type_definition;
		} else {
			decl_frag = source_type_declaration;
			def_frag = source_type_definition;
		}
		
		if (en.source_reference.comment != null) {
			def_frag.append (new CCodeComment (en.source_reference.comment));
		}

		def_frag.append (cenum);
		def_frag.append (new CCodeNewline ());

		en.accept_children (codegen);

		if (!en.has_type_id) {
			return;
		}

		decl_frag.append (new CCodeNewline ());

		var macro = "(%s_get_type ())".printf (en.get_lower_case_cname (null));
		decl_frag.append (new CCodeMacroReplacement (en.get_type_id (), macro));

		var clist = new CCodeInitializerList (); /* or during visit time? */
		CCodeInitializerList clist_ev = null;
		foreach (EnumValue ev in en.get_values ()) {
			clist_ev = new CCodeInitializerList ();
			clist_ev.append (new CCodeConstant (ev.get_cname ()));
			clist_ev.append (new CCodeIdentifier ("\"%s\"".printf (ev.get_cname ())));
			clist_ev.append (ev.get_canonical_cconstant ());
			clist.append (clist_ev);
		}

		clist_ev = new CCodeInitializerList ();
		clist_ev.append (new CCodeConstant ("0"));
		clist_ev.append (new CCodeConstant ("NULL"));
		clist_ev.append (new CCodeConstant ("NULL"));
		clist.append (clist_ev);

715
		var enum_decl = new CCodeVariableDeclarator ("values[]", clist);
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736

		CCodeDeclaration cdecl = null;
		if (en.is_flags) {
			cdecl = new CCodeDeclaration ("const GFlagsValue");
		} else {
			cdecl = new CCodeDeclaration ("const GEnumValue");
		}

		cdecl.add_declarator (enum_decl);
		cdecl.modifiers = CCodeModifiers.STATIC;

		var type_init = new CCodeBlock ();

		type_init.add_statement (cdecl);

		var fun_name = "%s_get_type".printf (en.get_lower_case_cname (null));
		var regfun = new CCodeFunction (fun_name, "GType");
		var regblock = new CCodeBlock ();

		cdecl = new CCodeDeclaration ("GType");
		string type_id_name = "%s_type_id".printf (en.get_lower_case_cname (null));
737
		cdecl.add_declarator (new CCodeVariableDeclarator (type_id_name, new CCodeConstant ("0")));
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
		cdecl.modifiers = CCodeModifiers.STATIC;
		regblock.add_statement (cdecl);

		CCodeFunctionCall reg_call;
		if (en.is_flags) {
			reg_call = new CCodeFunctionCall (new CCodeIdentifier ("g_flags_register_static"));
		} else {
			reg_call = new CCodeFunctionCall (new CCodeIdentifier ("g_enum_register_static"));
		}

		reg_call.add_argument (new CCodeConstant ("\"%s\"".printf (en.get_cname())));
		reg_call.add_argument (new CCodeIdentifier ("values"));

		type_init.add_statement (new CCodeExpressionStatement (new CCodeAssignment (new CCodeIdentifier (type_id_name), reg_call)));

		var cond = new CCodeFunctionCall (new CCodeIdentifier ("G_UNLIKELY"));
		cond.add_argument (new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier (type_id_name), new CCodeConstant ("0")));
		var cif = new CCodeIfStatement (cond, type_init);
		regblock.add_statement (cif);

		regblock.add_statement (new CCodeReturnStatement (new CCodeConstant (type_id_name)));

		if (en.access != SymbolAccessibility.PRIVATE) {
			header_type_member_declaration.append (regfun.copy ());
		} else {
			source_type_member_declaration.append (regfun.copy ());
		}
		regfun.block = regblock;

		source_type_member_definition.append (new CCodeNewline ());
		source_type_member_definition.append (regfun);
	}

	public override void visit_enum_value (EnumValue ev) {
		if (ev.value == null) {
			cenum.add_value (new CCodeEnumValue (ev.get_cname ()));
		} else {
			ev.value.accept (codegen);
			cenum.add_value (new CCodeEnumValue (ev.get_cname (), (CCodeExpression) ev.value.ccodenode));
		}
	}
	
	public override void visit_member (Member m) {
		/* stuff meant for all lockable members */
		if (m is Lockable && ((Lockable)m).get_lock_used ()) {
			CCodeExpression l = new CCodeIdentifier ("self");
			l = new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (l, "priv"), get_symbol_lock_name (m));	

			instance_priv_struct.add_field (mutex_type.get_cname (), get_symbol_lock_name (m));

			var initf = new CCodeFunctionCall (
				new CCodeIdentifier (mutex_type.default_construction_method.get_cname ()));

			initf.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));		

			instance_init_fragment.append (new CCodeExpressionStatement (initf));
		
			requires_free_checked = true;


			var fc = new CCodeFunctionCall (new CCodeIdentifier ("g_static_rec_mutex_free"));

			fc.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));

			if (instance_finalize_fragment != null) {
				instance_finalize_fragment.append (new CCodeExpressionStatement (fc));
			}
		}
	}

	public override void visit_constant (Constant c) {
		c.accept_children (codegen);

Jürg Billeter's avatar
Jürg Billeter committed
811
		if (c.initializer is InitializerList) {
812 813 814 815 816
			var cdecl = new CCodeDeclaration (c.type_reference.get_const_cname ());
			var arr = "";
			if (c.type_reference is ArrayType) {
				arr = "[]";
			}
817
			cdecl.add_declarator (new CCodeVariableDeclarator ("%s%s".printf (c.get_cname (), arr), (CCodeExpression) c.initializer.ccodenode));
818 819
			cdecl.modifiers = CCodeModifiers.STATIC;
		
820 821 822 823 824
			if (!c.is_internal_symbol ()) {
				header_constant_declaration.append (cdecl);
			} else {
				source_constant_declaration.append (cdecl);
			}
Jürg Billeter's avatar
Jürg Billeter committed
825 826 827 828 829 830 831
		} else {
			var cdefine = new CCodeMacroReplacement.with_expression (c.get_cname (), (CCodeExpression) c.initializer.ccodenode);
			if (!c.is_internal_symbol ()) {
				header_type_member_declaration.append (cdefine);
			} else {
				source_type_member_declaration.append (cdefine);
			}
832 833 834 835
		}
	}

	public override void visit_field (Field f) {
836 837
		check_type (f.field_type);

838 839 840 841 842 843 844 845 846 847 848 849 850
		f.accept_children (codegen);

		var cl = f.parent_symbol as Class;
		bool is_gtypeinstance = (cl != null && !cl.is_compact);

		CCodeExpression lhs = null;
		CCodeStruct st = null;
		
		string field_ctype = f.field_type.get_cname ();
		if (f.is_volatile) {
			field_ctype = "volatile " + field_ctype;
		}

851 852 853 854 855
		if (f.binding == MemberBinding.INSTANCE)  {
			if (is_gtypeinstance && f.access == SymbolAccessibility.PRIVATE) {
				st = instance_priv_struct;
				lhs = new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), "priv"), f.get_cname ());
			} else {
856 857 858 859 860 861 862 863
				st = instance_struct;
				lhs = new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), f.get_cname ());
			}

			st.add_field (field_ctype, f.get_cname ());
			if (f.field_type is ArrayType && !f.no_array_length) {
				// create fields to store array dimensions
				var array_type = (ArrayType) f.field_type;
864
				var len_type = int_type.copy ();
865 866 867 868
				
				for (int dim = 1; dim <= array_type.rank; dim++) {
					st.add_field (len_type.get_cname (), head.get_array_length_cname (f.name, dim));
				}
869 870 871 872

				if (array_type.rank == 1 && f.is_internal_symbol ()) {
					st.add_field (len_type.get_cname (), head.get_array_size_cname (f.name));
				}
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
			} else if (f.field_type is DelegateType) {
				var delegate_type = (DelegateType) f.field_type;
				if (delegate_type.delegate_symbol.has_target) {
					// create field to store delegate target
					st.add_field ("gpointer", get_delegate_target_cname (f.name));
				}
			}

			if (f.initializer != null) {
				var rhs = (CCodeExpression) f.initializer.ccodenode;

				instance_init_fragment.append (new CCodeExpressionStatement (new CCodeAssignment (lhs, rhs)));

				if (f.field_type is ArrayType && !f.no_array_length &&
				    f.initializer is ArrayCreationExpression) {
					var array_type = (ArrayType) f.field_type;
					var this_access = new MemberAccess.simple ("this");
					this_access.value_type = get_data_type_for_symbol ((TypeSymbol) f.parent_symbol);
					this_access.ccodenode = new CCodeIdentifier ("self");
					var ma = new MemberAccess (this_access, f.name);
					ma.symbol_reference = f;
					
					Gee.List<Expression> sizes = ((ArrayCreationExpression) f.initializer).get_sizes ();
					for (int dim = 1; dim <= array_type.rank; dim++) {
						var array_len_lhs = head.get_array_length_cexpression (ma, dim);
						var size = sizes[dim - 1];
						instance_init_fragment.append (new CCodeExpressionStatement (new CCodeAssignment (array_len_lhs, (CCodeExpression) size.ccodenode)));
					}
				}
902 903 904

				append_temp_decl (instance_init_fragment, temp_vars);
				temp_vars.clear ();
905 906 907 908 909
			}
			
			if (requires_destroy (f.field_type) && instance_finalize_fragment != null) {
				var this_access = new MemberAccess.simple ("this");
				this_access.value_type = get_data_type_for_symbol ((TypeSymbol) f.parent_symbol);
910

911 912
				var field_st = f.parent_symbol as Struct;
				if (field_st != null && !field_st.is_simple_type ()) {
913 914 915 916 917
					this_access.ccodenode = new CCodeIdentifier ("(*self)");
				} else {
					this_access.ccodenode = new CCodeIdentifier ("self");
				}

918 919 920 921 922
				var ma = new MemberAccess (this_access, f.name);
				ma.symbol_reference = f;
				instance_finalize_fragment.append (new CCodeExpressionStatement (get_unref_expression (lhs, f.field_type, ma)));
			}
		} else if (f.binding == MemberBinding.CLASS)  {
923 924 925 926 927 928 929 930 931 932 933 934
			if (!is_gtypeinstance) {
				Report.error (f.source_reference, "class fields are not supported in compact classes");
				f.error = true;
				return;
			}

			if (f.access != SymbolAccessibility.PRIVATE) {
				st = type_struct;
			} else {
				st = type_priv_struct;
			}

935 936
			st.add_field (field_ctype, f.get_cname ());
		} else {
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
			lhs = new CCodeIdentifier (f.get_cname ());

			if (!f.is_internal_symbol ()) {
				var cdecl = new CCodeDeclaration (field_ctype);
				cdecl.add_declarator (new CCodeVariableDeclarator (f.get_cname ()));
				cdecl.modifiers = CCodeModifiers.EXTERN;
				header_type_member_declaration.append (cdecl);
			}

			var var_decl = new CCodeVariableDeclarator (f.get_cname ());
			var_decl.initializer = default_value_for_type (f.field_type, true);

			if (f.initializer != null) {
				var init = (CCodeExpression) f.initializer.ccodenode;
				if (is_constant_ccode_expression (init)) {
					var_decl.initializer = init;
				}
			}

			var var_def = new CCodeDeclaration (field_ctype);
			var_def.add_declarator (var_decl);
			if (!f.is_internal_symbol ()) {
				var_def.modifiers = CCodeModifiers.EXTERN;
			} else {
				var_def.modifiers = CCodeModifiers.STATIC;
			}
			source_type_member_declaration.append (var_def);

965 966 967 968 969 970 971
			/* add array length fields where necessary */
			if (f.field_type is ArrayType && !f.no_array_length) {
				var array_type = (ArrayType) f.field_type;

				for (int dim = 1; dim <= array_type.rank; dim++) {
					var len_type = int_type.copy ();

972 973 974
					if (!f.is_internal_symbol ()) {
						var cdecl = new CCodeDeclaration (len_type.get_cname ());
						cdecl.add_declarator (new CCodeVariableDeclarator (head.get_array_length_cname (f.get_cname (), dim)));
975 976
						cdecl.modifiers = CCodeModifiers.EXTERN;
						header_type_member_declaration.append (cdecl);
977 978 979
					}

					var len_def = new CCodeDeclaration (len_type.get_cname ());
980
					len_def.add_declarator (new CCodeVariableDeclarator (head.get_array_length_cname (f.get_cname (), dim), new CCodeConstant ("0")));
981 982
					if (!f.is_internal_symbol ()) {
						len_def.modifiers = CCodeModifiers.EXTERN;
983
					} else {
984
						len_def.modifiers = CCodeModifiers.STATIC;
985
					}
986
					source_type_member_declaration.append (len_def);
987
				}
988 989 990 991 992

				if (array_type.rank == 1 && f.is_internal_symbol ()) {
					var len_type = int_type.copy ();

					var cdecl = new CCodeDeclaration (len_type.get_cname ());
993
					cdecl.add_declarator (new CCodeVariableDeclarator (head.get_array_size_cname (f.get_cname ()), new CCodeConstant ("0")));
994 995 996
					cdecl.modifiers = CCodeModifiers.STATIC;
					source_type_member_declaration.append (cdecl);
				}
997 998 999 1000
			} else if (f.field_type is DelegateType) {
				var delegate_type = (DelegateType) f.field_type;
				if (delegate_type.delegate_symbol.has_target) {
					// create field to store delegate target
1001 1002 1003 1004

					if (!f.is_internal_symbol ()) {
						var cdecl = new CCodeDeclaration ("gpointer");
						cdecl.add_declarator (new CCodeVariableDeclarator (get_delegate_target_cname  (f.get_cname ())));
1005 1006
						cdecl.modifiers = CCodeModifiers.EXTERN;
						header_type_member_declaration.append (cdecl);
1007 1008 1009
					}

					var target_def = new CCodeDeclaration ("gpointer");
1010
					target_def.add_declarator (new CCodeVariableDeclarator (get_delegate_target_cname  (f.get_cname ()), new CCodeConstant ("NULL")));
1011 1012
					if (!f.is_internal_symbol ()) {
						target_def.modifiers = CCodeModifiers.EXTERN;
1013
					} else {
1014
						target_def.modifiers = CCodeModifiers.STATIC;
1015
					}
1016
					source_type_member_declaration.append (target_def);
1017 1018 1019 1020 1021 1022 1023 1024
				}
			}

			if (f.initializer != null) {
				var rhs = (CCodeExpression) f.initializer.ccodenode;
				if (!is_constant_ccode_expression (rhs)) {
					if (f.parent_symbol is Class) {
						class_init_fragment.append (new CCodeExpressionStatement (new CCodeAssignment (lhs, rhs)));
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

						if (f.field_type is ArrayType && !f.no_array_length &&
						    f.initializer is ArrayCreationExpression) {
							var array_type = (ArrayType) f.field_type;
							var ma = new MemberAccess.simple (f.name);
							ma.symbol_reference = f;
					
							Gee.List<Expression> sizes = ((ArrayCreationExpression) f.initializer).get_sizes ();
							for (int dim = 1; dim <= array_type.rank; dim++) {
								var array_len_lhs = head.get_array_length_cexpression (ma, dim);
								var size = sizes[dim - 1];
								class_init_fragment.append (new CCodeExpressionStatement (new CCodeAssignment (array_len_lhs, (CCodeExpression) size.ccodenode)));
							}
						}

						append_temp_decl (class_init_fragment, temp_vars);
						temp_vars.clear ();
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
					} else {
						f.error = true;
						Report.error (f.source_reference, "Non-constant field initializers not supported in this context");
						return;
					}
				}
			}
		}
	}

Jürg Billeter's avatar
Jürg Billeter committed
1052
	public bool is_constant_ccode_expression (CCodeExpression cexpr) {
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
		if (cexpr is CCodeConstant) {
			return true;
		} else if (cexpr is CCodeBinaryExpression) {
			var cbinary = (CCodeBinaryExpression) cexpr;
			return is_constant_ccode_expression (cbinary.left) && is_constant_ccode_expression (cbinary.right);
		}

		var cparenthesized = (cexpr as CCodeParenthesizedExpression);
		return (null != cparenthesized && is_constant_ccode_expression (cparenthesized.inner));
	}

	/**
	 * Returns whether the passed cexpr is a pure expression, i.e. an
	 * expression without side-effects.
	 */
	public bool is_pure_ccode_expression (CCodeExpression cexpr) {
		if (cexpr is CCodeConstant || cexpr is CCodeIdentifier) {
			return true;
		} else if (cexpr is CCodeBinaryExpression) {
			var cbinary = (CCodeBinaryExpression) cexpr;
			return is_pure_ccode_expression (cbinary.left) && is_constant_ccode_expression (cbinary.right);
		} else if (cexpr is CCodeMemberAccess) {
			var cma = (CCodeMemberAccess) cexpr;
			return is_pure_ccode_expression (cma.inner);
		}

		var cparenthesized = (cexpr as CCodeParenthesizedExpression);
		return (null != cparenthesized && is_pure_ccode_expression (cparenthesized.inner));
	}

	public override void visit_formal_parameter (FormalParameter p) {
1084 1085
		check_type (p.parameter_type);

1086 1087 1088 1089 1090 1091 1092 1093 1094
		p.accept_children (codegen);

		if (!p.ellipsis) {
			string ctypename = p.parameter_type.get_cname ();
			string cname = p.name;

			// pass non-simple structs always by reference
			if (p.parameter_type.data_type is Struct) {
				var st = (Struct) p.parameter_type.data_type;
1095 1096 1097 1098 1099
				if (!st.is_simple_type () && p.direction == ParameterDirection.IN) {
					ctypename = "const " + ctypename;
					if (!p.parameter_type.nullable) {
						ctypename += "*";
					}
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
				}
			}

			if (p.direction != ParameterDirection.IN) {
				ctypename += "*";
			}

			p.ccodenode = new CCodeFormalParameter (cname, ctypename);
		} else {
			p.ccodenode = new CCodeFormalParameter.with_ellipsis ();
		}
	}

	public override void visit_property (Property prop) {
1114 1115
		check_type (prop.property_type);

1116
		int old_next_temp_var_id = next_temp_var_id;
1117
		var old_variable_name_map = variable_name_map;
1118
		next_temp_var_id = 0;
1119
		variable_name_map = new HashMap<string,string> (str_hash, str_equal);
1120 1121 1122 1123

		prop.accept_children (codegen);

		next_temp_var_id = old_next_temp_var_id;
1124
		variable_name_map = old_variable_name_map;
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
	}

	public override void visit_property_accessor (PropertyAccessor acc) {
		current_property_accessor = acc;
		current_method_inner_error = false;

		var prop = (Property) acc.prop;

		bool returns_real_struct = prop.property_type.is_real_struct_type ();

		if (acc.readable && !returns_real_struct) {
			current_return_type = prop.property_type;
		} else {
			current_return_type = new VoidType ();
		}

		acc.accept_children (codegen);

		var t = (TypeSymbol) prop.parent_symbol;

1145 1146 1147 1148 1149 1150
		if (acc.construction && !t.is_subtype_of (gobject_type)) {
			Report.error (acc.source_reference, "construct properties require GLib.Object");
			acc.error = true;
			return;
		}

1151 1152 1153 1154 1155 1156 1157 1158 1159
		ReferenceType this_type;
		if (t is Class) {
			this_type = new ObjectType ((Class) t);
		} else {
			this_type = new ObjectType ((Interface) t);
		}
		var cselfparam = new CCodeFormalParameter ("self", this_type.get_cname ());
		CCodeFormalParameter cvalueparam;
		if (returns_real_struct) {
1160
			cvalueparam = new CCodeFormalParameter ("value", acc.value_type.get_cname () + "*");
1161
		} else {
1162
			cvalueparam = new CCodeFormalParameter ("value", acc.value_type.get_cname ());
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
		}

		if (prop.is_abstract || prop.is_virtual) {
			CCodeFunctionDeclarator vdeclarator;

			if (acc.readable) {
				function = new CCodeFunction (acc.get_cname (), current_return_type.get_cname ());

				var vdecl = new CCodeDeclaration (current_return_type.get_cname ());
				vdeclarator = new CCodeFunctionDeclarator ("get_%s".printf (prop.name));
				vdecl.add_declarator (vdeclarator);
				type_struct.add_declaration (vdecl);
			} else {
				function = new CCodeFunction (acc.get_cname (), "void");

				var vdecl = new CCodeDeclaration ("void");
				vdeclarator = new CCodeFunctionDeclarator ("set_%s".printf (prop.name));
				vdecl.add_declarator (vdeclarator);
				type_struct.add_declaration (vdecl);
			}
			function.add_parameter (cselfparam);
			vdeclarator.add_parameter (cselfparam);
			if (acc.writable || acc.construction || returns_real_struct) {
				function.add_parameter (cvalueparam);
				vdeclarator.add_parameter (cvalueparam);
			}
			
			if (!prop.is_internal_symbol () && (acc.readable || acc.writable) && acc.access != SymbolAccessibility.PRIVATE) {
				// accessor function should be public if the property is a public symbol and it's not a construct-only setter
				header_type_member_declaration.append (function.copy ());
			} else {
				function.modifiers |= CCodeModifiers.STATIC;
				source_type_member_declaration.append (function.copy ());
			}
			
			var block = new CCodeBlock ();
			function.block = block;

			CCodeFunctionCall vcast = null;
			if (prop.parent_symbol is Interface) {
				var iface = (Interface) prop.parent_symbol;

				vcast = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_INTERFACE".printf (iface.get_upper_case_cname (null))));
			} else {
				var cl = (Class) prop.parent_symbol;

				vcast = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS".printf (cl.get_upper_case_cname (null))));
			}
			vcast.add_argument (new CCodeIdentifier ("self"));

			if (acc.readable) {
				var vcall = new CCodeFunctionCall (new CCodeMemberAccess.pointer (vcast, "get_%s".printf (prop.name)));
				vcall.add_argument (new CCodeIdentifier ("self"));
				if (returns_real_struct) {
					vcall.add_argument (new CCodeIdentifier ("value"));
					block.add_statement (new CCodeExpressionStatement (vcall));
				} else {
					block.add_statement (new CCodeReturnStatement (vcall));
				}
			} else {
				var vcall = new CCodeFunctionCall (new CCodeMemberAccess.pointer (vcast, "set_%s".printf (prop.name)));
				vcall.add_argument (new CCodeIdentifier ("self"));
				vcall.add_argument (new CCodeIdentifier ("value"));
				block.add_statement (new CCodeExpressionStatement (vcall));
			}

			source_type_member_definition.append (function);
		}

		if (!prop.is_abstract) {
			bool is_virtual = prop.base_property != null || prop.base_interface_property != null;

			string cname;
			if (is_virtual) {
				if (acc.readable) {
					cname = "%s_real_get_%s".printf (t.get_lower_case_cname (null), prop.name);
				} else {
					cname = "%s_real_set_%s".printf (t.get_lower_case_cname (null), prop.name);
				}
			} else {
				cname = acc.get_cname ();
			}

			if (acc.writable || acc.construction || returns_real_struct) {
				function = new CCodeFunction (cname, "void");
			} else {
1249
				function = new CCodeFunction (cname, acc.value_type.get_cname ());
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
			}

			ObjectType base_type = null;
			if (prop.binding == MemberBinding.INSTANCE) {
				if (is_virtual) {
					if (prop.base_property != null) {
						base_type = new ObjectType ((ObjectTypeSymbol) prop.base_property.parent_symbol);
					} else if (prop.base_interface_property != null) {
						base_type = new ObjectType ((ObjectTypeSymbol) prop.base_interface_property.parent_symbol);
					}
					function.modifiers |= CCodeModifiers.STATIC;
					function.add_parameter (new CCodeFormalParameter ("base", base_type.get_cname ()));
				} else {
					function.add_parameter (cselfparam);
				}
			}
			if (acc.writable || acc.construction || returns_real_struct) {
				function.add_parameter (cvalueparam);
			}

			if (!is_virtual) {
				if (!prop.is_internal_symbol () && (acc.readable || acc.writable) && acc.access != SymbolAccessibility.PRIVATE) {
					// accessor function should be public if the property is a public symbol and it's not a construct-only setter
					header_type_member_declaration.append (function.copy ());
				} else {
					function.modifiers |= CCodeModifiers.STATIC;
					source_type_member_declaration.append (function.copy ());
				}
			}

			function.block = (CCodeBlock) acc.body.ccodenode;

			if (is_virtual) {
				var cdecl = new CCodeDeclaration (this_type.get_cname ());
1284
				cdecl.add_declarator (new CCodeVariableDeclarator ("self", transform_expression (new CCodeIdentifier ("base"), base_type, this_type)));
1285 1286 1287 1288 1289
				function.block.prepend_statement (cdecl);
			}

			if (current_method_inner_error) {
				var cdecl = new CCodeDeclaration ("GError *");
1290
				cdecl.add_declarator (new CCodeVariableDeclarator ("inner_error", new CCodeConstant ("NULL")));
1291 1292 1293 1294
				function.block.prepend_statement (cdecl);
			}

			if (prop.binding == MemberBinding.INSTANCE && !is_virtual) {
1295
				CCodeStatement check_stmt;
1296
				if (returns_real_struct) {
1297
					check_stmt = create_property_type_check_statement (prop, false, t, true, "self");
1298
				} else {
1299 1300 1301 1302
					check_stmt = create_property_type_check_statement (prop, acc.readable, t, true, "self");
				}
				if (check_stmt != null) {
					function.block.prepend_statement (check_stmt);
1303 1304 1305 1306 1307
				}
			}

			// notify on property changes
			var typesymbol = (TypeSymbol) prop.parent_symbol;
1308
			var st = prop.property_type.data_type as Struct;
1309
			if (typesymbol.is_subtype_of (gobject_type) &&
1310
			    (st == null || st.has_type_id) &&
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
			    prop.notify &&
			    prop.access != SymbolAccessibility.PRIVATE && // FIXME: use better means to detect gobject properties
			    prop.binding == MemberBinding.INSTANCE &&
			    (acc.writable || acc.construction)) {
				var notify_call = new CCodeFunctionCall (new CCodeIdentifier ("g_object_notify"));
				notify_call.add_argument (new CCodeCastExpression (new CCodeIdentifier ("self"), "GObject *"));
				notify_call.add_argument (prop.get_canonical_cconstant ());
				function.block.add_statement (new CCodeExpressionStatement (notify_call));
			}

			source_type_member_definition.append (function);
		}

		current_property_accessor = null;
		current_return_type = null;
	}

	public override void visit_destructor (Destructor d) {
		current_method_inner_error = false;

		d.accept_children (codegen);

1333 1334 1335 1336 1337 1338
		if (d.binding == MemberBinding.STATIC && !in_plugin) {
			Report.error (d.source_reference, "static destructors are only supported for dynamic types");
			d.error = true;
			return;
		}

1339 1340 1341 1342
		CCodeFragment cfrag = new CCodeFragment ();

		if (current_method_inner_error) {
			var cdecl = new CCodeDeclaration ("GError *");
1343
			cdecl.add_declarator (new CCodeVariableDeclarator ("inner_error", new CCodeConstant ("NULL")));
1344 1345 1346 1347 1348 1349 1350 1351 1352
			cfrag.append (cdecl);
		}

		cfrag.append (d.body.ccodenode);

		d.ccodenode = cfrag;
	}

	public override void visit_block (Block b) {
1353
		var old_symbol = current_symbol;
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
		current_symbol = b;

		b.accept_children (codegen);

		var local_vars = b.get_local_variables ();
		foreach (LocalVariable local in local_vars) {
			local.active = false;
		}
		
		var cblock = new CCodeBlock ();
		
		foreach (CodeNode stmt in b.get_statements ()) {
			if (stmt.error) {
				continue;
			}

			var src = stmt.source_reference;
			if (src != null && src.comment != null) {
				cblock.add_statement (new CCodeComment (src.comment));
			}
			
			if (stmt.ccodenode is CCodeFragment) {
				foreach (CCodeNode cstmt in ((CCodeFragment) stmt.ccodenode).get_children ()) {
					cblock.add_statement (cstmt);
				}
			} else {
				cblock.add_statement (stmt.ccodenode);
			}
		}

		foreach (LocalVariable local in local_vars) {
1385
			if (!local.floating && requires_destroy (local.variable_type)) {
1386 1387
				var ma = new MemberAccess.simple (local.name);
				ma.symbol_reference = local;
1388
				cblock.add_statement (new CCodeExpressionStatement (get_unref_expression (get_variable_cexpression (local.name), local.variable_type, ma)));
1389 1390 1391 1392 1393 1394 1395 1396 1397
			}
		}

		if (b.parent_symbol is Method) {
			var m = (Method) b.parent_symbol;
			foreach (FormalParameter param in m.get_parameters ()) {
				if (requires_destroy (param.parameter_type) && param.direction == ParameterDirection.IN) {
					var ma = new MemberAccess.simple (param.name);
					ma.symbol_reference = param;
1398
					cblock.add_statement (new CCodeExpressionStatement (get_unref_expression (get_variable_cexpression (param.name), param.parameter_type, ma)));
1399 1400 1401 1402 1403 1404
				}
			}
		}

		b.ccodenode = cblock;

1405
		current_symbol = old_symbol;
1406 1407 1408 1409 1410 1411 1412
	}

	public override void visit_empty_statement (EmptyStatement stmt) {
		stmt.ccodenode = new CCodeEmptyStatement ();
	}

	public override void visit_declaration_statement (DeclarationStatement stmt) {
1413 1414
		stmt.declaration.accept (codegen);

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
		stmt.ccodenode = stmt.declaration.ccodenode;

		var local = stmt.declaration as LocalVariable;
		if (local != null && local.initializer != null) {
			create_temp_decl (stmt, local.initializer.temp_vars);
		}

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

1426 1427 1428 1429 1430 1431 1432 1433
	public CCodeExpression get_variable_cexpression (string name) {
		if (current_method != null && current_method.coroutine) {
			return new CCodeMemberAccess.pointer (new CCodeIdentifier ("data"), get_variable_cname (name));
		} else {
			return new CCodeIdentifier (get_variable_cname (name));
		}
	}

1434
	public string get_variable_cname (string name) {
1435 1436 1437 1438 1439 1440 1441 1442
		if (name[0] == '.') {
			// compiler-internal variable
			if (!variable_name_map.contains (name)) {
				variable_name_map.set (name, "_tmp%d".printf (next_temp_var_id));
				next_temp_var_id++;
			}
			return variable_name_map.get (name);
		} else if (c_keywords.contains (name)) {
1443 1444 1445 1446 1447 1448 1449
			return name + "_";
		} else {
			return name;
		}
	}

	public override void visit_local_variable (LocalVariable local) {
1450 1451
		check_type (local.variable_type);

1452 1453 1454 1455 1456 1457 1458
		local.accept_children (codegen);

		if (local.variable_type is ArrayType) {
			// create variables to store array dimensions
			var array_type = (ArrayType) local.variable_type;
			
			for (int dim = 1; dim <= array_type.rank; dim++) {
1459
				var len_var = new LocalVariable (int_type.copy (), head.get_array_length_cname (get_variable_cname (local.name), dim));
1460 1461
				temp_vars.insert (0, len_var);
			}
1462 1463 1464 1465 1466

			if (array_type.rank == 1) {
				var size_var = new LocalVariable (int_type.copy (), head.get_array_size_cname (get_variable_cname (local.name)));
				temp_vars.insert (0, size_var);
			}
1467 1468 1469 1470 1471
		} else if (local.variable_type is DelegateType) {
			var deleg_type = (DelegateType) local.variable_type;
			var d = deleg_type.delegate_symbol;
			if (d.has_target) {
				// create variable to store delegate target
1472
				var target_var = new LocalVariable (new PointerType (new VoidType ()), get_delegate_target_cname (get_variable_cname (local.name)));
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
				temp_vars.insert (0, target_var);
			}
		}
	
		CCodeExpression rhs = null;
		if (local.initializer != null && local.initializer.ccodenode != null) {
			rhs = (CCodeExpression) local.initializer.ccodenode;

			if (local.variable_type is ArrayType) {
				var array_type = (ArrayType) local.variable_type;

				var ccomma = new CCodeCommaExpression ();

				var temp_var = get_temp_variable (local.variable_type, true, local);
				temp_vars.insert (0, temp_var);
Jürg Billeter's avatar
Jürg Billeter committed
1488
				ccomma.append_expression (new CCodeAssignment (get_variable_cexpression (temp_var.name), rhs));
1489 1490

				for (int dim = 1; dim <= array_type.rank; dim++) {
1491
					var lhs_array_len = get_variable_cexpression (head.get_array_length_cname (get_variable_cname (local.name), dim));
1492 1493 1494
					var rhs_array_len = head.get_array_length_cexpression (local.initializer, dim);
					ccomma.append_expression (new CCodeAssignment (lhs_array_len, rhs_array_len));
				}
1495 1496 1497 1498 1499
				if (array_type.rank == 1) {
					var lhs_array_size = get_variable_cexpression (head.get_array_size_cname (get_variable_cname (local.name)));
					var rhs_array_len = get_variable_cexpression (head.get_array_length_cname (get_variable_cname (local.name), 1));
					ccomma.append_expression (new CCodeAssignment (lhs_array_size, rhs_array_len));
				}
1500
				
1501
				ccomma.append_expression (get_variable_cexpression (temp_var.name));
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
				
				rhs = ccomma;
			} else if (local.variable_type is DelegateType) {
				var deleg_type = (DelegateType) local.variable_type;
				var d = deleg_type.delegate_symbol;
				if (d.has_target) {
					var ccomma = new CCodeCommaExpression ();

					var temp_var = get_temp_variable (local.variable_type, true, local);
					temp_vars.insert (0, temp_var);
Jürg Billeter's avatar
Jürg Billeter committed
1512
					ccomma.append_expression (new CCodeAssignment (get_variable_cexpression (temp_var.name), rhs));
1513

1514
					var lhs_delegate_target = get_variable_cexpression (get_delegate_target_cname (get_variable_cname (local.name)));
1515 1516 1517
					var rhs_delegate_target = get_delegate_target_cexpression (local.initializer);
					ccomma.append_expression (new CCodeAssignment (lhs_delegate_target, rhs_delegate_target));
				
1518
					ccomma.append_expression (get_variable_cexpression (temp_var.name));
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
				
					rhs = ccomma;
				}
			}
		} else if (local.variable_type.is_reference_type_or_type_parameter ()) {
			rhs = new CCodeConstant ("NULL");

			if (local.variable_type is ArrayType) {
				// initialize array length variables
				var array_type = (ArrayType) local.variable_type;

				var ccomma = new CCodeCommaExpression ();

				for (int dim = 1; dim <= array_type.rank; dim++) {
1533
					ccomma.append_expression (new CCodeAssignment (get_variable_cexpression (head.get_array_length_cname (get_variable_cname (local.name), dim)), new CCodeConstant ("0")));
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
				}

				ccomma.append_expression (rhs);

				rhs = ccomma;
			}
		}

		var cfrag = new CCodeFragment ();

1544 1545 1546 1547 1548
		if (pre_statement_fragment != null) {
			cfrag.append (pre_statement_fragment);
			pre_statement_fragment = null;
		}

1549 1550 1551 1552 1553 1554 1555
		if (current_method != null && current_method.coroutine) {
			closure_struct.add_field (local.variable_type.get_cname (), get_variable_cname (local.name));

			if (local.initializer != null) {
				cfrag.append (new CCodeExpressionStatement (new CCodeAssignment (new CCodeMemberAccess.pointer (new CCodeIdentifier ("data"), get_variable_cname (local.name)), rhs)));
			}
		} else {
1556
			var cvar = new CCodeVariableDeclarator (get_variable_cname (local.name), rhs);
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566

			var cdecl = new CCodeDeclaration (local.variable_type.get_cname ());
			cdecl.add_declarator (cvar);
			cfrag.append (cdecl);

			// try to initialize uninitialized variables
			// initialization not necessary for variables stored in closure
			if (cvar.initializer == null) {
				cvar.initializer = default_value_for_type (local.variable_type, true);
			}
1567 1568
		}

1569 1570
		if (local.initializer != null && local.initializer.tree_can_fail) {
			head.add_simple_check (local.initializer, cfrag);
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
		}

		local.ccodenode = cfrag;

		local.active = true;
	}

	public override void visit_initializer_list (InitializerList list) {
		list.accept_children (codegen);

		if (list.target_type.data_type is Struct) {
			/* initializer is used as struct initializer */
			var st = (Struct) list.target_type.data_type;

			var clist = new CCodeInitializerList ();

			var field_it = st.get_fields ().iterator ();
			foreach (Expression expr in list.get_initializers ()) {
				Field field = null;
				while (field == null) {
					field_it.next ();
					field = field_it.get ();
					if (field.binding != MemberBinding.INSTANCE) {
						// we only initialize instance fields
						field = null;
					}
				}

				var cexpr = (CCodeExpression) expr.ccodenode;

				string ctype = field.get_ctype ();
				if (ctype != null) {
					cexpr = new CCodeCastExpression (cexpr, ctype);
				}

				clist.append (cexpr);
			}

			list.ccodenode = clist;
		} else {
			var clist = new CCodeInitializerList ();
			foreach (Expression expr in list.get_initializers ()) {
				clist.append ((CCodeExpression) expr.ccodenode);
			}
			list.ccodenode = clist;
		}
	}

	public LocalVariable get_temp_variable (DataType type, bool value_owned = true, CodeNode? node_reference = null) {
		var var_type = type.copy ();
		var_type.value_owned = value_owned;
		var local = new LocalVariable (var_type, "_tmp%d".printf (next_temp_var_id));

		if (node_reference != null) {
			local.source_reference = node_reference.source_reference;
		}

		next_temp_var_id++;
		
		return local;
	}

	private CCodeExpression get_type_id_expression (DataType type) {
1634
		if (type is GenericType) {
1635 1636 1637
			string var_name = "%s_type".printf (type.type_parameter.name.down ());
			return new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), "priv"), var_name);
		} else {
1638 1639 1640 1641 1642
			string type_id = type.get_type_id ();
			if (type_id == null) {
				type_id = "G_TYPE_INVALID";
			}
			return new CCodeIdentifier (type_id);