valacodegeneratormethod.vala 16.5 KB
Newer Older
Jürg Billeter's avatar
Jürg Billeter committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* valacodegeneratormethod.vala
 *
 * Copyright (C) 2006-2007  Jürg Billeter, Raffaele Sandrini
 *
 * 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 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>
 *	Raffaele Sandrini <rasa@gmx.ch>
 */

using GLib;

public class Vala.CodeGenerator {
27
	public override void visit_method (Method! m) {
Jürg Billeter's avatar
Jürg Billeter committed
28 29
		current_symbol = m.symbol;
		current_return_type = m.return_type;
30 31 32

		if (m is CreationMethod) {
			in_creation_method = true;
Jürg Billeter's avatar
Jürg Billeter committed
33 34
		}

35 36 37 38 39
		m.accept_children (this);

		if (m is CreationMethod) {
			if (current_class != null && m.body != null) {
				add_object_creation ((CCodeBlock) m.body.ccodenode);
Jürg Billeter's avatar
Jürg Billeter committed
40
			}
41 42

			in_creation_method = false;
Jürg Billeter's avatar
Jürg Billeter committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
		}

		current_symbol = current_symbol.parent_symbol;
		current_return_type = null;

		if (current_type_symbol != null && current_type_symbol.node is Interface) {
			var iface = (Interface) current_type_symbol.node;
			if (iface.is_static) {
				return;
			}
		}

		if (current_symbol.parent_symbol != null &&
		    current_symbol.parent_symbol.node is Method) {
			/* lambda expressions produce nested methods */
			var up_method = (Method) current_symbol.parent_symbol.node;
			current_return_type = up_method.return_type;
		}

		function = new CCodeFunction (m.get_real_cname (), m.return_type.get_cname ());
		CCodeFunctionDeclarator vdeclarator = null;
		
		CCodeFormalParameter instance_param = null;
		
		if (m.instance) {
			var this_type = new TypeReference ();
			this_type.data_type = find_parent_type (m);
			if (m.base_interface_method != null) {
				var base_type = new TypeReference ();
				base_type.data_type = (DataType) m.base_interface_method.symbol.parent_symbol.node;
				instance_param = new CCodeFormalParameter ("base", base_type.get_cname ());
			} else if (m.overrides) {
				var base_type = new TypeReference ();
				base_type.data_type = (DataType) m.base_method.symbol.parent_symbol.node;
				instance_param = new CCodeFormalParameter ("base", base_type.get_cname ());
			} else {
				if (m.instance_by_reference) {
					instance_param = new CCodeFormalParameter ("*self", this_type.get_cname ());
				} else {
					instance_param = new CCodeFormalParameter ("self", this_type.get_cname ());
				}
			}
			if (!m.instance_last) {
				function.add_parameter (instance_param);
			}
			
			if (m.is_abstract || m.is_virtual) {
				var vdecl = new CCodeDeclaration (m.return_type.get_cname ());
				vdeclarator = new CCodeFunctionDeclarator (m.name);
				vdecl.add_declarator (vdeclarator);
				type_struct.add_declaration (vdecl);

				vdeclarator.add_parameter (instance_param);
			}
		}

		if (m is CreationMethod && current_class != null) {
			// memory management for generic types
			foreach (TypeParameter type_param in current_class.get_type_parameters ()) {
				var cparam = new CCodeFormalParameter ("%s_destroy_func".printf (type_param.name.down ()), "GDestroyNotify");
				function.add_parameter (cparam);
			}
		}

		var params = m.get_parameters ();
		foreach (FormalParameter param in params) {
			if (!param.no_array_length && param.type_reference.data_type is Array) {
				var arr = (Array) param.type_reference.data_type;
				
				var length_ctype = "int";
				if (param.type_reference.is_out) {
					length_ctype = "int*";
				}
				
				for (int dim = 1; dim <= arr.rank; dim++) {
					var cparam = new CCodeFormalParameter (get_array_length_cname (param.name, dim), length_ctype);
					function.add_parameter (cparam);
					if (vdeclarator != null) {
						vdeclarator.add_parameter (cparam);
					}
				}
			}
		
			function.add_parameter ((CCodeFormalParameter) param.ccodenode);
			if (vdeclarator != null) {
				vdeclarator.add_parameter ((CCodeFormalParameter) param.ccodenode);
			}
		}
		
		if (m.instance && m.instance_last) {
			function.add_parameter (instance_param);
		}

		/* real function declaration and definition not needed
		 * for abstract methods */
		if (!m.is_abstract) {
			if (m.access != MemberAccessibility.PRIVATE && m.base_method == null && m.base_interface_method == null) {
				/* public methods need function declaration in
				 * header file except virtual/overridden methods */
				header_type_member_declaration.append (function.copy ());
			} else {
				/* declare all other functions in source file to
				 * avoid dependency on order within source file */
				function.modifiers |= CCodeModifiers.STATIC;
				source_type_member_declaration.append (function.copy ());
			}
			
			/* Methods imported from a plain C file don't
			 * have a body, e.g. Vala.Parser.parse_file () */
			if (m.body != null) {
				function.block = (CCodeBlock) m.body.ccodenode;

				var cinit = new CCodeFragment ();
				function.block.prepend_statement (cinit);

				if (m.symbol.parent_symbol.node is Class) {
					var cl = (Class) m.symbol.parent_symbol.node;
					if (m.overrides || m.base_interface_method != null) {
						var ccall = new CCodeFunctionCall (new CCodeIdentifier (cl.get_upper_case_cname (null)));
						ccall.add_argument (new CCodeIdentifier ("base"));
						
						var cdecl = new CCodeDeclaration ("%s *".printf (cl.get_cname ()));
						cdecl.add_declarator (new CCodeVariableDeclarator.with_initializer ("self", ccall));
						
						cinit.append (cdecl);
					} else if (m.instance) {
						cinit.append (create_method_type_check_statement (m, cl, true, "self"));
					}
				}
				foreach (FormalParameter param in m.get_parameters ()) {
					var t = param.type_reference.data_type;
					if (t != null && t.is_reference_type () && !param.type_reference.is_out) {
						var type_check = create_method_type_check_statement (m, t, param.type_reference.non_null, param.name);
						if (type_check != null) {
							cinit.append (type_check);
						}
					}
				}

				if (m.source_reference != null && m.source_reference.comment != null) {
					source_type_member_definition.append (new CCodeComment (m.source_reference.comment));
				}
				source_type_member_definition.append (function);
				
				if (m is CreationMethod) {
					if (current_class != null) {
						int n_params = ((CreationMethod) m).n_construction_params;
						n_params += (int) current_class.get_type_parameters ().length ();

						// declare construction parameter array
						var cparamsinit = new CCodeFunctionCall (new CCodeIdentifier ("g_new0"));
						cparamsinit.add_argument (new CCodeIdentifier ("GParameter"));
						cparamsinit.add_argument (new CCodeConstant (n_params.to_string ()));
						
						var cdecl = new CCodeDeclaration ("GParameter *");
						cdecl.add_declarator (new CCodeVariableDeclarator.with_initializer ("__params", cparamsinit));
						cinit.append (cdecl);
						
						cdecl = new CCodeDeclaration ("GParameter *");
						cdecl.add_declarator (new CCodeVariableDeclarator.with_initializer ("__params_it", new CCodeIdentifier ("__params")));
						cinit.append (cdecl);

						/* destroy func properties for generic types */
						foreach (TypeParameter type_param in current_class.get_type_parameters ()) {
							string func_name = "%s_destroy_func".printf (type_param.name.down ());
							var func_name_constant = new CCodeConstant ("\"%s-destroy-func\"".printf (type_param.name.down ()));

							// this property is used as a construction parameter
							var cpointer = new CCodeIdentifier ("__params_it");

							var ccomma = new CCodeCommaExpression ();
							// set name in array for current parameter
							var cnamemember = new CCodeMemberAccess.pointer (cpointer, "name");
							ccomma.append_expression (new CCodeAssignment (cnamemember, func_name_constant));
							var gvaluearg = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, new CCodeMemberAccess.pointer (cpointer, "value"));

							// initialize GValue in array for current parameter
							var cvalueinit = new CCodeFunctionCall (new CCodeIdentifier ("g_value_init"));
							cvalueinit.add_argument (gvaluearg);
							cvalueinit.add_argument (new CCodeIdentifier ("G_TYPE_POINTER"));
							ccomma.append_expression (cvalueinit);

							// set GValue for current parameter
							var cvalueset = new CCodeFunctionCall (new CCodeIdentifier ("g_value_set_pointer"));
							cvalueset.add_argument (gvaluearg);
							cvalueset.add_argument (new CCodeIdentifier (func_name));
							ccomma.append_expression (cvalueset);

							// move pointer to next parameter in array
							ccomma.append_expression (new CCodeUnaryExpression (CCodeUnaryOperator.POSTFIX_INCREMENT, cpointer));

							cinit.append (new CCodeExpressionStatement (ccomma));
						}
					} else {
						var st = (Struct) m.symbol.parent_symbol.node;
						var cdecl = new CCodeDeclaration (st.get_cname () + "*");
						var ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_new0"));
						ccall.add_argument (new CCodeConstant (st.get_cname ()));
						ccall.add_argument (new CCodeConstant ("1"));
						cdecl.add_declarator (new CCodeVariableDeclarator.with_initializer ("self", ccall));
						cinit.append (cdecl);
					}
				}

				if (context.module_init_method == m && in_plugin) {
					// GTypeModule-based plug-in, register types
					cinit.append (module_init_fragment);
				}
			}
		}
		
		if (m.is_abstract || m.is_virtual) {
			var vfunc = new CCodeFunction (m.get_cname (), m.return_type.get_cname ());

			var this_type = new TypeReference ();
			this_type.data_type = (DataType) m.symbol.parent_symbol.node;

			var cparam = new CCodeFormalParameter ("self", this_type.get_cname ());
			vfunc.add_parameter (cparam);
			
			var vblock = new CCodeBlock ();
			
			CCodeFunctionCall vcast = null;
			if (m.symbol.parent_symbol.node is Interface) {
				var iface = (Interface) m.symbol.parent_symbol.node;

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

				vcast = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS".printf (cl.get_upper_case_cname (null))));
			}
			vcast.add_argument (new CCodeIdentifier ("self"));
		
			var vcall = new CCodeFunctionCall (new CCodeMemberAccess.pointer (vcast, m.name));
			vcall.add_argument (new CCodeIdentifier ("self"));
		
			var params = m.get_parameters ();
			foreach (FormalParameter param in params) {
				vfunc.add_parameter ((CCodeFormalParameter) param.ccodenode);
				vcall.add_argument (new CCodeIdentifier (param.name));
			}

			if (m.return_type.data_type == null) {
				vblock.add_statement (new CCodeExpressionStatement (vcall));
			} else {
				/* pass method return value */
				vblock.add_statement (new CCodeReturnStatement (vcall));
			}

			header_type_member_declaration.append (vfunc.copy ());
			
			vfunc.block = vblock;
			
			source_type_member_definition.append (vfunc);
		}
		
		if (m is CreationMethod) {
			var creturn = new CCodeReturnStatement ();
			creturn.return_expression = new CCodeIdentifier ("self");
			function.block.add_statement (creturn);
		}
		
		bool return_value = true;
		bool args_parameter = true;
		if (is_possible_entry_point (m, ref return_value, ref args_parameter)) {
			// m is possible entry point, add appropriate startup code
			var cmain = new CCodeFunction ("main", "int");
			cmain.add_parameter (new CCodeFormalParameter ("argc", "int"));
			cmain.add_parameter (new CCodeFormalParameter ("argv", "char **"));
			var main_block = new CCodeBlock ();
314 315 316 317 318 319 320

			if (context.thread) {
				var thread_init_call = new CCodeFunctionCall (new CCodeIdentifier ("g_thread_init"));
				thread_init_call.add_argument (new CCodeConstant ("NULL"));
				main_block.add_statement (new CCodeExpressionStatement (thread_init_call)); 
			}

Jürg Billeter's avatar
Jürg Billeter committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
			main_block.add_statement (new CCodeExpressionStatement (new CCodeFunctionCall (new CCodeIdentifier ("g_type_init"))));
			var main_call = new CCodeFunctionCall (new CCodeIdentifier (function.name));
			if (args_parameter) {
				main_call.add_argument (new CCodeIdentifier ("argc"));
				main_call.add_argument (new CCodeIdentifier ("argv"));
			}
			if (return_value) {
				main_block.add_statement (new CCodeReturnStatement (main_call));
			} else {
				// method returns void, always use 0 as exit code
				main_block.add_statement (new CCodeExpressionStatement (main_call));
				main_block.add_statement (new CCodeReturnStatement (new CCodeConstant ("0")));
			}
			cmain.block = main_block;
			source_type_member_definition.append (cmain);
		}
	}
	
339
	private CCodeStatement create_method_type_check_statement (Method! m, DataType! t, bool non_null, string! var_name) {
340
		return create_type_check_statement (m, m.return_type.data_type, t, non_null, var_name);
Jürg Billeter's avatar
Jürg Billeter committed
341 342
	}
	
343
	private CCodeStatement create_property_type_check_statement (Property! prop, bool getter, DataType! t, bool non_null, string! var_name) {
344 345 346 347 348 349 350
		if (getter) {
			return create_type_check_statement (prop, prop.type_reference.data_type, t, non_null, var_name);
		} else {
			return create_type_check_statement (prop, null, t, non_null, var_name);
		}
	}
	
351
	private CCodeStatement create_type_check_statement (CodeNode! method_node, DataType ret_type, DataType! t, bool non_null, string! var_name) {
352 353 354 355 356 357
		var ccheck = new CCodeFunctionCall ();
		
		if (t is Class || t is Interface) {
			var ctype_check = new CCodeFunctionCall (new CCodeIdentifier (t.get_upper_case_cname ("IS_")));
			ctype_check.add_argument (new CCodeIdentifier (var_name));
			
358
			CCodeExpression cexpr = ctype_check;
359 360 361 362 363 364 365 366 367 368 369
			if (!non_null) {
				var cnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier (var_name), new CCodeConstant ("NULL"));
			
				cexpr = new CCodeBinaryExpression (CCodeBinaryOperator.OR, cnull, ctype_check);
			}
			ccheck.add_argument (cexpr);
		} else if (!non_null) {
			return null;
		} else {
			var cnonnull = new CCodeBinaryExpression (CCodeBinaryOperator.INEQUALITY, new CCodeIdentifier (var_name), new CCodeConstant ("NULL"));
			ccheck.add_argument (cnonnull);
Jürg Billeter's avatar
Jürg Billeter committed
370
		}
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
		
		if (ret_type == null) {
			/* void function */
			ccheck.call = new CCodeIdentifier ("g_return_if_fail");
		} else {
			ccheck.call = new CCodeIdentifier ("g_return_val_if_fail");
			
			if (ret_type.is_reference_type () || ret_type is Pointer) {
				ccheck.add_argument (new CCodeConstant ("NULL"));
			} else if (ret_type.get_default_value () != null) {
				ccheck.add_argument (new CCodeConstant (ret_type.get_default_value ()));
			} else {
				Report.warning (method_node.source_reference, "not supported return type for runtime type checks");
				return new CCodeExpressionStatement (new CCodeConstant ("0"));
			}
		}
		
		return new CCodeExpressionStatement (ccheck);
	}
Jürg Billeter's avatar
Jürg Billeter committed
390

391 392 393 394 395 396 397 398 399 400 401
	private DataType find_parent_type (CodeNode node) {
		var sym = node.symbol;
		while (sym != null) {
			if (sym.node is DataType) {
				return (DataType) sym.node;
			}
			sym = sym.parent_symbol;
		}
		return null;
	}
	
402
	private string! get_array_length_cname (string! array_cname, int dim) {
403 404
		return "%s_length%d".printf (array_cname, dim);
	}
Jürg Billeter's avatar
Jürg Billeter committed
405

406 407
	public override void visit_creation_method (CreationMethod! m) {
		visit_method (m);
Jürg Billeter's avatar
Jürg Billeter committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
	}
	
	private bool is_possible_entry_point (Method! m, ref bool return_value, ref bool args_parameter) {
		if (m.name == null || m.name != "main") {
			// method must be called "main"
			return false;
		}
		
		if (m.instance) {
			// method must be static
			return false;
		}
		
		if (m.return_type.data_type == null) {
			return_value = false;
		} else if (m.return_type.data_type == int_type.data_type) {
			return_value = true;
		} else {
			// return type must be void or int
			return false;
		}
		
		var params = m.get_parameters ();
		if (params.length () == 0) {
			// method may have no parameters
			args_parameter = false;
			return true;
		}
		
		if (params.length () > 1) {
			// method must not have more than one parameter
			return false;
		}
		
		var param = (FormalParameter) params.data;

		if (param.type_reference.is_out) {
			// parameter must not be an out parameter
			return false;
		}
		
		if (!(param.type_reference.data_type is Array)) {
			// parameter must be an array
			return false;
		}
		
		var array_type = (Array) param.type_reference.data_type;
		if (array_type.element_type != string_type.data_type) {
			// parameter must be an array of strings
			return false;
		}
		
		args_parameter = true;
		return true;
	}
}