summaryrefslogtreecommitdiff
path: root/vala/valaobjectcreationexpression.vala
blob: 19063a9d07dd44bf919f3dae8a2c5144679ff21a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
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
465
466
467
468
469
470
471
472
473
474
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/* valaobjectcreationexpression.vala
 *
 * Copyright (C) 2006-2012  Jürg Billeter
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

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

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

using GLib;

/**
 * Represents an object creation expression in the source code.
 */
public class Vala.ObjectCreationExpression : Expression {
	/**
	 * The object type to create.
	 */
	public DataType type_reference {
		get { return _data_type; }
		set {
			_data_type = value;
			_data_type.parent_node = this;
		}
	}

	/**
	 * The construction method to use or the data type to be created
	 * with the default construction method.
	 */
	public MemberAccess? member_name {
		get { return _member_name; }
		set {
			_member_name = value;
			if (_member_name != null) {
				_member_name.parent_node = this;
			}
		}
	}

	public bool is_yield_expression { get; set; }

	public bool struct_creation { get; set; }

	private List<Expression> argument_list = new ArrayList<Expression> ();

	private List<MemberInitializer> object_initializer = new ArrayList<MemberInitializer> ();

	private DataType _data_type;
	private MemberAccess? _member_name;

	/**
	 * Creates a new object creation expression.
	 *
	 * @param member_name      object type to create
	 * @param source_reference reference to source code
	 * @return                 newly created object creation expression
	 */
	public ObjectCreationExpression (MemberAccess? member_name, SourceReference? source_reference = null) {
		this.source_reference = source_reference;
		this.member_name = member_name;
	}

	/**
	 * Appends the specified expression to the list of arguments.
	 *
	 * @param arg an argument
	 */
	public void add_argument (Expression arg) {
		argument_list.add (arg);
		arg.parent_node = this;
	}

	/**
	 * Returns the argument list.
	 *
	 * @return argument list
	 */
	public unowned List<Expression> get_argument_list () {
		return argument_list;
	}

	/**
	 * Appends the specified member initializer to the object initializer.
	 *
	 * @param init a member initializer
	 */
	public void add_member_initializer (MemberInitializer init) {
		object_initializer.add (init);
		init.parent_node = this;
	}

	/**
	 * Returns the object initializer.
	 *
	 * @return member initializer list
	 */
	public unowned List<MemberInitializer> get_object_initializer () {
		return object_initializer;
	}

	public override void accept (CodeVisitor visitor) {
		visitor.visit_object_creation_expression (this);

		visitor.visit_expression (this);
	}

	public override void accept_children (CodeVisitor visitor) {
		if (type_reference != null) {
			type_reference.accept (visitor);
		}

		if (member_name != null) {
			member_name.accept (visitor);
		}

		foreach (Expression arg in argument_list) {
			arg.accept (visitor);
		}

		foreach (MemberInitializer init in object_initializer) {
			init.accept (visitor);
		}
	}

	public override void replace_expression (Expression old_node, Expression new_node) {
		int index = argument_list.index_of (old_node);
		if (index >= 0) {
			argument_list[index] = new_node;
			new_node.parent_node = this;
		}
	}

	public override bool is_pure () {
		return false;
	}

	public override bool is_accessible (Symbol sym) {
		if (member_name != null && !member_name.is_accessible (sym)) {
			return false;
		}

		foreach (var arg in argument_list) {
			if (!arg.is_accessible (sym)) {
				return false;
			}
		}

		foreach (var init in object_initializer) {
			if (!init.initializer.is_accessible (sym)) {
				return false;
			}
		}

		return true;
	}

	public override void replace_type (DataType old_type, DataType new_type) {
		if (type_reference == old_type) {
			type_reference = new_type;
		}
	}

	public override bool check (CodeContext context) {
		if (checked) {
			return !error;
		}

		checked = true;

		if (member_name != null) {
			if (!member_name.check (context)) {
				error = true;
				return false;
			}
		}

		TypeSymbol type;

		if (type_reference == null) {
			if (member_name == null) {
				error = true;
				Report.error (source_reference, "Incomplete object creation expression");
				return false;
			}

			if (member_name.symbol_reference == null) {
				error = true;
				return false;
			}

			var constructor_sym = member_name.symbol_reference;
			var type_sym = member_name.symbol_reference;

			var type_args = member_name.get_type_arguments ();

			if (constructor_sym is Method) {
				type_sym = constructor_sym.parent_symbol;

				var constructor = (Method) constructor_sym;
				if (!(constructor_sym is CreationMethod)) {
					error = true;
					Report.error (source_reference, "`%s' is not a creation method".printf (constructor.get_full_name ()));
					return false;
				}

				symbol_reference = constructor;

				// inner expression can also be base access when chaining constructors
				var ma = member_name.inner as MemberAccess;
				if (ma != null) {
					type_args = ma.get_type_arguments ();
				}
			}

			if (type_sym is Class) {
				type = (TypeSymbol) type_sym;
				if (((Class) type).is_error_base) {
					type_reference = new ErrorType (null, null, source_reference);
				} else {
					type_reference = new ObjectType ((Class) type);
				}
			} else if (type_sym is Struct) {
				type = (TypeSymbol) type_sym;
				type_reference = new StructValueType ((Struct) type);
			} else if (type_sym is ErrorCode) {
				type = (TypeSymbol) type_sym;
				type_reference = new ErrorType ((ErrorDomain) type_sym.parent_symbol, (ErrorCode) type_sym, source_reference);
				symbol_reference = type_sym;
			} else {
				error = true;
				Report.error (source_reference, "`%s' is not a class, struct, or error code".printf (type_sym.get_full_name ()));
				return false;
			}

			foreach (DataType type_arg in type_args) {
				type_reference.add_type_argument (type_arg);
			}
		} else {
			type = type_reference.data_type;
		}

		value_type = type_reference.copy ();
		value_type.value_owned = true;

		int given_num_type_args = type_reference.get_type_arguments ().size;
		int expected_num_type_args = 0;

		if (type is Class) {
			var cl = (Class) type;

			expected_num_type_args = cl.get_type_parameters ().size;

			if (struct_creation) {
				error = true;
				Report.error (source_reference, "syntax error, use `new' to create new objects");
				return false;
			}

			if (cl.is_abstract) {
				value_type = null;
				error = true;
				Report.error (source_reference, "Can't create instance of abstract class `%s'".printf (cl.get_full_name ()));
				return false;
			}

			if (symbol_reference == null) {
				symbol_reference = cl.default_construction_method;

				if (symbol_reference == null) {
					error = true;
					Report.error (source_reference, "`%s' does not have a default constructor".printf (cl.get_full_name ()));
					return false;
				}

				// track usage for flow analyzer
				symbol_reference.used = true;
				symbol_reference.version.check (source_reference);
			}

			if (symbol_reference != null
			    && (symbol_reference.access == SymbolAccessibility.PRIVATE || symbol_reference.access == SymbolAccessibility.PROTECTED)) {
				bool in_target_type = false;
				for (Symbol this_symbol = context.analyzer.current_symbol; this_symbol != null; this_symbol = this_symbol.parent_symbol) {
					if (this_symbol == cl) {
						in_target_type = true;
						break;
					}
				}

				if (!in_target_type) {
					error = true;
					Report.error (source_reference, "Access to non-public constructor `%s' denied".printf (symbol_reference.get_full_name ()));
					return false;
				}
			}

			while (cl != null) {
				// FIXME: use target values in the codegen
				if (cl.get_attribute_string ("CCode", "ref_sink_function") != null) {
					value_type.floating_reference = true;
					break;
				}

				cl = cl.base_class;
			}
		} else if (type is Struct) {
			var st = (Struct) type;

			expected_num_type_args = st.get_type_parameters ().size;

			if (!struct_creation && !context.deprecated) {
				Report.warning (source_reference, "deprecated syntax, don't use `new' to initialize structs");
			}

			if (symbol_reference == null) {
				symbol_reference = st.default_construction_method;
			}

			if (context.profile == Profile.GOBJECT && st.is_simple_type () && symbol_reference == null && object_initializer.size == 0) {
				error = true;
				Report.error (source_reference, "`%s' does not have a default constructor".printf (st.get_full_name ()));
				return false;
			}
		}

		if (expected_num_type_args > given_num_type_args) {
			error = true;
			Report.error (source_reference, "too few type arguments");
			return false;
		} else if (expected_num_type_args < given_num_type_args) {
			error = true;
			Report.error (source_reference, "too many type arguments");
			return false;
		}

		if (symbol_reference == null && get_argument_list ().size != 0) {
			value_type = null;
			error = true;
			Report.error (source_reference, "No arguments allowed when constructing type `%s'".printf (type.get_full_name ()));
			return false;
		}

		if (symbol_reference is Method) {
			var m = (Method) symbol_reference;

			if (is_yield_expression) {
				if (!m.coroutine) {
					error = true;
					Report.error (source_reference, "yield expression requires async method");
				}
				if (context.analyzer.current_method == null || !context.analyzer.current_method.coroutine) {
					error = true;
					Report.error (source_reference, "yield expression not available outside async method");
				}
			}

			// FIXME partial code duplication of MethodCall.check

			Expression last_arg = null;

			var args = get_argument_list ();
			Iterator<Expression> arg_it = args.iterator ();
			foreach (Parameter param in m.get_parameters ()) {
				if (!param.check (context)) {
					error = true;
				}

				if (param.ellipsis) {
					break;
				}

				if (arg_it.next ()) {
					Expression arg = arg_it.get ();

					/* store expected type for callback parameters */
					arg.formal_target_type = param.variable_type;
					arg.target_type = arg.formal_target_type.get_actual_type (value_type, null, this);

					last_arg = arg;
				}
			}

			// printf arguments
			if (m.printf_format) {
				StringLiteral format_literal = null;
				if (last_arg is NullLiteral) {
					// do not replace explicit null
				} else if (last_arg != null) {
					// use last argument as format string
					format_literal = StringLiteral.get_format_literal (last_arg);
					if (format_literal == null && args.size == m.get_parameters ().size - 1) {
						// insert "%s" to avoid issues with embedded %
						format_literal = new StringLiteral ("\"%s\"");
						format_literal.target_type = context.analyzer.string_type.copy ();
						argument_list.insert (args.size - 1, format_literal);

						// recreate iterator and skip to right position
						arg_it = argument_list.iterator ();
						foreach (Parameter param in m.get_parameters ()) {
							if (param.ellipsis) {
								break;
							}
							arg_it.next ();
						}
					}
				}
				if (format_literal != null) {
					string format = format_literal.eval ();
					if (!context.analyzer.check_print_format (format, arg_it, source_reference)) {
						return false;
					}
				}
			}

			foreach (Expression arg in args) {
				arg.check (context);
			}

			context.analyzer.check_arguments (this, new MethodType (m), m.get_parameters (), args);
		} else if (type_reference is ErrorType) {
			if (type_reference != null) {
				type_reference.check (context);
			}

			if (member_name != null) {
				member_name.check (context);
			}

			foreach (Expression arg in argument_list) {
				arg.check (context);
			}

			foreach (MemberInitializer init in object_initializer) {
				init.check (context);
			}

			if (get_argument_list ().size == 0) {
				error = true;
				Report.error (source_reference, "Too few arguments, errors need at least 1 argument");
			} else {
				Iterator<Expression> arg_it = get_argument_list ().iterator ();
				arg_it.next ();
				var ex = arg_it.get ();
				if (ex.value_type == null || !ex.value_type.compatible (context.analyzer.string_type)) {
					error = true;
					Report.error (source_reference, "Invalid type for argument 1");
				}

				var format_literal = StringLiteral.get_format_literal (ex);
				if (format_literal != null) {
					var format = format_literal.eval ();
					if (!context.analyzer.check_print_format (format, arg_it, source_reference)) {
						error = true;
						return false;
					}
				}

				arg_it = get_argument_list ().iterator ();
				arg_it.next ();
				if (!context.analyzer.check_variadic_arguments (arg_it, 1, source_reference)) {
					error = true;
					return false;
				}
			}
		}

		//Resolve possible generic-type in SizeofExpression used as parameter default-value
		foreach (Expression arg in get_argument_list ()) {
			unowned SizeofExpression sizeof_expr = arg as SizeofExpression;
			if (sizeof_expr != null && sizeof_expr.type_reference is GenericType) {
				var sizeof_type = sizeof_expr.type_reference.get_actual_type (type_reference, type_reference.get_type_arguments (), this);
				replace_expression (arg, new SizeofExpression (sizeof_type, source_reference));
			}
		}

		if (!type.external_package) {
			context.analyzer.check_type (type_reference);
		}

		foreach (MemberInitializer init in get_object_initializer ()) {
			context.analyzer.visit_member_initializer (init, type_reference);
		}

		if (tree_can_fail) {
			if (parent_node is LocalVariable || parent_node is ExpressionStatement) {
				// simple statements, no side effects after method call
			} else if (!(context.analyzer.current_symbol is Block)) {
				// can't handle errors in field initializers
				Report.error (source_reference, "Field initializers must not throw errors");
			} else {
				// store parent_node as we need to replace the expression in the old parent node later on
				var old_parent_node = parent_node;

				var local = new LocalVariable (value_type.copy (), get_temp_name (), null, source_reference);
				var decl = new DeclarationStatement (local, source_reference);

				insert_statement (context.analyzer.insert_block, decl);

				var temp_access = SemanticAnalyzer.create_temp_access (local, target_type);
				// don't set initializer earlier as this changes parent_node and parent_statement
				local.initializer = this;
				decl.check (context);

				// move temp variable to insert block to ensure the
				// variable is in the same block as the declaration
				// otherwise there will be scoping issues in the generated code
				var block = (Block) context.analyzer.current_symbol;
				block.remove_local_variable (local);
				context.analyzer.insert_block.add_local_variable (local);

				old_parent_node.replace_expression (this, temp_access);
				temp_access.check (context);
			}
		}

		return !error;
	}

	public override void get_error_types (Collection<DataType> collection, SourceReference? source_reference = null) {
		if (symbol_reference is Method) {
			if (source_reference == null) {
				source_reference = this.source_reference;
			}
			var m = (Method) symbol_reference;
			m.get_error_types (collection, source_reference);
		}
	}

	public override void emit (CodeGenerator codegen) {
		foreach (Expression arg in argument_list) {
			arg.emit (codegen);
		}

		foreach (MemberInitializer init in object_initializer) {
			init.emit (codegen);
		}

		codegen.visit_object_creation_expression (this);

		codegen.visit_expression (this);
	}

	public override void get_defined_variables (Collection<Variable> collection) {
		foreach (Expression arg in argument_list) {
			arg.get_defined_variables (collection);
		}
	}

	public override void get_used_variables (Collection<Variable> collection) {
		foreach (Expression arg in argument_list) {
			arg.get_used_variables (collection);
		}

		foreach (MemberInitializer init in object_initializer) {
			init.get_used_variables (collection);
		}
	}
}