valaccodebasemodule.vala 236 KB
Newer Older
1 2
/* valaccodebasemodule.vala
 *
3
 * Copyright (C) 2006-2012  Jürg Billeter
4
 * 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 27 28
/**
 * Code visitor generating C Code.
 */
29
public abstract class Vala.CCodeBaseModule : CodeGenerator {
30 31 32 33
	public class EmitContext {
		public Symbol? current_symbol;
		public ArrayList<Symbol> symbol_stack = new ArrayList<Symbol> ();
		public TryStatement current_try;
34
		public CatchClause current_catch;
35 36
		public CCodeFunction ccode;
		public ArrayList<CCodeFunction> ccode_stack = new ArrayList<CCodeFunction> ();
37
		public ArrayList<TargetValue> temp_ref_values = new ArrayList<TargetValue> ();
38 39
		public int next_temp_var_id;
		public bool current_method_inner_error;
40
		public bool current_method_return;
41
		public int next_coroutine_state = 1;
42
		public Map<string,string> variable_name_map = new HashMap<string,string> (str_hash, str_equal);
43 44
		public Map<string,int> closure_variable_count_map = new HashMap<string,int> (str_hash, str_equal);
		public Map<LocalVariable,int> closure_variable_clash_map = new HashMap<LocalVariable,int> ();
45 46 47 48 49 50 51 52 53 54 55

		public EmitContext (Symbol? symbol = null) {
			current_symbol = symbol;
		}

		public void push_symbol (Symbol symbol) {
			symbol_stack.add (current_symbol);
			current_symbol = symbol;
		}

		public void pop_symbol () {
56
			current_symbol = symbol_stack.remove_at (symbol_stack.size - 1);
57 58 59
		}
	}

60 61 62
	public CodeContext context { get; set; }

	public Symbol root_symbol;
63 64 65 66 67

	public EmitContext emit_context = new EmitContext ();

	List<EmitContext> emit_context_stack = new ArrayList<EmitContext> ();

68 69 70 71
	public CCodeLineDirective? current_line = null;

	List<CCodeLineDirective> line_directive_stack = new ArrayList<CCodeLineDirective> ();

72 73 74 75 76 77
	public Symbol current_symbol { get { return emit_context.current_symbol; } }

	public TryStatement current_try {
		get { return emit_context.current_try; }
		set { emit_context.current_try = value; }
	}
78

79 80 81 82 83
	public CatchClause current_catch {
		get { return emit_context.current_catch; }
		set { emit_context.current_catch = value; }
	}

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	public TypeSymbol? current_type_symbol {
		get {
			var sym = current_symbol;
			while (sym != null) {
				if (sym is TypeSymbol) {
					return (TypeSymbol) sym;
				}
				sym = sym.parent_symbol;
			}
			return null;
		}
	}

	public Class? current_class {
		get { return current_type_symbol as Class; }
	}

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	public Method? current_method {
		get {
			var sym = current_symbol;
			while (sym is Block) {
				sym = sym.parent_symbol;
			}
			return sym as Method;
		}
	}

	public PropertyAccessor? current_property_accessor {
		get {
			var sym = current_symbol;
			while (sym is Block) {
				sym = sym.parent_symbol;
			}
			return sym as PropertyAccessor;
		}
	}

121 122 123 124 125 126 127 128 129 130
	public Constructor? current_constructor {
		get {
			var sym = current_symbol;
			while (sym is Block) {
				sym = sym.parent_symbol;
			}
			return sym as Constructor;
		}
	}

131 132 133 134 135 136 137 138 139 140
	public Destructor? current_destructor {
		get {
			var sym = current_symbol;
			while (sym is Block) {
				sym = sym.parent_symbol;
			}
			return sym as Destructor;
		}
	}

141
	public DataType? current_return_type {
142
		get {
143 144 145 146 147 148 149 150 151 152 153
			var m = current_method;
			if (m != null) {
				return m.return_type;
			}

			var acc = current_property_accessor;
			if (acc != null) {
				if (acc.readable) {
					return acc.value_type;
				} else {
					return void_type;
154 155
				}
			}
156

157 158 159 160
			if (is_in_constructor () || is_in_destructor ()) {
				return void_type;
			}

161 162 163 164
			return null;
		}
	}

165 166 167 168
	public bool is_in_coroutine () {
		return current_method != null && current_method.coroutine;
	}

169
	public bool is_in_constructor () {
170 171 172 173
		if (current_method != null) {
			// make sure to not return true in lambda expression inside constructor
			return false;
		}
174 175 176 177 178 179 180 181 182 183
		var sym = current_symbol;
		while (sym != null) {
			if (sym is Constructor) {
				return true;
			}
			sym = sym.parent_symbol;
		}
		return false;
	}

184
	public bool is_in_destructor () {
185 186 187 188
		if (current_method != null) {
			// make sure to not return true in lambda expression inside constructor
			return false;
		}
189 190 191 192 193 194 195 196 197 198
		var sym = current_symbol;
		while (sym != null) {
			if (sym is Destructor) {
				return true;
			}
			sym = sym.parent_symbol;
		}
		return false;
	}

Jürg Billeter's avatar
Jürg Billeter committed
199 200 201 202 203 204 205 206
	public Block? current_closure_block {
		get {
			return next_closure_block (current_symbol);
		}
	}

	public unowned Block? next_closure_block (Symbol sym) {
		while (true) {
207 208 209 210 211 212 213 214
			unowned Method method = sym as Method;
			if (method != null && !method.closure) {
				// parent blocks are not captured by this method
				break;
			}

			unowned Block block = sym as Block;
			if (method == null && block == null) {
Jürg Billeter's avatar
Jürg Billeter committed
215 216 217
				// no closure block
				break;
			}
218

Jürg Billeter's avatar
Jürg Billeter committed
219 220
			if (block != null && block.captured) {
				// closure block found
221
				return block;
Jürg Billeter's avatar
Jürg Billeter committed
222 223 224
			}
			sym = sym.parent_symbol;
		}
225
		return null;
Jürg Billeter's avatar
Jürg Billeter committed
226 227
	}

228 229 230
	public CCodeFile header_file;
	public CCodeFile internal_header_file;
	public CCodeFile cfile;
231

232 233 234 235 236 237
	public EmitContext class_init_context;
	public EmitContext base_init_context;
	public EmitContext class_finalize_context;
	public EmitContext base_finalize_context;
	public EmitContext instance_init_context;
	public EmitContext instance_finalize_context;
238 239
	
	public CCodeStruct param_spec_struct;
240
	public CCodeStruct closure_struct;
241
	public CCodeEnum prop_enum;
242
	public CCodeEnum signal_enum;
243

244
	public CCodeFunction ccode { get { return emit_context.ccode; } }
245

246
	/* temporary variables that own their content */
247
	public ArrayList<TargetValue> temp_ref_values { get { return emit_context.temp_ref_values; } }
248
	/* cache to check whether a certain marshaller has been created yet */
249
	public Set<string> user_marshal_set;
250
	/* (constant) hash table with all predefined marshallers */
251
	public Set<string> predefined_marshal_set;
252
	/* (constant) hash table with all reserved identifiers in the generated code */
253
	Set<string> reserved_identifiers;
254
	
255 256 257 258 259
	public int next_temp_var_id {
		get { return emit_context.next_temp_var_id; }
		set { emit_context.next_temp_var_id = value; }
	}

260
	public int next_regex_id = 0;
261
	public bool in_creation_method { get { return current_method is CreationMethod; } }
262 263 264 265 266 267

	public bool current_method_inner_error {
		get { return emit_context.current_method_inner_error; }
		set { emit_context.current_method_inner_error = value; }
	}

268 269 270 271 272
	public bool current_method_return {
		get { return emit_context.current_method_return; }
		set { emit_context.current_method_return = value; }
	}

273 274
	int next_block_id = 0;
	Map<Block,int> block_map = new HashMap<Block,int> ();
275

276
	public DataType void_type = new VoidType ();
277 278 279
	public DataType bool_type;
	public DataType char_type;
	public DataType uchar_type;
280
	public DataType? unichar_type;
281 282 283 284 285 286 287 288
	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;
289 290
	public DataType int16_type;
	public DataType uint16_type;
291 292 293 294 295
	public DataType int32_type;
	public DataType uint32_type;
	public DataType int64_type;
	public DataType uint64_type;
	public DataType string_type;
296
	public DataType regex_type;
297 298 299 300 301 302 303
	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;
304
	public Class gnode_type;
305
	public Class gqueue_type;
306
	public Class gvaluearray_type;
307 308
	public TypeSymbol gstringbuilder_type;
	public TypeSymbol garray_type;
309
	public TypeSymbol gbytearray_type;
310
	public TypeSymbol gptrarray_type;
Jürg Billeter's avatar
Jürg Billeter committed
311
	public TypeSymbol gthreadpool_type;
312
	public DataType gdestroynotify_type;
313
	public DataType gquark_type;
314
	public Struct gvalue_type;
315
	public Class gvariant_type;
316
	public Struct mutex_type;
317 318 319 320
	public Struct gmutex_type;
	public Struct grecmutex_type;
	public Struct grwlock_type;
	public Struct gcond_type;
321
	public Class gsource_type;
322
	public TypeSymbol type_module_type;
323
	public TypeSymbol dbus_proxy_type;
324
	public Class gtk_widget_type;
325 326 327 328 329

	public bool in_plugin = false;
	public string module_init_param_name;
	
	public bool gvaluecollector_h_needed;
330
	public bool requires_assert;
331 332
	public bool requires_array_free;
	public bool requires_array_move;
333
	public bool requires_array_length;
334
	public bool requires_clear_mutex;
335 336

	public Set<string> wrappers;
337
	Set<Symbol> generated_external_symbols;
338

339
	public Map<string,string> variable_name_map { get { return emit_context.variable_name_map; } }
340

341 342
	public static int ccode_attribute_cache_index = CodeNode.get_attribute_cache_index ();

343
	public CCodeBaseModule () {
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		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");
363 364 365
		predefined_marshal_set.add ("VOID:BOXED");
		predefined_marshal_set.add ("VOID:VARIANT");
		predefined_marshal_set.add ("BOOLEAN:BOXED,BOXED");
366

367
		reserved_identifiers = new HashSet<string> (str_hash, str_equal);
368 369

		// C99 keywords
370 371 372
		reserved_identifiers.add ("_Bool");
		reserved_identifiers.add ("_Complex");
		reserved_identifiers.add ("_Imaginary");
373
		reserved_identifiers.add ("asm");
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
		reserved_identifiers.add ("auto");
		reserved_identifiers.add ("break");
		reserved_identifiers.add ("case");
		reserved_identifiers.add ("char");
		reserved_identifiers.add ("const");
		reserved_identifiers.add ("continue");
		reserved_identifiers.add ("default");
		reserved_identifiers.add ("do");
		reserved_identifiers.add ("double");
		reserved_identifiers.add ("else");
		reserved_identifiers.add ("enum");
		reserved_identifiers.add ("extern");
		reserved_identifiers.add ("float");
		reserved_identifiers.add ("for");
		reserved_identifiers.add ("goto");
		reserved_identifiers.add ("if");
		reserved_identifiers.add ("inline");
		reserved_identifiers.add ("int");
		reserved_identifiers.add ("long");
		reserved_identifiers.add ("register");
		reserved_identifiers.add ("restrict");
		reserved_identifiers.add ("return");
		reserved_identifiers.add ("short");
		reserved_identifiers.add ("signed");
		reserved_identifiers.add ("sizeof");
		reserved_identifiers.add ("static");
		reserved_identifiers.add ("struct");
		reserved_identifiers.add ("switch");
		reserved_identifiers.add ("typedef");
		reserved_identifiers.add ("union");
		reserved_identifiers.add ("unsigned");
		reserved_identifiers.add ("void");
		reserved_identifiers.add ("volatile");
		reserved_identifiers.add ("while");
408

409 410 411 412 413 414 415 416 417
		// C11 keywords
		reserved_identifiers.add ("_Alignas");
		reserved_identifiers.add ("_Alignof");
		reserved_identifiers.add ("_Atomic");
		reserved_identifiers.add ("_Generic");
		reserved_identifiers.add ("_Noreturn");
		reserved_identifiers.add ("_Static_assert");
		reserved_identifiers.add ("_Thread_local");

418
		// MSVC keywords
419 420 421 422 423 424
		reserved_identifiers.add ("cdecl");

		// reserved for Vala/GObject naming conventions
		reserved_identifiers.add ("error");
		reserved_identifiers.add ("result");
		reserved_identifiers.add ("self");
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
	public override void emit (CodeContext context) {
		this.context = context;

		root_symbol = context.root;

		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"));
		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"));
		string_type = new ObjectType ((Class) root_symbol.scope.lookup ("string"));
452 453 454 455 456
		var unichar_struct = (Struct) root_symbol.scope.lookup ("unichar");
		if (unichar_struct != null) {
			unichar_type = new IntegerType (unichar_struct);
		}

Jürg Billeter's avatar
Jürg Billeter committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
		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");
		gnode_type = (Class) glib_ns.scope.lookup ("Node");
		gqueue_type = (Class) glib_ns.scope.lookup ("Queue");
		gvaluearray_type = (Class) glib_ns.scope.lookup ("ValueArray");
		gstringbuilder_type = (TypeSymbol) glib_ns.scope.lookup ("StringBuilder");
		garray_type = (TypeSymbol) glib_ns.scope.lookup ("Array");
		gbytearray_type = (TypeSymbol) glib_ns.scope.lookup ("ByteArray");
		gptrarray_type = (TypeSymbol) glib_ns.scope.lookup ("PtrArray");
		gthreadpool_type = (TypeSymbol) glib_ns.scope.lookup ("ThreadPool");
		gdestroynotify_type = new DelegateType ((Delegate) glib_ns.scope.lookup ("DestroyNotify"));

		gquark_type = new IntegerType ((Struct) glib_ns.scope.lookup ("Quark"));
		gvalue_type = (Struct) glib_ns.scope.lookup ("Value");
		gvariant_type = (Class) glib_ns.scope.lookup ("Variant");
477
		gsource_type = (Class) glib_ns.scope.lookup ("Source");
Jürg Billeter's avatar
Jürg Billeter committed
478

479 480 481 482
		gmutex_type = (Struct) glib_ns.scope.lookup ("Mutex");
		grecmutex_type = (Struct) glib_ns.scope.lookup ("RecMutex");
		grwlock_type = (Struct) glib_ns.scope.lookup ("RWLock");
		gcond_type = (Struct) glib_ns.scope.lookup ("Cond");
483

484
		mutex_type = grecmutex_type;
Jürg Billeter's avatar
Jürg Billeter committed
485 486 487 488 489 490 491 492 493 494 495

		type_module_type = (TypeSymbol) glib_ns.scope.lookup ("TypeModule");

		regex_type = new ObjectType ((Class) root_symbol.scope.lookup ("GLib").scope.lookup ("Regex"));

		if (context.module_init_method != null) {
			foreach (Parameter parameter in context.module_init_method.get_parameters ()) {
				if (parameter.variable_type.data_type == type_module_type) {
					in_plugin = true;
					module_init_param_name = parameter.name;
					break;
496
				}
497
			}
Jürg Billeter's avatar
Jürg Billeter committed
498 499 500
			if (!in_plugin) {
				Report.error (context.module_init_method.source_reference, "[ModuleInit] requires a parameter of type `GLib.TypeModule'");
			}
501 502
		}

Jürg Billeter's avatar
Jürg Billeter committed
503 504
		dbus_proxy_type = (TypeSymbol) glib_ns.scope.lookup ("DBusProxy");

505 506 507 508 509
		var gtk_ns = root_symbol.scope.lookup ("Gtk");
		if (gtk_ns != null) {
			gtk_widget_type = (Class) gtk_ns.scope.lookup ("Widget");
		}

510 511 512 513
		header_file = new CCodeFile ();
		header_file.is_header = true;
		internal_header_file = new CCodeFile ();
		internal_header_file.is_header = true;
514 515 516 517

		/* we're only interested in non-pkg source files */
		var source_files = context.get_source_files ();
		foreach (SourceFile file in source_files) {
518 519
			if (file.file_type == SourceFileType.SOURCE ||
			    (context.header_filename != null && file.file_type == SourceFileType.FAST)) {
520
				file.accept (this);
521 522 523
			}
		}

524 525 526
		// generate symbols file for public API
		if (context.symbols_filename != null) {
			var stream = FileStream.open (context.symbols_filename, "w");
527 528 529 530
			if (stream == null) {
				Report.error (null, "unable to open `%s' for writing".printf (context.symbols_filename));
				return;
			}
531

532 533 534
			foreach (string symbol in header_file.get_symbols ()) {
				stream.puts (symbol);
				stream.putc ('\n');
535 536 537 538 539
			}

			stream = null;
		}

540 541
		// generate C header file for public API
		if (context.header_filename != null) {
Jürg Billeter's avatar
Jürg Billeter committed
542
			bool ret = header_file.store (context.header_filename, null, context.version_header, false, "G_BEGIN_DECLS", "G_END_DECLS");
543 544
			if (!ret) {
				Report.error (null, "unable to open `%s' for writing".printf (context.header_filename));
545
			}
546
		}
547 548 549

		// generate C header file for internal API
		if (context.internal_header_filename != null) {
Jürg Billeter's avatar
Jürg Billeter committed
550
			bool ret = internal_header_file.store (context.internal_header_filename, null, context.version_header, false, "G_BEGIN_DECLS", "G_END_DECLS");
551 552
			if (!ret) {
				Report.error (null, "unable to open `%s' for writing".printf (context.internal_header_filename));
553
			}
554
		}
555 556
	}

557 558 559 560 561 562
	public void push_context (EmitContext emit_context) {
		if (this.emit_context != null) {
			emit_context_stack.add (this.emit_context);
		}

		this.emit_context = emit_context;
563 564 565
		if (ccode != null) {
			ccode.current_line = current_line;
		}
566 567 568 569
	}

	public void pop_context () {
		if (emit_context_stack.size > 0) {
570
			this.emit_context = emit_context_stack.remove_at (emit_context_stack.size - 1);
571 572 573
			if (ccode != null) {
				ccode.current_line = current_line;
			}
574 575 576 577 578
		} else {
			this.emit_context = null;
		}
	}

579 580 581
	public void push_line (SourceReference? source_reference) {
		line_directive_stack.add (current_line);
		if (source_reference != null) {
582
			current_line = new CCodeLineDirective (source_reference.file.filename, source_reference.begin.line);
583 584 585 586 587 588 589
			if (ccode != null) {
				ccode.current_line = current_line;
			}
		}
	}

	public void pop_line () {
590
		current_line = line_directive_stack.remove_at (line_directive_stack.size - 1);
591 592 593 594 595
		if (ccode != null) {
			ccode.current_line = current_line;
		}
	}

596 597 598
	public void push_function (CCodeFunction func) {
		emit_context.ccode_stack.add (ccode);
		emit_context.ccode = func;
599
		ccode.current_line = current_line;
600 601 602
	}

	public void pop_function () {
603
		emit_context.ccode = emit_context.ccode_stack.remove_at (emit_context.ccode_stack.size - 1);
604 605 606
		if (ccode != null) {
			ccode.current_line = current_line;
		}
607 608
	}

609
	public bool add_symbol_declaration (CCodeFile decl_space, Symbol sym, string name) {
610 611 612
		if (decl_space.add_declaration (name)) {
			return true;
		}
613 614 615
		if (sym.source_reference != null) {
			sym.source_reference.file.used = true;
		}
616 617
		if (sym.external_package || (!decl_space.is_header && CodeContext.get ().use_header && !sym.is_internal_symbol ())) {
			// add appropriate include file
618
			foreach (unowned string header_filename in get_ccode_header_filenames (sym).split (",")) {
619 620 621
				decl_space.add_include (header_filename, !sym.external_package ||
				                                         (sym.external_package &&
				                                          sym.from_commandline));
622 623 624 625 626 627 628 629 630
			}
			// declaration complete
			return true;
		} else {
			// require declaration
			return false;
		}
	}

631
	public CCodeIdentifier get_value_setter_function (DataType type_reference) {
632
		var array_type = type_reference as ArrayType;
633
		if (type_reference.data_type != null) {
634
			return new CCodeIdentifier (get_ccode_set_value_function (type_reference.data_type));
635 636 637
		} else if (array_type != null && array_type.element_type.data_type == string_type.data_type) {
			// G_TYPE_STRV
			return new CCodeIdentifier ("g_value_set_boxed");
638 639 640 641 642
		} else {
			return new CCodeIdentifier ("g_value_set_pointer");
		}
	}

643
	public CCodeIdentifier get_value_taker_function (DataType type_reference) {
644 645
		var array_type = type_reference as ArrayType;
		if (type_reference.data_type != null) {
646
			return new CCodeIdentifier (get_ccode_take_value_function (type_reference.data_type));
647 648 649 650 651 652 653 654
		} else if (array_type != null && array_type.element_type.data_type == string_type.data_type) {
			// G_TYPE_STRV
			return new CCodeIdentifier ("g_value_take_boxed");
		} else {
			return new CCodeIdentifier ("g_value_set_pointer");
		}
	}

655 656 657
	CCodeIdentifier get_value_getter_function (DataType type_reference) {
		var array_type = type_reference as ArrayType;
		if (type_reference.data_type != null) {
658
			return new CCodeIdentifier (get_ccode_get_value_function (type_reference.data_type));
659 660 661 662 663 664 665 666
		} else if (array_type != null && array_type.element_type.data_type == string_type.data_type) {
			// G_TYPE_STRV
			return new CCodeIdentifier ("g_value_get_boxed");
		} else {
			return new CCodeIdentifier ("g_value_get_pointer");
		}
	}

667
	public virtual void append_vala_array_free () {
668 669
	}

670
	public virtual void append_vala_array_move () {
671 672
	}

673 674 675
	public virtual void append_vala_array_length () {
	}

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
	public void append_vala_clear_mutex (string typename, string funcprefix) {
		// memset
		cfile.add_include ("string.h");

		var fun = new CCodeFunction ("_vala_clear_" + typename);
		fun.modifiers = CCodeModifiers.STATIC;
		fun.add_parameter (new CCodeParameter ("mutex", typename + " *"));

		push_function (fun);

		ccode.add_declaration (typename, new CCodeVariableDeclarator.zero ("zero_mutex", new CCodeConstant ("{ 0 }")));

		var cmp = new CCodeFunctionCall (new CCodeIdentifier ("memcmp"));
		cmp.add_argument (new CCodeIdentifier ("mutex"));
		cmp.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, new CCodeIdentifier ("zero_mutex")));
		cmp.add_argument (new CCodeIdentifier ("sizeof (" + typename + ")"));
		ccode.open_if (cmp);

		var mutex_clear = new CCodeFunctionCall (new CCodeIdentifier (funcprefix + "_clear"));
		mutex_clear.add_argument (new CCodeIdentifier ("mutex"));
		ccode.add_expression (mutex_clear);

		var mset = new CCodeFunctionCall (new CCodeIdentifier ("memset"));
		mset.add_argument (new CCodeIdentifier ("mutex"));
		mset.add_argument (new CCodeConstant ("0"));
		mset.add_argument (new CCodeIdentifier ("sizeof (" + typename + ")"));
		ccode.add_expression (mset);

		ccode.close ();

		pop_function ();

		cfile.add_function_declaration (fun);
		cfile.add_function (fun);
	}

712
	public override void visit_source_file (SourceFile source_file) {
713
		cfile = new CCodeFile ();
714 715 716
		
		user_marshal_set = new HashSet<string> (str_hash, str_equal);
		
717
		next_regex_id = 0;
718 719
		
		gvaluecollector_h_needed = false;
720
		requires_assert = false;
721 722
		requires_array_free = false;
		requires_array_move = false;
723
		requires_array_length = false;
724
		requires_clear_mutex = false;
725 726

		wrappers = new HashSet<string> (str_hash, str_equal);
727
		generated_external_symbols = new HashSet<Symbol> ();
728

Jürg Billeter's avatar
Jürg Billeter committed
729 730 731 732
		header_file.add_include ("glib.h");
		internal_header_file.add_include ("glib.h");
		cfile.add_include ("glib.h");
		cfile.add_include ("glib-object.h");
733

734
		source_file.accept_children (this);
735

736
		if (context.report.get_errors () > 0) {
737 738 739
			return;
		}

740 741 742 743 744 745 746 747
		/* For fast-vapi, we only wanted the header declarations
		 * to be emitted, so bail out here without writing the
		 * C code output.
		 */
		if (source_file.file_type == SourceFileType.FAST) {
			return;
		}

748 749
		if (requires_assert) {
			cfile.add_type_declaration (new CCodeMacroReplacement.with_expression ("_vala_assert(expr, msg)", new CCodeConstant ("if G_LIKELY (expr) ; else g_assertion_message_expr (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, msg);")));
750 751 752
			cfile.add_type_declaration (new CCodeMacroReplacement.with_expression ("_vala_return_if_fail(expr, msg)", new CCodeConstant ("if G_LIKELY (expr) ; else { g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, msg); return; }")));
			cfile.add_type_declaration (new CCodeMacroReplacement.with_expression ("_vala_return_val_if_fail(expr, msg, val)", new CCodeConstant ("if G_LIKELY (expr) ; else { g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC, msg); return val; }")));
			cfile.add_type_declaration (new CCodeMacroReplacement.with_expression ("_vala_warn_if_fail(expr, msg)", new CCodeConstant ("if G_LIKELY (expr) ; else g_warn_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, msg);")));
753
		}
754
		if (requires_array_free) {
755 756
			append_vala_array_free ();
		}
757
		if (requires_array_move) {
758 759
			append_vala_array_move ();
		}
760 761 762
		if (requires_array_length) {
			append_vala_array_length ();
		}
763 764 765 766 767 768
		if (requires_clear_mutex) {
			append_vala_clear_mutex ("GMutex", "g_mutex");
			append_vala_clear_mutex ("GRecMutex", "g_rec_mutex");
			append_vala_clear_mutex ("GRWLock", "g_rw_lock");
			append_vala_clear_mutex ("GCond", "g_cond");
		}
769

770
		if (gvaluecollector_h_needed) {
771
			cfile.add_include ("gobject/gvaluecollector.h");
772
		}
773 774 775 776 777

		var comments = source_file.get_comments();
		if (comments != null) {
			foreach (Comment comment in comments) {
				var ccomment = new CCodeComment (comment.content);
778
				cfile.add_comment (ccomment);
779 780
			}
		}
781 782 783 784 785 786

		if (!cfile.store (source_file.get_csource_filename (), source_file.filename, context.version_header, context.debug)) {
			Report.error (null, "unable to open `%s' for writing".printf (source_file.get_csource_filename ()));
		}

		cfile = null;
787
	}
788

789
	public virtual bool generate_enum_declaration (Enum en, CCodeFile decl_space) {
790
		if (add_symbol_declaration (decl_space, en, get_ccode_name (en))) {
791
			return false;
792 793
		}

794
		var cenum = new CCodeEnum (get_ccode_name (en));
795

796
		cenum.modifiers |= (en.version.deprecated ? CCodeModifiers.DEPRECATED : 0);
797

798
		int flag_shift = 0;
799
		foreach (EnumValue ev in en.get_values ()) {
800
			CCodeEnumValue c_ev;
801
			if (ev.value == null) {
802
				c_ev = new CCodeEnumValue (get_ccode_name (ev));
803 804 805 806
				if (en.is_flags) {
					c_ev.value = new CCodeConstant ("1 << %d".printf (flag_shift));
					flag_shift += 1;
				}
807
			} else {
808
				ev.value.emit (this);
809
				c_ev = new CCodeEnumValue (get_ccode_name (ev), get_cvalue (ev.value));
810
			}
811
			c_ev.modifiers |= (ev.version.deprecated ? CCodeModifiers.DEPRECATED : 0);
812
			cenum.add_value (c_ev);
813 814
		}

815 816
		decl_space.add_type_definition (cenum);
		decl_space.add_type_definition (new CCodeNewline ());
817

818
		if (!get_ccode_has_type_id (en)) {
819
			return true;
820 821
		}

822
		decl_space.add_include ("glib-object.h");
823
		decl_space.add_type_declaration (new CCodeNewline ());
824

825 826
		var macro = "(%s_get_type ())".printf (get_ccode_lower_case_name (en, null));
		decl_space.add_type_declaration (new CCodeMacroReplacement (get_ccode_type_id (en), macro));
827

828
		var fun_name = "%s_get_type".printf (get_ccode_lower_case_name (en, null));
829
		var regfun = new CCodeFunction (fun_name, "GType");
830
		regfun.modifiers = CCodeModifiers.CONST;
831

832
		if (en.is_private_symbol ()) {
833
			// avoid C warning as this function is not always used
834
			regfun.modifiers |= CCodeModifiers.STATIC | CCodeModifiers.UNUSED;
835
		} else if (context.hide_internal && en.is_internal_symbol ()) {
836
			regfun.modifiers |= CCodeModifiers.INTERNAL;
837 838
		}

839
		decl_space.add_function_declaration (regfun);
840 841

		return true;
842 843 844
	}

	public override void visit_enum (Enum en) {
845 846
		push_line (en.source_reference);

847
		en.accept_children (this);
848

849
		if (en.comment != null) {
850
			cfile.add_type_member_definition (new CCodeComment (en.comment.content));
851 852
		}

853
		generate_enum_declaration (en, cfile);
854 855

		if (!en.is_internal_symbol ()) {
856
			generate_enum_declaration (en, header_file);
857
		}
858
		if (!en.is_private_symbol ()) {
859
			generate_enum_declaration (en, internal_header_file);
860
		}
861 862

		pop_line ();
863 864
	}

865
	public void visit_member (Symbol m) {
866
		/* stuff meant for all lockable members */
867
		if (m is Lockable && ((Lockable) m).get_lock_used ()) {
868
			CCodeExpression l = new CCodeIdentifier ("self");
869 870
			var init_context = class_init_context;
			var finalize_context = class_finalize_context;
871 872 873

			if (m.is_instance_member ()) {
				l = new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (l, "priv"), get_symbol_lock_name (m.name));
874 875
				init_context = instance_init_context;
				finalize_context = instance_finalize_context;
876 877
			} else if (m.is_class_member ()) {
				TypeSymbol parent = (TypeSymbol)m.parent_symbol;
878

879
				var get_class_private_call = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS_PRIVATE".printf(get_ccode_upper_case_name (parent))));
880 881
				get_class_private_call.add_argument (new CCodeIdentifier ("klass"));
				l = new CCodeMemberAccess.pointer (get_class_private_call, get_symbol_lock_name (m.name));
882
			} else {
883
				l = new CCodeIdentifier (get_symbol_lock_name ("%s_%s".printf(get_ccode_lower_case_name (m.parent_symbol), m.name)));
884
			}
885

886
			push_context (init_context);
887
			var initf = new CCodeFunctionCall (new CCodeIdentifier (get_ccode_name (mutex_type.default_construction_method)));
888
			initf.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));
889 890
			ccode.add_expression (initf);
			pop_context ();
891

892 893
			if (finalize_context != null) {
				push_context (finalize_context);
894
				var fc = new CCodeFunctionCall (new CCodeIdentifier ("g_rec_mutex_clear"));
895
				fc.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));
896 897
				ccode.add_expression (fc);
				pop_context ();
898 899 900 901
			}
		}
	}

902
	public void generate_constant_declaration (Constant c, CCodeFile decl_space, bool definition = false) {
903 904 905 906 907
		if (c.parent_symbol is Block) {
			// local constant
			return;
		}

908
		if (add_symbol_declaration (decl_space, c, get_ccode_name (c))) {
909 910 911
			return;
		}

912
		if (!c.external) {
913 914
			generate_type_declaration (c.type_reference, decl_space);

915
			c.value.emit (this);
916

917
			var initializer_list = c.value as InitializerList;
918
			if (initializer_list != null) {
919
				var cdecl = new CCodeDeclaration (get_ccode_const_name (c.type_reference));
920 921
				var arr = "";
				if (c.type_reference is ArrayType) {
922
					arr = "[%d]".printf (initializer_list.size);
923
				}
924

925
				var cinitializer = get_cvalue (c.value);
926
				if (!definition) {
927 928 929 930 931
					// never output value in header
					// special case needed as this method combines declaration and definition
					cinitializer = null;
				}

932
				cdecl.add_declarator (new CCodeVariableDeclarator ("%s%s".printf (get_ccode_name (c), arr), cinitializer));
933 934 935 936 937
				if (c.is_private_symbol ()) {
					cdecl.modifiers = CCodeModifiers.STATIC;
				} else {
					cdecl.modifiers = CCodeModifiers.EXTERN;
				}
938

939 940
				decl_space.add_constant_declaration (cdecl);
			} else {
941
				var cdefine = new CCodeMacroReplacement.with_expression (get_ccode_name (c), get_cvalue (c.value));
942 943
				decl_space.add_type_member_declaration (cdefine);
			}
944 945 946 947
		}
	}

	public override void visit_constant (Constant c) {
948 949
		push_line (c.source_reference);

950 951 952 953 954 955 956
		if (c.parent_symbol is Block) {
			// local constant

			generate_type_declaration (c.type_reference, cfile);

			c.value.emit (this);

957
			string type_name = get_ccode_const_name (c.type_reference);
958 959 960 961 962 963 964 965 966 967 968 969
			string arr = "";
			if (c.type_reference is ArrayType) {
				arr = "[]";
			}

			if (c.type_reference.compatible (string_type)) {
				type_name = "const char";
				arr = "[]";
			}

			var cinitializer = get_cvalue (c.value);

970
			ccode.add_declaration (type_name, new CCodeVariableDeclarator ("%s%s".printf (get_ccode_name (c), arr), cinitializer), CCodeModifiers.STATIC);
971 972
		} else {
			generate_constant_declaration (c, cfile, true);
973

974 975 976 977 978 979
			if (!c.is_internal_symbol ()) {
				generate_constant_declaration (c, header_file);
			}
			if (!c.is_private_symbol ()) {
				generate_constant_declaration (c, internal_header_file);
			}
980 981
		}

982
		pop_line ();
983 984
	}

985
	public void generate_field_declaration (Field f, CCodeFile decl_space) {
986
		if (add_symbol_declaration (decl_space, f, get_ccode_name (f))) {
987 988 989
			return;
		}

Jürg Billeter's avatar
Jürg Billeter committed
990
		generate_type_declaration (f.variable_type, decl_space);
991

992
		var cdecl = new CCodeDeclaration (get_ccode_name (f.variable_type));
993
		cdecl.add_declarator (new CCodeVariableDeclarator (get_ccode_name (f), null, get_ccode_declarator_suffix (f.variable_type)));
994 995 996 997 998
		if (f.is_private_symbol ()) {
			cdecl.modifiers = CCodeModifiers.STATIC;
		} else {
			cdecl.modifiers = CCodeModifiers.EXTERN;
		}
999
		if (f.version.deprecated) {
1000 1001
			cdecl.modifiers |= CCodeModifiers.DEPRECATED;
		}
1002 1003 1004
		if (f.is_volatile) {
			cdecl.modifiers |= CCodeModifiers.VOLATILE;
		}
1005 1006
		decl_space.add_type_member_declaration (cdecl);

1007 1008
		if (f.get_lock_used ()) {
			// Declare mutex for static member
1009 1010
			var flock = new CCodeDeclaration (get_ccode_name (mutex_type));
			var flock_decl =  new CCodeVariableDeclarator (get_symbol_lock_name (get_ccode_name (f)), new CCodeConstant ("{0}"));
1011 1012 1013 1014
			flock.add_declarator (flock_decl);

			if (f.is_private_symbol ()) {
				flock.modifiers = CCodeModifiers.STATIC;
1015 1016
			} else if (context.hide_internal && f.is_internal_symbol ()) {
				flock.modifiers = CCodeModifiers.INTERNAL;
1017 1018 1019 1020 1021 1022
			} else {
				flock.modifiers = CCodeModifiers.EXTERN;
			}
			decl_space.add_type_member_declaration (flock);
		}

1023
		if (f.variable_type is ArrayType && get_ccode_array_length (f)) {
Jürg Billeter's avatar
Jürg Billeter committed
1024
			var array_type = (ArrayType) f.variable_type;
1025

1026 1027 1028
			if (!array_type.fixed_length) {
				for (int dim = 1; dim <= array_type.rank; dim++) {
					var len_type = int_type.copy ();
1029

1030 1031
					cdecl = new CCodeDeclaration (get_ccode_name (len_type));
					cdecl.add_declarator (new CCodeVariableDeclarator (get_array_length_cname (get_ccode_name (f), dim)));
1032 1033
					if (f.is_private_symbol ()) {
						cdecl.modifiers = CCodeModifiers.STATIC;
1034 1035
					} else if (context.hide_internal && f.is_internal_symbol ()) {
						cdecl.modifiers = CCodeModifiers.INTERNAL;
1036 1037 1038 1039
					} else {
						cdecl.modifiers = CCodeModifiers.EXTERN;
					}
					decl_space.add_type_member_declaration (cdecl);
1040 1041
				}
			}
Jürg Billeter's avatar
Jürg Billeter committed
1042 1043
		} else if (f.variable_type is DelegateType) {
			var delegate_type = (DelegateType) f.variable_type;
1044 1045 1046 1047
			if (delegate_type.delegate_symbol.has_target) {
				// create field to store delegate target

				cdecl = new CCodeDeclaration ("gpointer");
1048
				cdecl.add_declarator (new CCodeVariableDeclarator (get_ccode_delegate_target_name (f)));
1049 1050
				if (f.is_private_symbol ()) {
					cdecl.modifiers = CCodeModifiers.STATIC;
1051 1052
				} else if (context.hide_internal && f.is_internal_symbol ()) {
					cdecl.modifiers = CCodeModifiers.INTERNAL;
1053 1054 1055 1056
				} else {
					cdecl.modifiers = CCodeModifiers.EXTERN;
				}
				decl_space.add_type_member_declaration (cdecl);
1057

1058
				if (delegate_type.value_owned && !delegate_type.is_called_once) {
1059
					cdecl = new CCodeDeclaration ("GDestroyNotify");
1060
					cdecl.add_declarator (new CCodeVariableDeclarator (get_delegate_target_destroy_notify_cname  (get_ccode_name (f))));
1061 1062
					if (f.is_private_symbol ()) {
						cdecl.modifiers = CCodeModifiers.STATIC;
1063 1064
					} else if (context.hide_internal && f.is_internal_symbol ()) {
						cdecl.modifiers = CCodeModifiers.INTERNAL;
1065 1066 1067 1068 1069
					} else {
						cdecl.modifiers = CCodeModifiers.EXTERN;
					}
					decl_space.add_type_member_declaration (cdecl);
				}
Jürg Billeter's avatar
Jürg Billeter committed
1070
			}
1071 1072 1073 1074
		}
	}

	public override void visit_field (Field f) {
1075
		push_line (f.source_reference);
Jürg Billeter's avatar
Jürg Billeter committed
1076 1077
		visit_member (f);

Jürg Billeter's avatar
Jürg Billeter committed
1078
		check_type (f.variable_type);
1079

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

		CCodeExpression lhs = null;
1084

1085 1086
		if (f.binding == MemberBinding.INSTANCE)  {
			if (is_gtypeinstance && f.access == SymbolAccessibility.PRIVATE) {
1087
				lhs = new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), "priv"), get_ccode_name (f));
1088
			} else {
1089
				lhs = new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), get_ccode_name (f));
1090 1091 1092
			}

			if (f.initializer != null) {
1093 1094 1095 1096
				push_context (instance_init_context);

				f.initializer.emit (this);

1097
				var rhs = get_cvalue (f.initializer);
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
				if (!is_simple_struct_creation (f, f.initializer)) {
					// otherwise handled in visit_object_creation_expression
					
					ccode.add_assignment (lhs, rhs);
					
					if (f.variable_type is ArrayType && get_ccode_array_length (f)) {
						var array_type = (ArrayType) f.variable_type;
						var field_value = get_field_cvalue (f, load_this_parameter ((TypeSymbol) f.parent_symbol));
						
						var glib_value = (GLibValue) f.initializer.target_value;
						if (glib_value.array_length_cvalues != null) {
							for (int dim = 1; dim <= array_type.rank; dim++) {
								var array_len_lhs = get_array_length_cvalue (field_value, dim);
								ccode.add_assignment (array_len_lhs, get_array_length_cvalue (glib_value, dim));
							}
						} else if (glib_value.array_null_terminated) {
							requires_array_length = true;
							var len_call = new CCodeFunctionCall (new CCodeIdentifier ("_vala_array_length"));
							len_call.add_argument (get_cvalue_ (glib_value));
							
							ccode.add_assignment (get_array_length_cvalue (field_value, 1), len_call);
						} else {
							for (int dim = 1; dim <= array_type.rank; dim++) {
								ccode.add_assignment (get_array_length_cvalue (field_value, dim), new CCodeConstant ("-1"));
							}
1123
						}
1124 1125 1126 1127 1128
						
						if (array_type.rank == 1 && f.is_internal_symbol ()) {
							var lhs_array_size = get_array_size_cvalue (field_value);
							var rhs_array_len = get_array_length_cvalue (field_value, 1);
							ccode.add_assignment (lhs_array_size, rhs_array_len);
1129
						}
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
					} else if (f.variable_type is DelegateType) {
						var delegate_type = (DelegateType) f.variable_type;
						if (delegate_type.delegate_symbol.has_target) {
							var field_value = get_field_cvalue (f, load_this_parameter ((TypeSymbol) f.parent_symbol));

							ccode.add_assignment (get_delegate_target_cvalue (field_value), new CCodeIdentifier ("self"));
							if (delegate_type.is_disposable ()) {
								ccode.add_assignment (get_delegate_target_destroy_notify_cvalue (field_value), new CCodeIdentifier ("NULL"));
							}
						}
1140 1141
					}
				}
1142

1143 1144
				foreach (var value in temp_ref_values) {
					ccode.add_expression (destroy_value (value));
1145 1146
				}

1147
				temp_ref_values.clear ();
1148 1149

				pop_context ();
1150 1151
			}
			
1152 1153
			if (requires_destroy (f.variable_type) && instance_finalize_context != null) {
				push_context (instance_finalize_context);
1154
				ccode.add_expression (destroy_field (f, load_this_parameter ((TypeSymbol) f.parent_symbol)));
1155
				pop_context ();
1156 1157
			}
		} else if (f.binding == MemberBinding.CLASS)  {
1158 1159 1160 1161 1162
			if (!is_gtypeinstance) {
				Report.error (f.source_reference, "class fields are not supported in compact classes");
				f.error = true;
				return;
			}
1163 1164

			if (f.access == SymbolAccessibility.PRIVATE) {
1165
				var ccall = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS_PRIVATE".printf (get_ccode_upper_case_name (cl))));
1166
				ccall.add_argument (new CCodeIdentifier ("klass"));
1167
				lhs = new CCodeMemberAccess (ccall, get_ccode_name (f), true);
1168
			} else {
1169
				lhs = new CCodeMemberAccess (new CCodeIdentifier ("klass"), get_ccode_name (f), true);
1170 1171 1172
			}

			if (f.initializer != null) {
1173 1174 1175
				push_context (class_init_context);

				f.initializer.emit (this);
1176

1177
				var rhs = get_cvalue (f.initializer);
1178

1179
				ccode.add_assignment (lhs, rhs);
1180

1181 1182
				foreach (var value in temp_ref_values) {
					ccode.add_expression (destroy_value (value));
1183 1184
				}

1185
				temp_ref_values.clear ();
1186 1187

				pop_context ();
1188
			}
1189
		} else {
1190
			generate_field_declaration (f, cfile);
1191 1192

			if (!f.is_internal_symbol ()) {
1193
				generate_field_declaration (f, header_file);
1194
			}
1195
			if (!f.is_private_symbol ()) {
1196
				generate_field_declaration (f, internal_header_file);
1197
			}
1198

1199 1200
			if (!f.external) {
				lhs = new CCodeIdentifier (get_ccode_name (f));
1201

1202 1203
				var var_decl = new CCodeVariableDeclarator (get_ccode_name (f), null, get_ccode_declarator_suffix (f.variable_type));
				var_decl.initializer = default_value_for_type (f.variable_type, true);
1204

1205 1206 1207 1208 1209
				if (class_init_context != null) {
					push_context (class_init_context);
				} else {
					push_context (new EmitContext ());
				}
1210

1211 1212
				if (f.initializer != null) {
					f.initializer.emit (this);
1213

1214 1215 1216 1217
					var init = get_cvalue (f.initializer);
					if (is_constant_ccode_expression (init)) {
						var_decl.initializer = init;
					}
1218 1219
				}

1220
				var var_def = new CCodeDeclaration (get_ccode_name (f.variable_type));
1221 1222 1223 1224 1225 1226
				var_def.add_declarator (var_decl);
				if (!f.is_private_symbol ()) {
					var_def.modifiers = CCodeModifiers.EXTERN;
				} else {
					var_def.modifiers = CCodeModifiers.STATIC;
				}
1227 1228 1229 1230 1231 1232
				if (f.version.deprecated) {
					var_def.modifiers |= CCodeModifiers.DEPRECATED;
				}
				if (f.is_volatile) {
					var_def.modifiers |= CCodeModifiers.VOLATILE;
				}
1233
				cfile.add_type_member_declaration (var_def);
1234

1235 1236 1237
				/* add array length fields where necessary */
				if (f.variable_type is ArrayType && get_ccode_array_length (f)) {
					var array_type = (ArrayType) f.variable_type;
1238

1239 1240 1241
					if (!array_type.fixed_length) {
						for (int dim = 1; dim <= array_type.rank; dim++) {
							var len_type = int_type.copy ();
1242

1243 1244 1245 1246 1247 1248 1249 1250
							var len_def = new CCodeDeclaration (get_ccode_name (len_type));
							len_def.add_declarator (new CCodeVariableDeclarator (get_array_length_cname (get_ccode_name (f), dim), new CCodeConstant ("0")));
							if (!f.is_private_symbol ()) {
								len_def.modifiers = CCodeModifiers.EXTERN;
							} else {
								len_def.modifiers = CCodeModifiers.STATIC;
							}
							cfile.add_type_member_declaration (len_def);
1251
						}
1252

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

1256 1257 1258 1259 1260
							var cdecl = new CCodeDeclaration (get_ccode_name (len_type));
							cdecl.add_declarator (new CCodeVariableDeclarator (get_array_size_cname (get_ccode_name (f)), new CCodeConstant ("0")));
							cdecl.modifiers = CCodeModifiers.STATIC;
							cfile.add_type_member_declaration (cdecl);
						}
1261
					}
1262 1263 1264 1265
				} else if (f.variable_type is DelegateType) {
					var delegate_type = (DelegateType) f.variable_type;
					if (delegate_type.delegate_symbol.has_target) {
						// create field to store delegate target
1266

1267
						var target_def = new CCodeDeclaration ("gpointer");
1268
						target_def.add_declarator (new CCodeVariableDeclarator (get_ccode_delegate_target_name (f), new CCodeConstant ("NULL")));
1269
						if (!f.is_private_symbol ()) {
1270
							target_def.modifiers = CCodeModifiers.EXTERN;
1271
						} else {
1272
							target_def.modifiers = CCodeModifiers.STATIC;
</