libgda-4.0, gedit-2.20: Fix gedit typo and GdaXaTransactionId.data
[vala-lang.git] / codegen / valaccodebasemodule.vala
blobbed29d4fd6d45615f3f9311fba66c95caafa2056
1 /* valaccodebasemodule.vala
3 * Copyright (C) 2006-2011 Jürg Billeter
4 * Copyright (C) 2006-2008 Raffaele Sandrini
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 * Author:
21 * Jürg Billeter <j@bitron.ch>
22 * Raffaele Sandrini <raffaele@sandrini.ch>
26 /**
27 * Code visitor generating C Code.
29 public abstract class Vala.CCodeBaseModule : CodeGenerator {
30 public class EmitContext {
31 public Symbol? current_symbol;
32 public ArrayList<Symbol> symbol_stack = new ArrayList<Symbol> ();
33 public TryStatement current_try;
34 public CatchClause current_catch;
35 public CCodeFunction ccode;
36 public ArrayList<CCodeFunction> ccode_stack = new ArrayList<CCodeFunction> ();
37 public ArrayList<LocalVariable> temp_ref_vars = new ArrayList<LocalVariable> ();
38 public int next_temp_var_id;
39 public bool current_method_inner_error;
40 public bool current_method_return;
41 public Map<string,string> variable_name_map = new HashMap<string,string> (str_hash, str_equal);
43 public EmitContext (Symbol? symbol = null) {
44 current_symbol = symbol;
47 public void push_symbol (Symbol symbol) {
48 symbol_stack.add (current_symbol);
49 current_symbol = symbol;
52 public void pop_symbol () {
53 current_symbol = symbol_stack[symbol_stack.size - 1];
54 symbol_stack.remove_at (symbol_stack.size - 1);
58 public CodeContext context { get; set; }
60 public Symbol root_symbol;
62 public EmitContext emit_context = new EmitContext ();
64 List<EmitContext> emit_context_stack = new ArrayList<EmitContext> ();
66 public Symbol current_symbol { get { return emit_context.current_symbol; } }
68 public TryStatement current_try {
69 get { return emit_context.current_try; }
70 set { emit_context.current_try = value; }
73 public CatchClause current_catch {
74 get { return emit_context.current_catch; }
75 set { emit_context.current_catch = value; }
78 public TypeSymbol? current_type_symbol {
79 get {
80 var sym = current_symbol;
81 while (sym != null) {
82 if (sym is TypeSymbol) {
83 return (TypeSymbol) sym;
85 sym = sym.parent_symbol;
87 return null;
91 public Class? current_class {
92 get { return current_type_symbol as Class; }
95 public Method? current_method {
96 get {
97 var sym = current_symbol;
98 while (sym is Block) {
99 sym = sym.parent_symbol;
101 return sym as Method;
105 public PropertyAccessor? current_property_accessor {
106 get {
107 var sym = current_symbol;
108 while (sym is Block) {
109 sym = sym.parent_symbol;
111 return sym as PropertyAccessor;
115 public DataType? current_return_type {
116 get {
117 var m = current_method;
118 if (m != null) {
119 return m.return_type;
122 var acc = current_property_accessor;
123 if (acc != null) {
124 if (acc.readable) {
125 return acc.value_type;
126 } else {
127 return void_type;
131 if (is_in_constructor () || is_in_destructor ()) {
132 return void_type;
135 return null;
139 public bool is_in_coroutine () {
140 return current_method != null && current_method.coroutine;
143 public bool is_in_constructor () {
144 if (current_method != null) {
145 // make sure to not return true in lambda expression inside constructor
146 return false;
148 var sym = current_symbol;
149 while (sym != null) {
150 if (sym is Constructor) {
151 return true;
153 sym = sym.parent_symbol;
155 return false;
158 public bool is_in_destructor () {
159 if (current_method != null) {
160 // make sure to not return true in lambda expression inside constructor
161 return false;
163 var sym = current_symbol;
164 while (sym != null) {
165 if (sym is Destructor) {
166 return true;
168 sym = sym.parent_symbol;
170 return false;
173 public Block? current_closure_block {
174 get {
175 return next_closure_block (current_symbol);
179 public unowned Block? next_closure_block (Symbol sym) {
180 while (true) {
181 unowned Method method = sym as Method;
182 if (method != null && !method.closure) {
183 // parent blocks are not captured by this method
184 break;
187 unowned Block block = sym as Block;
188 if (method == null && block == null) {
189 // no closure block
190 break;
193 if (block != null && block.captured) {
194 // closure block found
195 return block;
197 sym = sym.parent_symbol;
199 return null;
202 public CCodeFile header_file;
203 public CCodeFile internal_header_file;
204 public CCodeFile cfile;
206 public EmitContext class_init_context;
207 public EmitContext base_init_context;
208 public EmitContext class_finalize_context;
209 public EmitContext base_finalize_context;
210 public EmitContext instance_init_context;
211 public EmitContext instance_finalize_context;
213 public CCodeStruct param_spec_struct;
214 public CCodeStruct closure_struct;
215 public CCodeEnum prop_enum;
217 public CCodeFunction ccode { get { return emit_context.ccode; } }
219 /* temporary variables that own their content */
220 public ArrayList<LocalVariable> temp_ref_vars { get { return emit_context.temp_ref_vars; } }
221 /* cache to check whether a certain marshaller has been created yet */
222 public Set<string> user_marshal_set;
223 /* (constant) hash table with all predefined marshallers */
224 public Set<string> predefined_marshal_set;
225 /* (constant) hash table with all reserved identifiers in the generated code */
226 Set<string> reserved_identifiers;
228 public int next_temp_var_id {
229 get { return emit_context.next_temp_var_id; }
230 set { emit_context.next_temp_var_id = value; }
233 public int next_regex_id = 0;
234 public bool in_creation_method { get { return current_method is CreationMethod; } }
235 public bool in_constructor = false;
236 public bool in_static_or_class_context = false;
238 public bool current_method_inner_error {
239 get { return emit_context.current_method_inner_error; }
240 set { emit_context.current_method_inner_error = value; }
243 public bool current_method_return {
244 get { return emit_context.current_method_return; }
245 set { emit_context.current_method_return = value; }
248 public int next_coroutine_state = 1;
249 int next_block_id = 0;
250 Map<Block,int> block_map = new HashMap<Block,int> ();
252 public DataType void_type = new VoidType ();
253 public DataType bool_type;
254 public DataType char_type;
255 public DataType uchar_type;
256 public DataType? unichar_type;
257 public DataType short_type;
258 public DataType ushort_type;
259 public DataType int_type;
260 public DataType uint_type;
261 public DataType long_type;
262 public DataType ulong_type;
263 public DataType int8_type;
264 public DataType uint8_type;
265 public DataType int16_type;
266 public DataType uint16_type;
267 public DataType int32_type;
268 public DataType uint32_type;
269 public DataType int64_type;
270 public DataType uint64_type;
271 public DataType string_type;
272 public DataType regex_type;
273 public DataType float_type;
274 public DataType double_type;
275 public TypeSymbol gtype_type;
276 public TypeSymbol gobject_type;
277 public ErrorType gerror_type;
278 public Class glist_type;
279 public Class gslist_type;
280 public Class gnode_type;
281 public Class gvaluearray_type;
282 public TypeSymbol gstringbuilder_type;
283 public TypeSymbol garray_type;
284 public TypeSymbol gbytearray_type;
285 public TypeSymbol gptrarray_type;
286 public TypeSymbol gthreadpool_type;
287 public DataType gdestroynotify_type;
288 public DataType gquark_type;
289 public Struct gvalue_type;
290 public Class gvariant_type;
291 public Struct mutex_type;
292 public TypeSymbol type_module_type;
293 public TypeSymbol dbus_proxy_type;
295 public bool in_plugin = false;
296 public string module_init_param_name;
298 public bool gvaluecollector_h_needed;
299 public bool requires_array_free;
300 public bool requires_array_move;
301 public bool requires_array_length;
303 public Set<string> wrappers;
304 Set<Symbol> generated_external_symbols;
306 public Map<string,string> variable_name_map { get { return emit_context.variable_name_map; } }
308 public CCodeBaseModule () {
309 predefined_marshal_set = new HashSet<string> (str_hash, str_equal);
310 predefined_marshal_set.add ("VOID:VOID");
311 predefined_marshal_set.add ("VOID:BOOLEAN");
312 predefined_marshal_set.add ("VOID:CHAR");
313 predefined_marshal_set.add ("VOID:UCHAR");
314 predefined_marshal_set.add ("VOID:INT");
315 predefined_marshal_set.add ("VOID:UINT");
316 predefined_marshal_set.add ("VOID:LONG");
317 predefined_marshal_set.add ("VOID:ULONG");
318 predefined_marshal_set.add ("VOID:ENUM");
319 predefined_marshal_set.add ("VOID:FLAGS");
320 predefined_marshal_set.add ("VOID:FLOAT");
321 predefined_marshal_set.add ("VOID:DOUBLE");
322 predefined_marshal_set.add ("VOID:STRING");
323 predefined_marshal_set.add ("VOID:POINTER");
324 predefined_marshal_set.add ("VOID:OBJECT");
325 predefined_marshal_set.add ("STRING:OBJECT,POINTER");
326 predefined_marshal_set.add ("VOID:UINT,POINTER");
327 predefined_marshal_set.add ("BOOLEAN:FLAGS");
329 reserved_identifiers = new HashSet<string> (str_hash, str_equal);
331 // C99 keywords
332 reserved_identifiers.add ("_Bool");
333 reserved_identifiers.add ("_Complex");
334 reserved_identifiers.add ("_Imaginary");
335 reserved_identifiers.add ("asm");
336 reserved_identifiers.add ("auto");
337 reserved_identifiers.add ("break");
338 reserved_identifiers.add ("case");
339 reserved_identifiers.add ("char");
340 reserved_identifiers.add ("const");
341 reserved_identifiers.add ("continue");
342 reserved_identifiers.add ("default");
343 reserved_identifiers.add ("do");
344 reserved_identifiers.add ("double");
345 reserved_identifiers.add ("else");
346 reserved_identifiers.add ("enum");
347 reserved_identifiers.add ("extern");
348 reserved_identifiers.add ("float");
349 reserved_identifiers.add ("for");
350 reserved_identifiers.add ("goto");
351 reserved_identifiers.add ("if");
352 reserved_identifiers.add ("inline");
353 reserved_identifiers.add ("int");
354 reserved_identifiers.add ("long");
355 reserved_identifiers.add ("register");
356 reserved_identifiers.add ("restrict");
357 reserved_identifiers.add ("return");
358 reserved_identifiers.add ("short");
359 reserved_identifiers.add ("signed");
360 reserved_identifiers.add ("sizeof");
361 reserved_identifiers.add ("static");
362 reserved_identifiers.add ("struct");
363 reserved_identifiers.add ("switch");
364 reserved_identifiers.add ("typedef");
365 reserved_identifiers.add ("union");
366 reserved_identifiers.add ("unsigned");
367 reserved_identifiers.add ("void");
368 reserved_identifiers.add ("volatile");
369 reserved_identifiers.add ("while");
371 // MSVC keywords
372 reserved_identifiers.add ("cdecl");
374 // reserved for Vala/GObject naming conventions
375 reserved_identifiers.add ("error");
376 reserved_identifiers.add ("result");
377 reserved_identifiers.add ("self");
380 public override void emit (CodeContext context) {
381 this.context = context;
383 root_symbol = context.root;
385 bool_type = new BooleanType ((Struct) root_symbol.scope.lookup ("bool"));
386 char_type = new IntegerType ((Struct) root_symbol.scope.lookup ("char"));
387 uchar_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uchar"));
388 short_type = new IntegerType ((Struct) root_symbol.scope.lookup ("short"));
389 ushort_type = new IntegerType ((Struct) root_symbol.scope.lookup ("ushort"));
390 int_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int"));
391 uint_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint"));
392 long_type = new IntegerType ((Struct) root_symbol.scope.lookup ("long"));
393 ulong_type = new IntegerType ((Struct) root_symbol.scope.lookup ("ulong"));
394 int8_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int8"));
395 uint8_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint8"));
396 int16_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int16"));
397 uint16_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint16"));
398 int32_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int32"));
399 uint32_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint32"));
400 int64_type = new IntegerType ((Struct) root_symbol.scope.lookup ("int64"));
401 uint64_type = new IntegerType ((Struct) root_symbol.scope.lookup ("uint64"));
402 float_type = new FloatingType ((Struct) root_symbol.scope.lookup ("float"));
403 double_type = new FloatingType ((Struct) root_symbol.scope.lookup ("double"));
404 string_type = new ObjectType ((Class) root_symbol.scope.lookup ("string"));
405 var unichar_struct = (Struct) root_symbol.scope.lookup ("unichar");
406 if (unichar_struct != null) {
407 unichar_type = new IntegerType (unichar_struct);
410 if (context.profile == Profile.GOBJECT) {
411 var glib_ns = root_symbol.scope.lookup ("GLib");
413 gtype_type = (TypeSymbol) glib_ns.scope.lookup ("Type");
414 gobject_type = (TypeSymbol) glib_ns.scope.lookup ("Object");
415 gerror_type = new ErrorType (null, null);
416 glist_type = (Class) glib_ns.scope.lookup ("List");
417 gslist_type = (Class) glib_ns.scope.lookup ("SList");
418 gnode_type = (Class) glib_ns.scope.lookup ("Node");
419 gvaluearray_type = (Class) glib_ns.scope.lookup ("ValueArray");
420 gstringbuilder_type = (TypeSymbol) glib_ns.scope.lookup ("StringBuilder");
421 garray_type = (TypeSymbol) glib_ns.scope.lookup ("Array");
422 gbytearray_type = (TypeSymbol) glib_ns.scope.lookup ("ByteArray");
423 gptrarray_type = (TypeSymbol) glib_ns.scope.lookup ("PtrArray");
424 gthreadpool_type = (TypeSymbol) glib_ns.scope.lookup ("ThreadPool");
425 gdestroynotify_type = new DelegateType ((Delegate) glib_ns.scope.lookup ("DestroyNotify"));
427 gquark_type = new IntegerType ((Struct) glib_ns.scope.lookup ("Quark"));
428 gvalue_type = (Struct) glib_ns.scope.lookup ("Value");
429 gvariant_type = (Class) glib_ns.scope.lookup ("Variant");
430 mutex_type = (Struct) glib_ns.scope.lookup ("StaticRecMutex");
432 type_module_type = (TypeSymbol) glib_ns.scope.lookup ("TypeModule");
434 regex_type = new ObjectType ((Class) root_symbol.scope.lookup ("GLib").scope.lookup ("Regex"));
436 if (context.module_init_method != null) {
437 foreach (Parameter parameter in context.module_init_method.get_parameters ()) {
438 if (parameter.variable_type.data_type == type_module_type) {
439 in_plugin = true;
440 module_init_param_name = parameter.name;
441 break;
444 if (!in_plugin) {
445 Report.error (context.module_init_method.source_reference, "[ModuleInit] requires a parameter of type `GLib.TypeModule'");
449 dbus_proxy_type = (TypeSymbol) glib_ns.scope.lookup ("DBusProxy");
452 header_file = new CCodeFile ();
453 header_file.is_header = true;
454 internal_header_file = new CCodeFile ();
455 internal_header_file.is_header = true;
457 /* we're only interested in non-pkg source files */
458 var source_files = context.get_source_files ();
459 foreach (SourceFile file in source_files) {
460 if (file.file_type == SourceFileType.SOURCE ||
461 (context.header_filename != null && file.file_type == SourceFileType.FAST)) {
462 file.accept (this);
466 // generate symbols file for public API
467 if (context.symbols_filename != null) {
468 var stream = FileStream.open (context.symbols_filename, "w");
469 if (stream == null) {
470 Report.error (null, "unable to open `%s' for writing".printf (context.symbols_filename));
471 return;
474 foreach (string symbol in header_file.get_symbols ()) {
475 stream.puts (symbol);
476 stream.putc ('\n');
479 stream = null;
482 // generate C header file for public API
483 if (context.header_filename != null) {
484 bool ret;
485 if (context.profile == Profile.GOBJECT) {
486 ret = header_file.store (context.header_filename, null, context.version_header, false, "G_BEGIN_DECLS", "G_END_DECLS");
487 } else {
488 ret = header_file.store (context.header_filename, null, context.version_header, false);
490 if (!ret) {
491 Report.error (null, "unable to open `%s' for writing".printf (context.header_filename));
495 // generate C header file for internal API
496 if (context.internal_header_filename != null) {
497 bool ret;
498 if (context.profile == Profile.GOBJECT) {
499 ret = internal_header_file.store (context.internal_header_filename, null, context.version_header, false, "G_BEGIN_DECLS", "G_END_DECLS");
500 } else {
501 ret = internal_header_file.store (context.internal_header_filename, null, context.version_header, false);
503 if (!ret) {
504 Report.error (null, "unable to open `%s' for writing".printf (context.internal_header_filename));
509 public void push_context (EmitContext emit_context) {
510 if (this.emit_context != null) {
511 emit_context_stack.add (this.emit_context);
514 this.emit_context = emit_context;
517 public void pop_context () {
518 if (emit_context_stack.size > 0) {
519 this.emit_context = emit_context_stack[emit_context_stack.size - 1];
520 emit_context_stack.remove_at (emit_context_stack.size - 1);
521 } else {
522 this.emit_context = null;
526 public void push_function (CCodeFunction func) {
527 emit_context.ccode_stack.add (ccode);
528 emit_context.ccode = func;
531 public void pop_function () {
532 emit_context.ccode = emit_context.ccode_stack[emit_context.ccode_stack.size - 1];
533 emit_context.ccode_stack.remove_at (emit_context.ccode_stack.size - 1);
536 public bool add_symbol_declaration (CCodeFile decl_space, Symbol sym, string name) {
537 if (decl_space.add_declaration (name)) {
538 return true;
540 if (sym.source_reference != null) {
541 sym.source_reference.file.used = true;
543 if (sym.external_package || (!decl_space.is_header && CodeContext.get ().use_header && !sym.is_internal_symbol ())) {
544 // add appropriate include file
545 foreach (string header_filename in sym.get_cheader_filenames ()) {
546 decl_space.add_include (header_filename, !sym.external_package);
548 // declaration complete
549 return true;
550 } else {
551 // require declaration
552 return false;
556 public CCodeIdentifier get_value_setter_function (DataType type_reference) {
557 var array_type = type_reference as ArrayType;
558 if (type_reference.data_type != null) {
559 return new CCodeIdentifier (type_reference.data_type.get_set_value_function ());
560 } else if (array_type != null && array_type.element_type.data_type == string_type.data_type) {
561 // G_TYPE_STRV
562 return new CCodeIdentifier ("g_value_set_boxed");
563 } else {
564 return new CCodeIdentifier ("g_value_set_pointer");
568 public CCodeIdentifier get_value_taker_function (DataType type_reference) {
569 var array_type = type_reference as ArrayType;
570 if (type_reference.data_type != null) {
571 return new CCodeIdentifier (type_reference.data_type.get_take_value_function ());
572 } else if (array_type != null && array_type.element_type.data_type == string_type.data_type) {
573 // G_TYPE_STRV
574 return new CCodeIdentifier ("g_value_take_boxed");
575 } else {
576 return new CCodeIdentifier ("g_value_set_pointer");
580 CCodeIdentifier get_value_getter_function (DataType type_reference) {
581 var array_type = type_reference as ArrayType;
582 if (type_reference.data_type != null) {
583 return new CCodeIdentifier (type_reference.data_type.get_get_value_function ());
584 } else if (array_type != null && array_type.element_type.data_type == string_type.data_type) {
585 // G_TYPE_STRV
586 return new CCodeIdentifier ("g_value_get_boxed");
587 } else {
588 return new CCodeIdentifier ("g_value_get_pointer");
592 public virtual void append_vala_array_free () {
595 public virtual void append_vala_array_move () {
598 public virtual void append_vala_array_length () {
601 public override void visit_source_file (SourceFile source_file) {
602 cfile = new CCodeFile ();
604 user_marshal_set = new HashSet<string> (str_hash, str_equal);
606 next_regex_id = 0;
608 gvaluecollector_h_needed = false;
609 requires_array_free = false;
610 requires_array_move = false;
611 requires_array_length = false;
613 wrappers = new HashSet<string> (str_hash, str_equal);
614 generated_external_symbols = new HashSet<Symbol> ();
616 if (context.profile == Profile.GOBJECT) {
617 header_file.add_include ("glib.h");
618 internal_header_file.add_include ("glib.h");
619 cfile.add_include ("glib.h");
620 cfile.add_include ("glib-object.h");
623 source_file.accept_children (this);
625 if (context.report.get_errors () > 0) {
626 return;
629 /* For fast-vapi, we only wanted the header declarations
630 * to be emitted, so bail out here without writing the
631 * C code output.
633 if (source_file.file_type == SourceFileType.FAST) {
634 return;
637 if (requires_array_free) {
638 append_vala_array_free ();
640 if (requires_array_move) {
641 append_vala_array_move ();
643 if (requires_array_length) {
644 append_vala_array_length ();
647 if (gvaluecollector_h_needed) {
648 cfile.add_include ("gobject/gvaluecollector.h");
651 var comments = source_file.get_comments();
652 if (comments != null) {
653 foreach (Comment comment in comments) {
654 var ccomment = new CCodeComment (comment.content);
655 cfile.add_comment (ccomment);
659 if (!cfile.store (source_file.get_csource_filename (), source_file.filename, context.version_header, context.debug)) {
660 Report.error (null, "unable to open `%s' for writing".printf (source_file.get_csource_filename ()));
663 cfile = null;
666 public virtual bool generate_enum_declaration (Enum en, CCodeFile decl_space) {
667 if (add_symbol_declaration (decl_space, en, en.get_cname ())) {
668 return false;
671 var cenum = new CCodeEnum (en.get_cname ());
673 cenum.deprecated = en.deprecated;
675 int flag_shift = 0;
676 foreach (EnumValue ev in en.get_values ()) {
677 CCodeEnumValue c_ev;
678 if (ev.value == null) {
679 c_ev = new CCodeEnumValue (ev.get_cname ());
680 if (en.is_flags) {
681 c_ev.value = new CCodeConstant ("1 << %d".printf (flag_shift));
682 flag_shift += 1;
684 } else {
685 ev.value.emit (this);
686 c_ev = new CCodeEnumValue (ev.get_cname (), get_cvalue (ev.value));
688 c_ev.deprecated = ev.deprecated;
689 cenum.add_value (c_ev);
692 decl_space.add_type_definition (cenum);
693 decl_space.add_type_definition (new CCodeNewline ());
695 if (!en.has_type_id) {
696 return true;
699 decl_space.add_type_declaration (new CCodeNewline ());
701 var macro = "(%s_get_type ())".printf (en.get_lower_case_cname (null));
702 decl_space.add_type_declaration (new CCodeMacroReplacement (en.get_type_id (), macro));
704 var fun_name = "%s_get_type".printf (en.get_lower_case_cname (null));
705 var regfun = new CCodeFunction (fun_name, "GType");
706 regfun.attributes = "G_GNUC_CONST";
708 if (en.access == SymbolAccessibility.PRIVATE) {
709 regfun.modifiers = CCodeModifiers.STATIC;
710 // avoid C warning as this function is not always used
711 regfun.attributes = "G_GNUC_UNUSED";
714 decl_space.add_function_declaration (regfun);
716 return true;
719 public override void visit_enum (Enum en) {
720 en.accept_children (this);
722 if (en.comment != null) {
723 cfile.add_type_member_definition (new CCodeComment (en.comment.content));
726 generate_enum_declaration (en, cfile);
728 if (!en.is_internal_symbol ()) {
729 generate_enum_declaration (en, header_file);
731 if (!en.is_private_symbol ()) {
732 generate_enum_declaration (en, internal_header_file);
736 public void visit_member (Symbol m) {
737 /* stuff meant for all lockable members */
738 if (m is Lockable && ((Lockable) m).get_lock_used ()) {
739 CCodeExpression l = new CCodeIdentifier ("self");
740 var init_context = class_init_context;
741 var finalize_context = class_finalize_context;
743 if (m.is_instance_member ()) {
744 l = new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (l, "priv"), get_symbol_lock_name (m.name));
745 init_context = instance_init_context;
746 finalize_context = instance_finalize_context;
747 } else if (m.is_class_member ()) {
748 TypeSymbol parent = (TypeSymbol)m.parent_symbol;
750 var get_class_private_call = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS_PRIVATE".printf(parent.get_upper_case_cname ())));
751 get_class_private_call.add_argument (new CCodeIdentifier ("klass"));
752 l = new CCodeMemberAccess.pointer (get_class_private_call, get_symbol_lock_name (m.name));
753 } else {
754 l = new CCodeIdentifier (get_symbol_lock_name ("%s_%s".printf(m.parent_symbol.get_lower_case_cname (), m.name)));
757 push_context (init_context);
758 var initf = new CCodeFunctionCall (new CCodeIdentifier (mutex_type.default_construction_method.get_cname ()));
759 initf.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));
760 ccode.add_expression (initf);
761 pop_context ();
763 if (finalize_context != null) {
764 push_context (finalize_context);
765 var fc = new CCodeFunctionCall (new CCodeIdentifier ("g_static_rec_mutex_free"));
766 fc.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));
767 ccode.add_expression (fc);
768 pop_context ();
773 public void generate_constant_declaration (Constant c, CCodeFile decl_space, bool definition = false) {
774 if (c.parent_symbol is Block) {
775 // local constant
776 return;
779 if (add_symbol_declaration (decl_space, c, c.get_cname ())) {
780 return;
783 if (!c.external) {
784 generate_type_declaration (c.type_reference, decl_space);
786 c.value.emit (this);
788 var initializer_list = c.value as InitializerList;
789 if (initializer_list != null) {
790 var cdecl = new CCodeDeclaration (c.type_reference.get_const_cname ());
791 var arr = "";
792 if (c.type_reference is ArrayType) {
793 arr = "[%d]".printf (initializer_list.size);
796 var cinitializer = get_cvalue (c.value);
797 if (!definition) {
798 // never output value in header
799 // special case needed as this method combines declaration and definition
800 cinitializer = null;
803 cdecl.add_declarator (new CCodeVariableDeclarator ("%s%s".printf (c.get_cname (), arr), cinitializer));
804 if (c.is_private_symbol ()) {
805 cdecl.modifiers = CCodeModifiers.STATIC;
806 } else {
807 cdecl.modifiers = CCodeModifiers.EXTERN;
810 decl_space.add_constant_declaration (cdecl);
811 } else {
812 var cdefine = new CCodeMacroReplacement.with_expression (c.get_cname (), get_cvalue (c.value));
813 decl_space.add_type_member_declaration (cdefine);
818 public override void visit_constant (Constant c) {
819 if (c.parent_symbol is Block) {
820 // local constant
822 generate_type_declaration (c.type_reference, cfile);
824 c.value.emit (this);
826 string type_name = c.type_reference.get_const_cname ();
827 string arr = "";
828 if (c.type_reference is ArrayType) {
829 arr = "[]";
832 if (c.type_reference.compatible (string_type)) {
833 type_name = "const char";
834 arr = "[]";
837 var cinitializer = get_cvalue (c.value);
839 ccode.add_declaration (type_name, new CCodeVariableDeclarator ("%s%s".printf (c.get_cname (), arr), cinitializer), CCodeModifiers.STATIC);
841 return;
844 generate_constant_declaration (c, cfile, true);
846 if (!c.is_internal_symbol ()) {
847 generate_constant_declaration (c, header_file);
849 if (!c.is_private_symbol ()) {
850 generate_constant_declaration (c, internal_header_file);
854 public void generate_field_declaration (Field f, CCodeFile decl_space) {
855 if (add_symbol_declaration (decl_space, f, f.get_cname ())) {
856 return;
859 generate_type_declaration (f.variable_type, decl_space);
861 string field_ctype = f.variable_type.get_cname ();
862 if (f.is_volatile) {
863 field_ctype = "volatile " + field_ctype;
866 var cdecl = new CCodeDeclaration (field_ctype);
867 cdecl.add_declarator (new CCodeVariableDeclarator (f.get_cname (), null, f.variable_type.get_cdeclarator_suffix ()));
868 if (f.is_private_symbol ()) {
869 cdecl.modifiers = CCodeModifiers.STATIC;
870 } else {
871 cdecl.modifiers = CCodeModifiers.EXTERN;
873 if (f.deprecated) {
874 cdecl.modifiers |= CCodeModifiers.DEPRECATED;
876 decl_space.add_type_member_declaration (cdecl);
878 if (f.get_lock_used ()) {
879 // Declare mutex for static member
880 var flock = new CCodeDeclaration (mutex_type.get_cname ());
881 var flock_decl = new CCodeVariableDeclarator (get_symbol_lock_name (f.get_cname ()), new CCodeConstant ("{0}"));
882 flock.add_declarator (flock_decl);
884 if (f.is_private_symbol ()) {
885 flock.modifiers = CCodeModifiers.STATIC;
886 } else {
887 flock.modifiers = CCodeModifiers.EXTERN;
889 decl_space.add_type_member_declaration (flock);
892 if (f.variable_type is ArrayType && !f.no_array_length) {
893 var array_type = (ArrayType) f.variable_type;
895 if (!array_type.fixed_length) {
896 for (int dim = 1; dim <= array_type.rank; dim++) {
897 var len_type = int_type.copy ();
899 cdecl = new CCodeDeclaration (len_type.get_cname ());
900 cdecl.add_declarator (new CCodeVariableDeclarator (get_array_length_cname (f.get_cname (), dim)));
901 if (f.is_private_symbol ()) {
902 cdecl.modifiers = CCodeModifiers.STATIC;
903 } else {
904 cdecl.modifiers = CCodeModifiers.EXTERN;
906 decl_space.add_type_member_declaration (cdecl);
909 } else if (f.variable_type is DelegateType) {
910 var delegate_type = (DelegateType) f.variable_type;
911 if (delegate_type.delegate_symbol.has_target) {
912 // create field to store delegate target
914 cdecl = new CCodeDeclaration ("gpointer");
915 cdecl.add_declarator (new CCodeVariableDeclarator (get_delegate_target_cname (f.get_cname ())));
916 if (f.is_private_symbol ()) {
917 cdecl.modifiers = CCodeModifiers.STATIC;
918 } else {
919 cdecl.modifiers = CCodeModifiers.EXTERN;
921 decl_space.add_type_member_declaration (cdecl);
923 if (delegate_type.value_owned) {
924 cdecl = new CCodeDeclaration ("GDestroyNotify");
925 cdecl.add_declarator (new CCodeVariableDeclarator (get_delegate_target_destroy_notify_cname (f.get_cname ())));
926 if (f.is_private_symbol ()) {
927 cdecl.modifiers = CCodeModifiers.STATIC;
928 } else {
929 cdecl.modifiers = CCodeModifiers.EXTERN;
931 decl_space.add_type_member_declaration (cdecl);
937 public override void visit_field (Field f) {
938 visit_member (f);
940 check_type (f.variable_type);
942 var cl = f.parent_symbol as Class;
943 bool is_gtypeinstance = (cl != null && !cl.is_compact);
945 CCodeExpression lhs = null;
947 string field_ctype = f.variable_type.get_cname ();
948 if (f.is_volatile) {
949 field_ctype = "volatile " + field_ctype;
952 if (f.binding == MemberBinding.INSTANCE) {
953 if (is_gtypeinstance && f.access == SymbolAccessibility.PRIVATE) {
954 lhs = new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), "priv"), f.get_cname ());
955 } else {
956 lhs = new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), f.get_cname ());
959 if (f.initializer != null) {
960 push_context (instance_init_context);
962 f.initializer.emit (this);
964 var rhs = get_cvalue (f.initializer);
966 ccode.add_assignment (lhs, rhs);
968 if (f.variable_type is ArrayType && !f.no_array_length &&
969 f.initializer is ArrayCreationExpression) {
970 var array_type = (ArrayType) f.variable_type;
971 var field_value = get_field_cvalue (f, load_this_parameter ((TypeSymbol) f.parent_symbol));
973 List<Expression> sizes = ((ArrayCreationExpression) f.initializer).get_sizes ();
974 for (int dim = 1; dim <= array_type.rank; dim++) {
975 var array_len_lhs = get_array_length_cvalue (field_value, dim);
976 var size = sizes[dim - 1];
977 ccode.add_assignment (array_len_lhs, get_cvalue (size));
980 if (array_type.rank == 1 && f.is_internal_symbol ()) {
981 var lhs_array_size = get_array_size_cvalue (field_value);
982 var rhs_array_len = get_array_length_cvalue (field_value, 1);
983 ccode.add_assignment (lhs_array_size, rhs_array_len);
987 foreach (LocalVariable local in temp_ref_vars) {
988 ccode.add_expression (destroy_local (local));
991 temp_ref_vars.clear ();
993 pop_context ();
996 if (requires_destroy (f.variable_type) && instance_finalize_context != null) {
997 push_context (instance_finalize_context);
998 ccode.add_expression (destroy_field (f, load_this_parameter ((TypeSymbol) f.parent_symbol)));
999 pop_context ();
1001 } else if (f.binding == MemberBinding.CLASS) {
1002 if (!is_gtypeinstance) {
1003 Report.error (f.source_reference, "class fields are not supported in compact classes");
1004 f.error = true;
1005 return;
1008 if (f.access == SymbolAccessibility.PRIVATE) {
1009 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS_PRIVATE".printf (cl.get_upper_case_cname ())));
1010 ccall.add_argument (new CCodeIdentifier ("klass"));
1011 lhs = new CCodeMemberAccess (ccall, f.get_cname (), true);
1012 } else {
1013 lhs = new CCodeMemberAccess (new CCodeIdentifier ("klass"), f.get_cname (), true);
1016 if (f.initializer != null) {
1017 push_context (class_init_context);
1019 f.initializer.emit (this);
1021 var rhs = get_cvalue (f.initializer);
1023 ccode.add_assignment (lhs, rhs);
1025 foreach (LocalVariable local in temp_ref_vars) {
1026 ccode.add_expression (destroy_local (local));
1029 temp_ref_vars.clear ();
1031 pop_context ();
1033 } else {
1034 generate_field_declaration (f, cfile);
1036 if (!f.is_internal_symbol ()) {
1037 generate_field_declaration (f, header_file);
1039 if (!f.is_private_symbol ()) {
1040 generate_field_declaration (f, internal_header_file);
1043 lhs = new CCodeIdentifier (f.get_cname ());
1045 var var_decl = new CCodeVariableDeclarator (f.get_cname (), null, f.variable_type.get_cdeclarator_suffix ());
1046 var_decl.initializer = default_value_for_type (f.variable_type, true);
1048 if (class_init_context != null) {
1049 push_context (class_init_context);
1050 } else {
1051 push_context (new EmitContext ());
1054 if (f.initializer != null) {
1055 f.initializer.emit (this);
1057 var init = get_cvalue (f.initializer);
1058 if (is_constant_ccode_expression (init)) {
1059 var_decl.initializer = init;
1063 var var_def = new CCodeDeclaration (field_ctype);
1064 var_def.add_declarator (var_decl);
1065 if (!f.is_private_symbol ()) {
1066 var_def.modifiers = CCodeModifiers.EXTERN;
1067 } else {
1068 var_def.modifiers = CCodeModifiers.STATIC;
1070 cfile.add_type_member_declaration (var_def);
1072 /* add array length fields where necessary */
1073 if (f.variable_type is ArrayType && !f.no_array_length) {
1074 var array_type = (ArrayType) f.variable_type;
1076 if (!array_type.fixed_length) {
1077 for (int dim = 1; dim <= array_type.rank; dim++) {
1078 var len_type = int_type.copy ();
1080 var len_def = new CCodeDeclaration (len_type.get_cname ());
1081 len_def.add_declarator (new CCodeVariableDeclarator (get_array_length_cname (f.get_cname (), dim), new CCodeConstant ("0")));
1082 if (!f.is_private_symbol ()) {
1083 len_def.modifiers = CCodeModifiers.EXTERN;
1084 } else {
1085 len_def.modifiers = CCodeModifiers.STATIC;
1087 cfile.add_type_member_declaration (len_def);
1090 if (array_type.rank == 1 && f.is_internal_symbol ()) {
1091 var len_type = int_type.copy ();
1093 var cdecl = new CCodeDeclaration (len_type.get_cname ());
1094 cdecl.add_declarator (new CCodeVariableDeclarator (get_array_size_cname (f.get_cname ()), new CCodeConstant ("0")));
1095 cdecl.modifiers = CCodeModifiers.STATIC;
1096 cfile.add_type_member_declaration (cdecl);
1099 } else if (f.variable_type is DelegateType) {
1100 var delegate_type = (DelegateType) f.variable_type;
1101 if (delegate_type.delegate_symbol.has_target) {
1102 // create field to store delegate target
1104 var target_def = new CCodeDeclaration ("gpointer");
1105 target_def.add_declarator (new CCodeVariableDeclarator (get_delegate_target_cname (f.get_cname ()), new CCodeConstant ("NULL")));
1106 if (!f.is_private_symbol ()) {
1107 target_def.modifiers = CCodeModifiers.EXTERN;
1108 } else {
1109 target_def.modifiers = CCodeModifiers.STATIC;
1111 cfile.add_type_member_declaration (target_def);
1113 if (delegate_type.value_owned) {
1114 var target_destroy_notify_def = new CCodeDeclaration ("GDestroyNotify");
1115 target_destroy_notify_def.add_declarator (new CCodeVariableDeclarator (get_delegate_target_destroy_notify_cname (f.get_cname ()), new CCodeConstant ("NULL")));
1116 if (!f.is_private_symbol ()) {
1117 target_destroy_notify_def.modifiers = CCodeModifiers.EXTERN;
1118 } else {
1119 target_destroy_notify_def.modifiers = CCodeModifiers.STATIC;
1121 cfile.add_type_member_declaration (target_destroy_notify_def);
1127 if (f.initializer != null) {
1128 var rhs = get_cvalue (f.initializer);
1129 if (!is_constant_ccode_expression (rhs)) {
1130 if (f.parent_symbol is Class) {
1131 if (f.initializer is InitializerList) {
1132 ccode.open_block ();
1134 var temp_decl = get_temp_variable (f.variable_type);
1135 var vardecl = new CCodeVariableDeclarator.zero (temp_decl.name, rhs);
1136 ccode.add_declaration (temp_decl.variable_type.get_cname (), vardecl);
1138 var tmp = get_variable_cexpression (get_variable_cname (temp_decl.name));
1139 ccode.add_assignment (lhs, tmp);
1141 ccode.close ();
1142 } else {
1143 ccode.add_assignment (lhs, rhs);
1146 if (f.variable_type is ArrayType && !f.no_array_length &&
1147 f.initializer is ArrayCreationExpression) {
1148 var array_type = (ArrayType) f.variable_type;
1149 var field_value = get_field_cvalue (f, null);
1151 List<Expression> sizes = ((ArrayCreationExpression) f.initializer).get_sizes ();
1152 for (int dim = 1; dim <= array_type.rank; dim++) {
1153 var array_len_lhs = get_array_length_cvalue (field_value, dim);
1154 var size = sizes[dim - 1];
1155 ccode.add_assignment (array_len_lhs, get_cvalue (size));
1158 } else {
1159 f.error = true;
1160 Report.error (f.source_reference, "Non-constant field initializers not supported in this context");
1161 return;
1166 pop_context ();
1170 public bool is_constant_ccode_expression (CCodeExpression cexpr) {
1171 if (cexpr is CCodeConstant) {
1172 return true;
1173 } else if (cexpr is CCodeCastExpression) {
1174 var ccast = (CCodeCastExpression) cexpr;
1175 return is_constant_ccode_expression (ccast.inner);
1176 } else if (cexpr is CCodeBinaryExpression) {
1177 var cbinary = (CCodeBinaryExpression) cexpr;
1178 return is_constant_ccode_expression (cbinary.left) && is_constant_ccode_expression (cbinary.right);
1181 var cparenthesized = (cexpr as CCodeParenthesizedExpression);
1182 return (null != cparenthesized && is_constant_ccode_expression (cparenthesized.inner));
1186 * Returns whether the passed cexpr is a pure expression, i.e. an
1187 * expression without side-effects.
1189 public bool is_pure_ccode_expression (CCodeExpression cexpr) {
1190 if (cexpr is CCodeConstant || cexpr is CCodeIdentifier) {
1191 return true;
1192 } else if (cexpr is CCodeBinaryExpression) {
1193 var cbinary = (CCodeBinaryExpression) cexpr;
1194 return is_pure_ccode_expression (cbinary.left) && is_constant_ccode_expression (cbinary.right);
1195 } else if (cexpr is CCodeUnaryExpression) {
1196 var cunary = (CCodeUnaryExpression) cexpr;
1197 switch (cunary.operator) {
1198 case CCodeUnaryOperator.PREFIX_INCREMENT:
1199 case CCodeUnaryOperator.PREFIX_DECREMENT:
1200 case CCodeUnaryOperator.POSTFIX_INCREMENT:
1201 case CCodeUnaryOperator.POSTFIX_DECREMENT:
1202 return false;
1203 default:
1204 return is_pure_ccode_expression (cunary.inner);
1206 } else if (cexpr is CCodeMemberAccess) {
1207 var cma = (CCodeMemberAccess) cexpr;
1208 return is_pure_ccode_expression (cma.inner);
1209 } else if (cexpr is CCodeElementAccess) {
1210 var cea = (CCodeElementAccess) cexpr;
1211 return is_pure_ccode_expression (cea.container) && is_pure_ccode_expression (cea.index);
1212 } else if (cexpr is CCodeCastExpression) {
1213 var ccast = (CCodeCastExpression) cexpr;
1214 return is_pure_ccode_expression (ccast.inner);
1215 } else if (cexpr is CCodeParenthesizedExpression) {
1216 var cparenthesized = (CCodeParenthesizedExpression) cexpr;
1217 return is_pure_ccode_expression (cparenthesized.inner);
1220 return false;
1223 public override void visit_formal_parameter (Parameter p) {
1224 if (!p.ellipsis) {
1225 check_type (p.variable_type);
1229 public override void visit_property (Property prop) {
1230 visit_member (prop);
1232 check_type (prop.property_type);
1234 if (prop.get_accessor != null) {
1235 prop.get_accessor.accept (this);
1237 if (prop.set_accessor != null) {
1238 prop.set_accessor.accept (this);
1242 public void generate_type_declaration (DataType type, CCodeFile decl_space) {
1243 if (type is ObjectType) {
1244 var object_type = (ObjectType) type;
1245 if (object_type.type_symbol is Class) {
1246 generate_class_declaration ((Class) object_type.type_symbol, decl_space);
1247 } else if (object_type.type_symbol is Interface) {
1248 generate_interface_declaration ((Interface) object_type.type_symbol, decl_space);
1250 } else if (type is DelegateType) {
1251 var deleg_type = (DelegateType) type;
1252 var d = deleg_type.delegate_symbol;
1253 generate_delegate_declaration (d, decl_space);
1254 } else if (type.data_type is Enum) {
1255 var en = (Enum) type.data_type;
1256 generate_enum_declaration (en, decl_space);
1257 } else if (type is ValueType) {
1258 var value_type = (ValueType) type;
1259 generate_struct_declaration ((Struct) value_type.type_symbol, decl_space);
1260 } else if (type is ArrayType) {
1261 var array_type = (ArrayType) type;
1262 generate_type_declaration (array_type.element_type, decl_space);
1263 } else if (type is ErrorType) {
1264 var error_type = (ErrorType) type;
1265 if (error_type.error_domain != null) {
1266 generate_error_domain_declaration (error_type.error_domain, decl_space);
1268 } else if (type is PointerType) {
1269 var pointer_type = (PointerType) type;
1270 generate_type_declaration (pointer_type.base_type, decl_space);
1273 foreach (DataType type_arg in type.get_type_arguments ()) {
1274 generate_type_declaration (type_arg, decl_space);
1278 public virtual void generate_class_struct_declaration (Class cl, CCodeFile decl_space) {
1281 public virtual void generate_struct_declaration (Struct st, CCodeFile decl_space) {
1284 public virtual void generate_delegate_declaration (Delegate d, CCodeFile decl_space) {
1287 public virtual void generate_cparameters (Method m, CCodeFile decl_space, Map<int,CCodeParameter> cparam_map, CCodeFunction func, CCodeFunctionDeclarator? vdeclarator = null, Map<int,CCodeExpression>? carg_map = null, CCodeFunctionCall? vcall = null, int direction = 3) {
1290 public void generate_property_accessor_declaration (PropertyAccessor acc, CCodeFile decl_space) {
1291 if (add_symbol_declaration (decl_space, acc, acc.get_cname ())) {
1292 return;
1295 var prop = (Property) acc.prop;
1297 bool returns_real_struct = acc.readable && prop.property_type.is_real_non_null_struct_type ();
1300 CCodeParameter cvalueparam;
1301 if (returns_real_struct) {
1302 cvalueparam = new CCodeParameter ("result", acc.value_type.get_cname () + "*");
1303 } else if (!acc.readable && prop.property_type.is_real_non_null_struct_type ()) {
1304 cvalueparam = new CCodeParameter ("value", acc.value_type.get_cname () + "*");
1305 } else {
1306 cvalueparam = new CCodeParameter ("value", acc.value_type.get_cname ());
1308 generate_type_declaration (acc.value_type, decl_space);
1310 CCodeFunction function;
1311 if (acc.readable && !returns_real_struct) {
1312 function = new CCodeFunction (acc.get_cname (), acc.value_type.get_cname ());
1313 } else {
1314 function = new CCodeFunction (acc.get_cname (), "void");
1317 if (prop.binding == MemberBinding.INSTANCE) {
1318 var t = (TypeSymbol) prop.parent_symbol;
1319 var this_type = get_data_type_for_symbol (t);
1320 generate_type_declaration (this_type, decl_space);
1321 var cselfparam = new CCodeParameter ("self", this_type.get_cname ());
1322 if (t is Struct) {
1323 cselfparam.type_name += "*";
1326 function.add_parameter (cselfparam);
1329 if (acc.writable || acc.construction || returns_real_struct) {
1330 function.add_parameter (cvalueparam);
1333 if (acc.value_type is ArrayType) {
1334 var array_type = (ArrayType) acc.value_type;
1336 var length_ctype = "int";
1337 if (acc.readable) {
1338 length_ctype = "int*";
1341 for (int dim = 1; dim <= array_type.rank; dim++) {
1342 function.add_parameter (new CCodeParameter (get_array_length_cname (acc.readable ? "result" : "value", dim), length_ctype));
1344 } else if ((acc.value_type is DelegateType) && ((DelegateType) acc.value_type).delegate_symbol.has_target) {
1345 function.add_parameter (new CCodeParameter (get_delegate_target_cname (acc.readable ? "result" : "value"), acc.readable ? "gpointer*" : "gpointer"));
1348 if (prop.is_private_symbol () || (!acc.readable && !acc.writable) || acc.access == SymbolAccessibility.PRIVATE) {
1349 function.modifiers |= CCodeModifiers.STATIC;
1351 decl_space.add_function_declaration (function);
1354 public override void visit_property_accessor (PropertyAccessor acc) {
1355 push_context (new EmitContext (acc));
1357 var prop = (Property) acc.prop;
1359 if (acc.comment != null) {
1360 cfile.add_type_member_definition (new CCodeComment (acc.comment.content));
1363 bool returns_real_struct = acc.readable && prop.property_type.is_real_non_null_struct_type ();
1365 if (acc.result_var != null) {
1366 acc.result_var.accept (this);
1369 var t = (TypeSymbol) prop.parent_symbol;
1371 if (acc.construction && !t.is_subtype_of (gobject_type)) {
1372 Report.error (acc.source_reference, "construct properties require GLib.Object");
1373 acc.error = true;
1374 return;
1375 } else if (acc.construction && !is_gobject_property (prop)) {
1376 Report.error (acc.source_reference, "construct properties not supported for specified property type");
1377 acc.error = true;
1378 return;
1381 // do not declare overriding properties and interface implementations
1382 if (prop.is_abstract || prop.is_virtual
1383 || (prop.base_property == null && prop.base_interface_property == null)) {
1384 generate_property_accessor_declaration (acc, cfile);
1386 // do not declare construct-only properties in header files
1387 if (acc.readable || acc.writable) {
1388 if (!prop.is_internal_symbol ()
1389 && (acc.access == SymbolAccessibility.PUBLIC
1390 || acc.access == SymbolAccessibility.PROTECTED)) {
1391 generate_property_accessor_declaration (acc, header_file);
1393 if (!prop.is_private_symbol () && acc.access != SymbolAccessibility.PRIVATE) {
1394 generate_property_accessor_declaration (acc, internal_header_file);
1399 if (acc.source_type == SourceFileType.FAST) {
1400 return;
1403 var this_type = get_data_type_for_symbol (t);
1404 var cselfparam = new CCodeParameter ("self", this_type.get_cname ());
1405 if (t is Struct) {
1406 cselfparam.type_name += "*";
1408 CCodeParameter cvalueparam;
1409 if (returns_real_struct) {
1410 cvalueparam = new CCodeParameter ("result", acc.value_type.get_cname () + "*");
1411 } else if (!acc.readable && prop.property_type.is_real_non_null_struct_type ()) {
1412 cvalueparam = new CCodeParameter ("value", acc.value_type.get_cname () + "*");
1413 } else {
1414 cvalueparam = new CCodeParameter ("value", acc.value_type.get_cname ());
1417 if (prop.is_abstract || prop.is_virtual) {
1418 CCodeFunction function;
1419 if (acc.readable && !returns_real_struct) {
1420 function = new CCodeFunction (acc.get_cname (), current_return_type.get_cname ());
1421 } else {
1422 function = new CCodeFunction (acc.get_cname (), "void");
1424 function.add_parameter (cselfparam);
1425 if (acc.writable || acc.construction || returns_real_struct) {
1426 function.add_parameter (cvalueparam);
1429 if (acc.value_type is ArrayType) {
1430 var array_type = (ArrayType) acc.value_type;
1432 var length_ctype = "int";
1433 if (acc.readable) {
1434 length_ctype = "int*";
1437 for (int dim = 1; dim <= array_type.rank; dim++) {
1438 function.add_parameter (new CCodeParameter (get_array_length_cname (acc.readable ? "result" : "value", dim), length_ctype));
1440 } else if ((acc.value_type is DelegateType) && ((DelegateType) acc.value_type).delegate_symbol.has_target) {
1441 function.add_parameter (new CCodeParameter (get_delegate_target_cname (acc.readable ? "result" : "value"), acc.readable ? "gpointer*" : "gpointer"));
1444 if (prop.is_private_symbol () || !(acc.readable || acc.writable) || acc.access == SymbolAccessibility.PRIVATE) {
1445 // accessor function should be private if the property is an internal symbol or it's a construct-only setter
1446 function.modifiers |= CCodeModifiers.STATIC;
1449 push_function (function);
1451 CCodeFunctionCall vcast = null;
1452 if (prop.parent_symbol is Interface) {
1453 var iface = (Interface) prop.parent_symbol;
1455 vcast = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_INTERFACE".printf (iface.get_upper_case_cname (null))));
1456 } else {
1457 var cl = (Class) prop.parent_symbol;
1459 vcast = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS".printf (cl.get_upper_case_cname (null))));
1461 vcast.add_argument (new CCodeIdentifier ("self"));
1463 if (acc.readable) {
1464 var vcall = new CCodeFunctionCall (new CCodeMemberAccess.pointer (vcast, "get_%s".printf (prop.name)));
1465 vcall.add_argument (new CCodeIdentifier ("self"));
1466 if (returns_real_struct) {
1467 vcall.add_argument (new CCodeIdentifier ("result"));
1468 ccode.add_expression (vcall);
1469 } else {
1470 if (acc.value_type is ArrayType) {
1471 var array_type = (ArrayType) acc.value_type;
1473 for (int dim = 1; dim <= array_type.rank; dim++) {
1474 var len_expr = new CCodeIdentifier (get_array_length_cname ("result", dim));
1475 vcall.add_argument (len_expr);
1477 } else if ((acc.value_type is DelegateType) && ((DelegateType) acc.value_type).delegate_symbol.has_target) {
1478 vcall.add_argument (new CCodeIdentifier (get_delegate_target_cname ("result")));
1481 ccode.add_return (vcall);
1483 } else {
1484 var vcall = new CCodeFunctionCall (new CCodeMemberAccess.pointer (vcast, "set_%s".printf (prop.name)));
1485 vcall.add_argument (new CCodeIdentifier ("self"));
1486 vcall.add_argument (new CCodeIdentifier ("value"));
1488 if (acc.value_type is ArrayType) {
1489 var array_type = (ArrayType) acc.value_type;
1491 for (int dim = 1; dim <= array_type.rank; dim++) {
1492 var len_expr = new CCodeIdentifier (get_array_length_cname ("value", dim));
1493 vcall.add_argument (len_expr);
1495 } else if ((acc.value_type is DelegateType) && ((DelegateType) acc.value_type).delegate_symbol.has_target) {
1496 vcall.add_argument (new CCodeIdentifier (get_delegate_target_cname ("value")));
1499 ccode.add_expression (vcall);
1502 pop_function ();
1504 cfile.add_function (function);
1507 if (!prop.is_abstract) {
1508 bool is_virtual = prop.base_property != null || prop.base_interface_property != null;
1510 string cname;
1511 if (is_virtual) {
1512 if (acc.readable) {
1513 cname = "%s_real_get_%s".printf (t.get_lower_case_cname (null), prop.name);
1514 } else {
1515 cname = "%s_real_set_%s".printf (t.get_lower_case_cname (null), prop.name);
1517 } else {
1518 cname = acc.get_cname ();
1521 CCodeFunction function;
1522 if (acc.writable || acc.construction || returns_real_struct) {
1523 function = new CCodeFunction (cname, "void");
1524 } else {
1525 function = new CCodeFunction (cname, acc.value_type.get_cname ());
1528 ObjectType base_type = null;
1529 if (prop.binding == MemberBinding.INSTANCE) {
1530 if (is_virtual) {
1531 if (prop.base_property != null) {
1532 base_type = new ObjectType ((ObjectTypeSymbol) prop.base_property.parent_symbol);
1533 } else if (prop.base_interface_property != null) {
1534 base_type = new ObjectType ((ObjectTypeSymbol) prop.base_interface_property.parent_symbol);
1536 function.modifiers |= CCodeModifiers.STATIC;
1537 function.add_parameter (new CCodeParameter ("base", base_type.get_cname ()));
1538 } else {
1539 function.add_parameter (cselfparam);
1542 if (acc.writable || acc.construction || returns_real_struct) {
1543 function.add_parameter (cvalueparam);
1546 if (acc.value_type is ArrayType) {
1547 var array_type = (ArrayType) acc.value_type;
1549 var length_ctype = "int";
1550 if (acc.readable) {
1551 length_ctype = "int*";
1554 for (int dim = 1; dim <= array_type.rank; dim++) {
1555 function.add_parameter (new CCodeParameter (get_array_length_cname (acc.readable ? "result" : "value", dim), length_ctype));
1557 } else if ((acc.value_type is DelegateType) && ((DelegateType) acc.value_type).delegate_symbol.has_target) {
1558 function.add_parameter (new CCodeParameter (get_delegate_target_cname (acc.readable ? "result" : "value"), acc.readable ? "gpointer*" : "gpointer"));
1561 if (!is_virtual) {
1562 if (prop.is_private_symbol () || !(acc.readable || acc.writable) || acc.access == SymbolAccessibility.PRIVATE) {
1563 // accessor function should be private if the property is an internal symbol or it's a construct-only setter
1564 function.modifiers |= CCodeModifiers.STATIC;
1568 push_function (function);
1570 if (prop.binding == MemberBinding.INSTANCE && !is_virtual) {
1571 if (!acc.readable || returns_real_struct) {
1572 create_property_type_check_statement (prop, false, t, true, "self");
1573 } else {
1574 create_property_type_check_statement (prop, true, t, true, "self");
1578 if (acc.readable && !returns_real_struct) {
1579 // do not declare result variable if exit block is known to be unreachable
1580 if (acc.return_block == null || acc.return_block.get_predecessors ().size > 0) {
1581 ccode.add_declaration (acc.value_type.get_cname (), new CCodeVariableDeclarator ("result"));
1585 if (is_virtual) {
1586 ccode.add_declaration (this_type.get_cname (), new CCodeVariableDeclarator ("self"));
1587 ccode.add_assignment (new CCodeIdentifier ("self"), transform_expression (new CCodeIdentifier ("base"), base_type, this_type));
1590 acc.body.emit (this);
1592 if (current_method_inner_error) {
1593 ccode.add_declaration ("GError *", new CCodeVariableDeclarator.zero ("_inner_error_", new CCodeConstant ("NULL")));
1596 // notify on property changes
1597 if (is_gobject_property (prop) &&
1598 prop.notify &&
1599 (acc.writable || acc.construction)) {
1600 var notify_call = new CCodeFunctionCall (new CCodeIdentifier ("g_object_notify"));
1601 notify_call.add_argument (new CCodeCastExpression (new CCodeIdentifier ("self"), "GObject *"));
1602 notify_call.add_argument (prop.get_canonical_cconstant ());
1603 ccode.add_expression (notify_call);
1606 cfile.add_function (function);
1609 pop_context ();
1612 public override void visit_destructor (Destructor d) {
1613 if (d.binding == MemberBinding.STATIC && !in_plugin) {
1614 Report.error (d.source_reference, "static destructors are only supported for dynamic types");
1615 d.error = true;
1616 return;
1620 public int get_block_id (Block b) {
1621 int result = block_map[b];
1622 if (result == 0) {
1623 result = ++next_block_id;
1624 block_map[b] = result;
1626 return result;
1629 void capture_parameter (Parameter param, CCodeStruct data, int block_id) {
1630 generate_type_declaration (param.variable_type, cfile);
1632 var param_type = param.variable_type.copy ();
1633 param_type.value_owned = true;
1634 data.add_field (param_type.get_cname (), get_variable_cname (param.name));
1636 bool is_unowned_delegate = param.variable_type is DelegateType && !param.variable_type.value_owned;
1638 // create copy if necessary as captured variables may need to be kept alive
1639 CCodeExpression cparam = get_variable_cexpression (param.name);
1640 if (param.variable_type.is_real_non_null_struct_type ()) {
1641 cparam = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, cparam);
1643 if (requires_copy (param_type) && !param.variable_type.value_owned && !is_unowned_delegate) {
1644 var ma = new MemberAccess.simple (param.name);
1645 ma.symbol_reference = param;
1646 ma.value_type = param.variable_type.copy ();
1647 // directly access parameters in ref expressions
1648 param.captured = false;
1649 visit_member_access (ma);
1650 cparam = get_ref_cexpression (param.variable_type, cparam, ma, param);
1651 param.captured = true;
1654 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), get_variable_cname (param.name)), cparam);
1656 if (param.variable_type is ArrayType) {
1657 var array_type = (ArrayType) param.variable_type;
1658 for (int dim = 1; dim <= array_type.rank; dim++) {
1659 data.add_field ("gint", get_parameter_array_length_cname (param, dim));
1660 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), get_array_length_cname (get_variable_cname (param.name), dim)), new CCodeIdentifier (get_array_length_cname (get_variable_cname (param.name), dim)));
1662 } else if (param.variable_type is DelegateType) {
1663 CCodeExpression target_expr;
1664 CCodeExpression delegate_target_destroy_notify;
1665 if (is_in_coroutine ()) {
1666 target_expr = new CCodeMemberAccess.pointer (new CCodeIdentifier ("data"), get_delegate_target_cname (get_variable_cname (param.name)));
1667 delegate_target_destroy_notify = new CCodeMemberAccess.pointer (new CCodeIdentifier ("data"), get_delegate_target_destroy_notify_cname (get_variable_cname (param.name)));
1668 } else {
1669 target_expr = new CCodeIdentifier (get_delegate_target_cname (get_variable_cname (param.name)));
1670 delegate_target_destroy_notify = new CCodeIdentifier (get_delegate_target_destroy_notify_cname (get_variable_cname (param.name)));
1673 data.add_field ("gpointer", get_delegate_target_cname (get_variable_cname (param.name)));
1674 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), get_delegate_target_cname (get_variable_cname (param.name))), target_expr);
1675 if (param.variable_type.value_owned) {
1676 data.add_field ("GDestroyNotify", get_delegate_target_destroy_notify_cname (get_variable_cname (param.name)));
1677 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), get_delegate_target_destroy_notify_cname (get_variable_cname (param.name))), delegate_target_destroy_notify);
1682 public override void visit_block (Block b) {
1683 emit_context.push_symbol (b);
1685 var local_vars = b.get_local_variables ();
1687 if (b.parent_node is Block || b.parent_node is SwitchStatement) {
1688 ccode.open_block ();
1691 if (b.captured) {
1692 var parent_block = next_closure_block (b.parent_symbol);
1694 int block_id = get_block_id (b);
1695 string struct_name = "Block%dData".printf (block_id);
1697 var data = new CCodeStruct ("_" + struct_name);
1698 data.add_field ("int", "_ref_count_");
1699 if (parent_block != null) {
1700 int parent_block_id = get_block_id (parent_block);
1702 data.add_field ("Block%dData *".printf (parent_block_id), "_data%d_".printf (parent_block_id));
1703 } else {
1704 if (in_constructor || (current_method != null && current_method.binding == MemberBinding.INSTANCE) ||
1705 (current_property_accessor != null && current_property_accessor.prop.binding == MemberBinding.INSTANCE)) {
1706 data.add_field ("%s *".printf (current_class.get_cname ()), "self");
1709 if (current_method != null) {
1710 // allow capturing generic type parameters
1711 foreach (var type_param in current_method.get_type_parameters ()) {
1712 string func_name;
1714 func_name = "%s_type".printf (type_param.name.down ());
1715 data.add_field ("GType", func_name);
1717 func_name = "%s_dup_func".printf (type_param.name.down ());
1718 data.add_field ("GBoxedCopyFunc", func_name);
1720 func_name = "%s_destroy_func".printf (type_param.name.down ());
1721 data.add_field ("GDestroyNotify", func_name);
1725 foreach (var local in local_vars) {
1726 if (local.captured) {
1727 generate_type_declaration (local.variable_type, cfile);
1729 data.add_field (local.variable_type.get_cname (), get_variable_cname (local.name) + local.variable_type.get_cdeclarator_suffix ());
1731 if (local.variable_type is ArrayType) {
1732 var array_type = (ArrayType) local.variable_type;
1733 for (int dim = 1; dim <= array_type.rank; dim++) {
1734 data.add_field ("gint", get_array_length_cname (get_variable_cname (local.name), dim));
1736 data.add_field ("gint", get_array_size_cname (get_variable_cname (local.name)));
1737 } else if (local.variable_type is DelegateType) {
1738 data.add_field ("gpointer", get_delegate_target_cname (get_variable_cname (local.name)));
1739 if (local.variable_type.value_owned) {
1740 data.add_field ("GDestroyNotify", get_delegate_target_destroy_notify_cname (get_variable_cname (local.name)));
1746 var data_alloc = new CCodeFunctionCall (new CCodeIdentifier ("g_slice_new0"));
1747 data_alloc.add_argument (new CCodeIdentifier (struct_name));
1749 if (is_in_coroutine ()) {
1750 closure_struct.add_field (struct_name + "*", "_data%d_".printf (block_id));
1751 } else {
1752 ccode.add_declaration (struct_name + "*", new CCodeVariableDeclarator ("_data%d_".printf (block_id)));
1754 ccode.add_assignment (get_variable_cexpression ("_data%d_".printf (block_id)), data_alloc);
1756 // initialize ref_count
1757 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), "_ref_count_"), new CCodeIdentifier ("1"));
1759 if (parent_block != null) {
1760 int parent_block_id = get_block_id (parent_block);
1762 var ref_call = new CCodeFunctionCall (new CCodeIdentifier ("block%d_data_ref".printf (parent_block_id)));
1763 ref_call.add_argument (get_variable_cexpression ("_data%d_".printf (parent_block_id)));
1765 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), "_data%d_".printf (parent_block_id)), ref_call);
1766 } else {
1767 if (in_constructor || (current_method != null && current_method.binding == MemberBinding.INSTANCE &&
1768 (!(current_method is CreationMethod) || current_method.body != b)) ||
1769 (current_property_accessor != null && current_property_accessor.prop.binding == MemberBinding.INSTANCE)) {
1770 var ref_call = new CCodeFunctionCall (get_dup_func_expression (new ObjectType (current_class), b.source_reference));
1771 ref_call.add_argument (get_result_cexpression ("self"));
1773 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), "self"), ref_call);
1776 if (current_method != null) {
1777 // allow capturing generic type parameters
1778 foreach (var type_param in current_method.get_type_parameters ()) {
1779 string func_name;
1781 func_name = "%s_type".printf (type_param.name.down ());
1782 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), func_name), new CCodeIdentifier (func_name));
1784 func_name = "%s_dup_func".printf (type_param.name.down ());
1785 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), func_name), new CCodeIdentifier (func_name));
1787 func_name = "%s_destroy_func".printf (type_param.name.down ());
1788 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), func_name), new CCodeIdentifier (func_name));
1793 if (b.parent_symbol is Method) {
1794 var m = (Method) b.parent_symbol;
1796 // parameters are captured with the top-level block of the method
1797 foreach (var param in m.get_parameters ()) {
1798 if (param.captured) {
1799 capture_parameter (param, data, block_id);
1803 if (m.coroutine) {
1804 // capture async data to allow invoking callback from inside closure
1805 data.add_field ("gpointer", "_async_data_");
1807 // async method is suspended while waiting for callback,
1808 // so we never need to care about memory management of async data
1809 ccode.add_assignment (new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (block_id)), "_async_data_"), new CCodeIdentifier ("data"));
1811 } else if (b.parent_symbol is PropertyAccessor) {
1812 var acc = (PropertyAccessor) b.parent_symbol;
1814 if (!acc.readable && acc.value_parameter.captured) {
1815 capture_parameter (acc.value_parameter, data, block_id);
1819 var typedef = new CCodeTypeDefinition ("struct _" + struct_name, new CCodeVariableDeclarator (struct_name));
1820 cfile.add_type_declaration (typedef);
1821 cfile.add_type_definition (data);
1823 // create ref/unref functions
1824 var ref_fun = new CCodeFunction ("block%d_data_ref".printf (block_id), struct_name + "*");
1825 ref_fun.add_parameter (new CCodeParameter ("_data%d_".printf (block_id), struct_name + "*"));
1826 ref_fun.modifiers = CCodeModifiers.STATIC;
1827 cfile.add_function_declaration (ref_fun);
1828 ref_fun.block = new CCodeBlock ();
1830 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_atomic_int_inc"));
1831 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, new CCodeMemberAccess.pointer (new CCodeIdentifier ("_data%d_".printf (block_id)), "_ref_count_")));
1832 ref_fun.block.add_statement (new CCodeExpressionStatement (ccall));
1833 ref_fun.block.add_statement (new CCodeReturnStatement (new CCodeIdentifier ("_data%d_".printf (block_id))));
1834 cfile.add_function (ref_fun);
1836 var unref_fun = new CCodeFunction ("block%d_data_unref".printf (block_id), "void");
1837 unref_fun.add_parameter (new CCodeParameter ("_data%d_".printf (block_id), struct_name + "*"));
1838 unref_fun.modifiers = CCodeModifiers.STATIC;
1839 cfile.add_function_declaration (unref_fun);
1841 push_function (unref_fun);
1843 ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_atomic_int_dec_and_test"));
1844 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, new CCodeMemberAccess.pointer (new CCodeIdentifier ("_data%d_".printf (block_id)), "_ref_count_")));
1845 ccode.open_if (ccall);
1847 if (parent_block != null) {
1848 int parent_block_id = get_block_id (parent_block);
1850 var unref_call = new CCodeFunctionCall (new CCodeIdentifier ("block%d_data_unref".printf (parent_block_id)));
1851 unref_call.add_argument (new CCodeMemberAccess.pointer (new CCodeIdentifier ("_data%d_".printf (block_id)), "_data%d_".printf (parent_block_id)));
1852 ccode.add_expression (unref_call);
1853 ccode.add_assignment (new CCodeMemberAccess.pointer (new CCodeIdentifier ("_data%d_".printf (block_id)), "_data%d_".printf (parent_block_id)), new CCodeConstant ("NULL"));
1854 } else {
1855 if (in_constructor || (current_method != null && current_method.binding == MemberBinding.INSTANCE) ||
1856 (current_property_accessor != null && current_property_accessor.prop.binding == MemberBinding.INSTANCE)) {
1857 var this_value = new GLibValue (new ObjectType (current_class), new CCodeMemberAccess.pointer (new CCodeIdentifier ("_data%d_".printf (block_id)), "self"));
1858 ccode.add_expression (destroy_value (this_value));
1862 // free in reverse order
1863 for (int i = local_vars.size - 1; i >= 0; i--) {
1864 var local = local_vars[i];
1865 if (local.captured) {
1866 if (requires_destroy (local.variable_type)) {
1867 bool old_coroutine = false;
1868 if (current_method != null) {
1869 old_coroutine = current_method.coroutine;
1870 current_method.coroutine = false;
1873 ccode.add_expression (destroy_local (local));
1875 if (old_coroutine) {
1876 current_method.coroutine = true;
1882 if (b.parent_symbol is Method) {
1883 var m = (Method) b.parent_symbol;
1885 // parameters are captured with the top-level block of the method
1886 foreach (var param in m.get_parameters ()) {
1887 if (param.captured) {
1888 var param_type = param.variable_type.copy ();
1889 param_type.value_owned = true;
1891 bool is_unowned_delegate = param.variable_type is DelegateType && !param.variable_type.value_owned;
1893 if (requires_destroy (param_type) && !is_unowned_delegate) {
1894 bool old_coroutine = false;
1895 if (m != null) {
1896 old_coroutine = m.coroutine;
1897 m.coroutine = false;
1900 ccode.add_expression (destroy_parameter (param));
1902 if (old_coroutine) {
1903 m.coroutine = true;
1908 } else if (b.parent_symbol is PropertyAccessor) {
1909 var acc = (PropertyAccessor) b.parent_symbol;
1911 if (!acc.readable && acc.value_parameter.captured) {
1912 var param_type = acc.value_parameter.variable_type.copy ();
1913 param_type.value_owned = true;
1915 bool is_unowned_delegate = acc.value_parameter.variable_type is DelegateType && !acc.value_parameter.variable_type.value_owned;
1917 if (requires_destroy (param_type) && !is_unowned_delegate) {
1918 ccode.add_expression (destroy_parameter (acc.value_parameter));
1923 var data_free = new CCodeFunctionCall (new CCodeIdentifier ("g_slice_free"));
1924 data_free.add_argument (new CCodeIdentifier (struct_name));
1925 data_free.add_argument (new CCodeIdentifier ("_data%d_".printf (block_id)));
1926 ccode.add_expression (data_free);
1928 ccode.close ();
1930 pop_function ();
1932 cfile.add_function (unref_fun);
1935 foreach (Statement stmt in b.get_statements ()) {
1936 stmt.emit (this);
1939 // free in reverse order
1940 for (int i = local_vars.size - 1; i >= 0; i--) {
1941 var local = local_vars[i];
1942 local.active = false;
1943 if (!local.unreachable && !local.floating && !local.captured && requires_destroy (local.variable_type)) {
1944 ccode.add_expression (destroy_local (local));
1948 if (b.parent_symbol is Method) {
1949 var m = (Method) b.parent_symbol;
1950 foreach (Parameter param in m.get_parameters ()) {
1951 if (!param.captured && !param.ellipsis && requires_destroy (param.variable_type) && param.direction == ParameterDirection.IN) {
1952 ccode.add_expression (destroy_parameter (param));
1953 } else if (param.direction == ParameterDirection.OUT && !m.coroutine) {
1954 return_out_parameter (param);
1959 if (b.captured) {
1960 int block_id = get_block_id (b);
1962 var data_unref = new CCodeFunctionCall (new CCodeIdentifier ("block%d_data_unref".printf (block_id)));
1963 data_unref.add_argument (get_variable_cexpression ("_data%d_".printf (block_id)));
1964 ccode.add_expression (data_unref);
1965 ccode.add_assignment (get_variable_cexpression ("_data%d_".printf (block_id)), new CCodeConstant ("NULL"));
1968 if (b.parent_node is Block || b.parent_node is SwitchStatement) {
1969 ccode.close ();
1972 emit_context.pop_symbol ();
1975 public override void visit_declaration_statement (DeclarationStatement stmt) {
1976 stmt.declaration.accept (this);
1979 public CCodeExpression get_variable_cexpression (string name) {
1980 if (is_in_coroutine ()) {
1981 return new CCodeMemberAccess.pointer (new CCodeIdentifier ("data"), get_variable_cname (name));
1982 } else {
1983 return new CCodeIdentifier (get_variable_cname (name));
1987 public string get_variable_cname (string name) {
1988 if (name[0] == '.') {
1989 if (name == ".result") {
1990 return "result";
1992 // compiler-internal variable
1993 if (!variable_name_map.contains (name)) {
1994 variable_name_map.set (name, "_tmp%d_".printf (next_temp_var_id));
1995 next_temp_var_id++;
1997 return variable_name_map.get (name);
1998 } else if (reserved_identifiers.contains (name)) {
1999 return "_%s_".printf (name);
2000 } else {
2001 return name;
2005 public CCodeExpression get_result_cexpression (string cname = "result") {
2006 if (is_in_coroutine ()) {
2007 return new CCodeMemberAccess.pointer (new CCodeIdentifier ("data"), cname);
2008 } else {
2009 return new CCodeIdentifier (cname);
2013 bool has_simple_struct_initializer (LocalVariable local) {
2014 var st = local.variable_type.data_type as Struct;
2015 var initializer = local.initializer as ObjectCreationExpression;
2016 if (st != null && (!st.is_simple_type () || st.get_cname () == "va_list") && !local.variable_type.nullable &&
2017 initializer != null && initializer.get_object_initializer ().size == 0) {
2018 return true;
2019 } else {
2020 return false;
2024 public override void visit_local_variable (LocalVariable local) {
2025 check_type (local.variable_type);
2027 if (local.initializer != null) {
2028 local.initializer.emit (this);
2030 visit_end_full_expression (local.initializer);
2033 generate_type_declaration (local.variable_type, cfile);
2035 CCodeExpression rhs = null;
2036 if (local.initializer != null && get_cvalue (local.initializer) != null) {
2037 rhs = get_cvalue (local.initializer);
2040 if (!local.captured) {
2041 if (current_method != null && current_method.coroutine) {
2042 closure_struct.add_field (local.variable_type.get_cname (), get_variable_cname (local.name) + local.variable_type.get_cdeclarator_suffix ());
2043 } else {
2044 var cvar = new CCodeVariableDeclarator (get_variable_cname (local.name), null, local.variable_type.get_cdeclarator_suffix ());
2046 // try to initialize uninitialized variables
2047 // initialization not necessary for variables stored in closure
2048 if (rhs == null || has_simple_struct_initializer (local)) {
2049 cvar.initializer = default_value_for_type (local.variable_type, true);
2050 cvar.init0 = true;
2053 ccode.add_declaration (local.variable_type.get_cname (), cvar);
2056 if (local.variable_type is ArrayType) {
2057 // create variables to store array dimensions
2058 var array_type = (ArrayType) local.variable_type;
2060 if (!array_type.fixed_length) {
2061 for (int dim = 1; dim <= array_type.rank; dim++) {
2062 var len_var = new LocalVariable (int_type.copy (), get_array_length_cname (get_variable_cname (local.name), dim));
2063 emit_temp_var (len_var, local.initializer == null);
2066 if (array_type.rank == 1) {
2067 var size_var = new LocalVariable (int_type.copy (), get_array_size_cname (get_variable_cname (local.name)));
2068 emit_temp_var (size_var, local.initializer == null);
2071 } else if (local.variable_type is DelegateType) {
2072 var deleg_type = (DelegateType) local.variable_type;
2073 var d = deleg_type.delegate_symbol;
2074 if (d.has_target) {
2075 // create variable to store delegate target
2076 var target_var = new LocalVariable (new PointerType (new VoidType ()), get_delegate_target_cname (get_variable_cname (local.name)));
2077 emit_temp_var (target_var, local.initializer == null);
2078 if (deleg_type.value_owned) {
2079 var target_destroy_notify_var = new LocalVariable (gdestroynotify_type, get_delegate_target_destroy_notify_cname (get_variable_cname (local.name)));
2080 emit_temp_var (target_destroy_notify_var, local.initializer == null);
2086 if (rhs != null) {
2087 if (!has_simple_struct_initializer (local)) {
2088 store_local (local, local.initializer.target_value, true);
2092 if (local.initializer != null && local.initializer.tree_can_fail) {
2093 add_simple_check (local.initializer);
2096 local.active = true;
2099 public override void visit_initializer_list (InitializerList list) {
2100 if (list.target_type.data_type is Struct) {
2101 /* initializer is used as struct initializer */
2102 var st = (Struct) list.target_type.data_type;
2104 if (list.parent_node is Constant || list.parent_node is Field || list.parent_node is InitializerList) {
2105 var clist = new CCodeInitializerList ();
2107 var field_it = st.get_fields ().iterator ();
2108 foreach (Expression expr in list.get_initializers ()) {
2109 Field field = null;
2110 while (field == null) {
2111 field_it.next ();
2112 field = field_it.get ();
2113 if (field.binding != MemberBinding.INSTANCE) {
2114 // we only initialize instance fields
2115 field = null;
2119 var cexpr = get_cvalue (expr);
2121 string ctype = field.get_ctype ();
2122 if (ctype != null) {
2123 cexpr = new CCodeCastExpression (cexpr, ctype);
2126 clist.append (cexpr);
2128 var array_type = field.variable_type as ArrayType;
2129 if (array_type != null && !field.no_array_length && !field.array_null_terminated) {
2130 for (int dim = 1; dim <= array_type.rank; dim++) {
2131 clist.append (get_array_length_cvalue (expr.target_value, dim));
2136 set_cvalue (list, clist);
2137 } else {
2138 // used as expression
2139 var temp_decl = get_temp_variable (list.target_type, false, list);
2140 emit_temp_var (temp_decl);
2142 var instance = get_variable_cexpression (get_variable_cname (temp_decl.name));
2144 var field_it = st.get_fields ().iterator ();
2145 foreach (Expression expr in list.get_initializers ()) {
2146 Field field = null;
2147 while (field == null) {
2148 field_it.next ();
2149 field = field_it.get ();
2150 if (field.binding != MemberBinding.INSTANCE) {
2151 // we only initialize instance fields
2152 field = null;
2156 var cexpr = get_cvalue (expr);
2158 string ctype = field.get_ctype ();
2159 if (ctype != null) {
2160 cexpr = new CCodeCastExpression (cexpr, ctype);
2163 var lhs = new CCodeMemberAccess (instance, field.get_cname ());;
2164 ccode.add_assignment (lhs, cexpr);
2167 set_cvalue (list, instance);
2169 } else {
2170 var clist = new CCodeInitializerList ();
2171 foreach (Expression expr in list.get_initializers ()) {
2172 clist.append (get_cvalue (expr));
2174 set_cvalue (list, clist);
2178 public override LocalVariable create_local (DataType type) {
2179 var result = get_temp_variable (type, type.value_owned);
2180 emit_temp_var (result);
2181 return result;
2184 public LocalVariable get_temp_variable (DataType type, bool value_owned = true, CodeNode? node_reference = null, bool init = true) {
2185 var var_type = type.copy ();
2186 var_type.value_owned = value_owned;
2187 var local = new LocalVariable (var_type, "_tmp%d_".printf (next_temp_var_id));
2188 local.no_init = !init;
2190 if (node_reference != null) {
2191 local.source_reference = node_reference.source_reference;
2194 next_temp_var_id++;
2196 return local;
2199 bool is_in_generic_type (DataType type) {
2200 if (current_symbol != null && type.type_parameter.parent_symbol is TypeSymbol
2201 && (current_method == null || current_method.binding == MemberBinding.INSTANCE)) {
2202 return true;
2203 } else {
2204 return false;
2208 public CCodeExpression get_type_id_expression (DataType type, bool is_chainup = false) {
2209 if (type is GenericType) {
2210 string var_name = "%s_type".printf (type.type_parameter.name.down ());
2211 if (is_in_generic_type (type) && !is_chainup && !in_creation_method) {
2212 return new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (get_result_cexpression ("self"), "priv"), var_name);
2213 } else {
2214 return new CCodeIdentifier (var_name);
2216 } else {
2217 string type_id = type.get_type_id ();
2218 if (type_id == null) {
2219 type_id = "G_TYPE_INVALID";
2220 } else {
2221 generate_type_declaration (type, cfile);
2223 return new CCodeIdentifier (type_id);
2227 public virtual CCodeExpression? get_dup_func_expression (DataType type, SourceReference? source_reference, bool is_chainup = false) {
2228 if (type is ErrorType) {
2229 return new CCodeIdentifier ("g_error_copy");
2230 } else if (type.data_type != null) {
2231 string dup_function;
2232 var cl = type.data_type as Class;
2233 if (type.data_type.is_reference_counting ()) {
2234 dup_function = type.data_type.get_ref_function ();
2235 if (type.data_type is Interface && dup_function == null) {
2236 Report.error (source_reference, "missing class prerequisite for interface `%s', add GLib.Object to interface declaration if unsure".printf (type.data_type.get_full_name ()));
2237 return null;
2239 } else if (cl != null && cl.is_immutable) {
2240 // allow duplicates of immutable instances as for example strings
2241 dup_function = type.data_type.get_dup_function ();
2242 if (dup_function == null) {
2243 dup_function = "";
2245 } else if (cl != null && cl.is_gboxed) {
2246 // allow duplicates of gboxed instances
2247 dup_function = generate_dup_func_wrapper (type);
2248 if (dup_function == null) {
2249 dup_function = "";
2251 } else if (type is ValueType) {
2252 dup_function = type.data_type.get_dup_function ();
2253 if (dup_function == null && type.nullable) {
2254 dup_function = generate_struct_dup_wrapper ((ValueType) type);
2255 } else if (dup_function == null) {
2256 dup_function = "";
2258 } else {
2259 // duplicating non-reference counted objects may cause side-effects (and performance issues)
2260 Report.error (source_reference, "duplicating %s instance, use unowned variable or explicitly invoke copy method".printf (type.data_type.name));
2261 return null;
2264 return new CCodeIdentifier (dup_function);
2265 } else if (type.type_parameter != null) {
2266 string func_name = "%s_dup_func".printf (type.type_parameter.name.down ());
2267 if (is_in_generic_type (type) && !is_chainup && !in_creation_method) {
2268 return new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (get_result_cexpression ("self"), "priv"), func_name);
2269 } else {
2270 return new CCodeIdentifier (func_name);
2272 } else if (type is PointerType) {
2273 var pointer_type = (PointerType) type;
2274 return get_dup_func_expression (pointer_type.base_type, source_reference);
2275 } else {
2276 return new CCodeConstant ("NULL");
2280 void make_comparable_cexpression (ref DataType left_type, ref CCodeExpression cleft, ref DataType right_type, ref CCodeExpression cright) {
2281 var left_type_as_struct = left_type.data_type as Struct;
2282 var right_type_as_struct = right_type.data_type as Struct;
2284 // GValue support
2285 var valuecast = try_cast_value_to_type (cleft, left_type, right_type);
2286 if (valuecast != null) {
2287 cleft = valuecast;
2288 left_type = right_type;
2289 make_comparable_cexpression (ref left_type, ref cleft, ref right_type, ref cright);
2290 return;
2293 valuecast = try_cast_value_to_type (cright, right_type, left_type);
2294 if (valuecast != null) {
2295 cright = valuecast;
2296 right_type = left_type;
2297 make_comparable_cexpression (ref left_type, ref cleft, ref right_type, ref cright);
2298 return;
2301 if (left_type.data_type is Class && !((Class) left_type.data_type).is_compact &&
2302 right_type.data_type is Class && !((Class) right_type.data_type).is_compact) {
2303 var left_cl = (Class) left_type.data_type;
2304 var right_cl = (Class) right_type.data_type;
2306 if (left_cl != right_cl) {
2307 if (left_cl.is_subtype_of (right_cl)) {
2308 cleft = generate_instance_cast (cleft, right_cl);
2309 } else if (right_cl.is_subtype_of (left_cl)) {
2310 cright = generate_instance_cast (cright, left_cl);
2313 } else if (left_type_as_struct != null && right_type_as_struct != null) {
2314 if (left_type is StructValueType) {
2315 // real structs (uses compare/equal function)
2316 if (!left_type.nullable) {
2317 cleft = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cleft);
2319 if (!right_type.nullable) {
2320 cright = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cright);
2322 } else {
2323 // integer or floating or boolean type
2324 if (left_type.nullable && right_type.nullable) {
2325 // FIXME also compare contents, not just address
2326 } else if (left_type.nullable) {
2327 // FIXME check left value is not null
2328 cleft = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, cleft);
2329 } else if (right_type.nullable) {
2330 // FIXME check right value is not null
2331 cright = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, cright);
2337 private string generate_struct_equal_function (Struct st) {
2338 string equal_func = "_%sequal".printf (st.get_lower_case_cprefix ());
2340 if (!add_wrapper (equal_func)) {
2341 // wrapper already defined
2342 return equal_func;
2345 var function = new CCodeFunction (equal_func, "gboolean");
2346 function.modifiers = CCodeModifiers.STATIC;
2348 function.add_parameter (new CCodeParameter ("s1", "const " + st.get_cname () + "*"));
2349 function.add_parameter (new CCodeParameter ("s2", "const " + st.get_cname () + "*"));
2351 push_function (function);
2353 // if (s1 == s2) return TRUE;
2355 var cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("s1"), new CCodeIdentifier ("s2"));
2356 ccode.open_if (cexp);
2357 ccode.add_return (new CCodeConstant ("TRUE"));
2358 ccode.close ();
2360 // if (s1 == NULL || s2 == NULL) return FALSE;
2362 var cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("s1"), new CCodeConstant ("NULL"));
2363 ccode.open_if (cexp);
2364 ccode.add_return (new CCodeConstant ("FALSE"));
2365 ccode.close ();
2367 cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("s2"), new CCodeConstant ("NULL"));
2368 ccode.open_if (cexp);
2369 ccode.add_return (new CCodeConstant ("FALSE"));
2370 ccode.close ();
2373 foreach (Field f in st.get_fields ()) {
2374 if (f.binding != MemberBinding.INSTANCE) {
2375 // we only compare instance fields
2376 continue;
2379 CCodeExpression cexp; // if (cexp) return FALSE;
2380 var s1 = (CCodeExpression) new CCodeMemberAccess.pointer (new CCodeIdentifier ("s1"), f.name); // s1->f
2381 var s2 = (CCodeExpression) new CCodeMemberAccess.pointer (new CCodeIdentifier ("s2"), f.name); // s2->f
2383 var variable_type = f.variable_type.copy ();
2384 make_comparable_cexpression (ref variable_type, ref s1, ref variable_type, ref s2);
2386 if (!(f.variable_type is NullType) && f.variable_type.compatible (string_type)) {
2387 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_strcmp0"));
2388 ccall.add_argument (s1);
2389 ccall.add_argument (s2);
2390 cexp = ccall;
2391 } else if (f.variable_type is StructValueType) {
2392 var equalfunc = generate_struct_equal_function (f.variable_type.data_type as Struct);
2393 var ccall = new CCodeFunctionCall (new CCodeIdentifier (equalfunc));
2394 ccall.add_argument (s1);
2395 ccall.add_argument (s2);
2396 cexp = new CCodeUnaryExpression (CCodeUnaryOperator.LOGICAL_NEGATION, ccall);
2397 } else {
2398 cexp = new CCodeBinaryExpression (CCodeBinaryOperator.INEQUALITY, s1, s2);
2401 ccode.open_if (cexp);
2402 ccode.add_return (new CCodeConstant ("FALSE"));
2403 ccode.close ();
2406 if (st.get_fields().size == 0) {
2407 // either opaque structure or simple type
2408 if (st.is_simple_type ()) {
2409 var cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, new CCodeIdentifier ("s1")), new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, new CCodeIdentifier ("s2")));
2410 ccode.add_return (cexp);
2411 } else {
2412 ccode.add_return (new CCodeConstant ("FALSE"));
2414 } else {
2415 ccode.add_return (new CCodeConstant ("TRUE"));
2418 pop_function ();
2420 cfile.add_function_declaration (function);
2421 cfile.add_function (function);
2423 return equal_func;
2426 private string generate_numeric_equal_function (Struct st) {
2427 string equal_func = "_%sequal".printf (st.get_lower_case_cprefix ());
2429 if (!add_wrapper (equal_func)) {
2430 // wrapper already defined
2431 return equal_func;
2434 var function = new CCodeFunction (equal_func, "gboolean");
2435 function.modifiers = CCodeModifiers.STATIC;
2437 function.add_parameter (new CCodeParameter ("s1", "const " + st.get_cname () + "*"));
2438 function.add_parameter (new CCodeParameter ("s2", "const " + st.get_cname () + "*"));
2440 push_function (function);
2442 // if (s1 == s2) return TRUE;
2444 var cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("s1"), new CCodeIdentifier ("s2"));
2445 ccode.open_if (cexp);
2446 ccode.add_return (new CCodeConstant ("TRUE"));
2447 ccode.close ();
2449 // if (s1 == NULL || s2 == NULL) return FALSE;
2451 var cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("s1"), new CCodeConstant ("NULL"));
2452 ccode.open_if (cexp);
2453 ccode.add_return (new CCodeConstant ("FALSE"));
2454 ccode.close ();
2456 cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier ("s2"), new CCodeConstant ("NULL"));
2457 ccode.open_if (cexp);
2458 ccode.add_return (new CCodeConstant ("FALSE"));
2459 ccode.close ();
2461 // return (*s1 == *s2);
2463 var cexp = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, new CCodeIdentifier ("s1")), new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, new CCodeIdentifier ("s2")));
2464 ccode.add_return (cexp);
2467 pop_function ();
2469 cfile.add_function_declaration (function);
2470 cfile.add_function (function);
2472 return equal_func;
2475 private string generate_struct_dup_wrapper (ValueType value_type) {
2476 string dup_func = "_%sdup".printf (value_type.type_symbol.get_lower_case_cprefix ());
2478 if (!add_wrapper (dup_func)) {
2479 // wrapper already defined
2480 return dup_func;
2483 var function = new CCodeFunction (dup_func, value_type.get_cname ());
2484 function.modifiers = CCodeModifiers.STATIC;
2486 function.add_parameter (new CCodeParameter ("self", value_type.get_cname ()));
2488 push_function (function);
2490 if (value_type.type_symbol == gvalue_type) {
2491 var dup_call = new CCodeFunctionCall (new CCodeIdentifier ("g_boxed_copy"));
2492 dup_call.add_argument (new CCodeIdentifier ("G_TYPE_VALUE"));
2493 dup_call.add_argument (new CCodeIdentifier ("self"));
2495 ccode.add_return (dup_call);
2496 } else {
2497 ccode.add_declaration (value_type.get_cname (), new CCodeVariableDeclarator ("dup"));
2499 var creation_call = new CCodeFunctionCall (new CCodeIdentifier ("g_new0"));
2500 creation_call.add_argument (new CCodeConstant (value_type.data_type.get_cname ()));
2501 creation_call.add_argument (new CCodeConstant ("1"));
2502 ccode.add_assignment (new CCodeIdentifier ("dup"), creation_call);
2504 var st = value_type.data_type as Struct;
2505 if (st != null && st.is_disposable ()) {
2506 if (!st.has_copy_function) {
2507 generate_struct_copy_function (st);
2510 var copy_call = new CCodeFunctionCall (new CCodeIdentifier (st.get_copy_function ()));
2511 copy_call.add_argument (new CCodeIdentifier ("self"));
2512 copy_call.add_argument (new CCodeIdentifier ("dup"));
2513 ccode.add_expression (copy_call);
2514 } else {
2515 cfile.add_include ("string.h");
2517 var sizeof_call = new CCodeFunctionCall (new CCodeIdentifier ("sizeof"));
2518 sizeof_call.add_argument (new CCodeConstant (value_type.data_type.get_cname ()));
2520 var copy_call = new CCodeFunctionCall (new CCodeIdentifier ("memcpy"));
2521 copy_call.add_argument (new CCodeIdentifier ("dup"));
2522 copy_call.add_argument (new CCodeIdentifier ("self"));
2523 copy_call.add_argument (sizeof_call);
2524 ccode.add_expression (copy_call);
2527 ccode.add_return (new CCodeIdentifier ("dup"));
2530 pop_function ();
2532 cfile.add_function_declaration (function);
2533 cfile.add_function (function);
2535 return dup_func;
2538 protected string generate_dup_func_wrapper (DataType type) {
2539 string destroy_func = "_vala_%s_copy".printf (type.data_type.get_cname ());
2541 if (!add_wrapper (destroy_func)) {
2542 // wrapper already defined
2543 return destroy_func;
2546 var function = new CCodeFunction (destroy_func, type.get_cname ());
2547 function.modifiers = CCodeModifiers.STATIC;
2548 function.add_parameter (new CCodeParameter ("self", type.get_cname ()));
2550 push_function (function);
2552 var cl = type.data_type as Class;
2553 assert (cl != null && cl.is_gboxed);
2555 var free_call = new CCodeFunctionCall (new CCodeIdentifier ("g_boxed_copy"));
2556 free_call.add_argument (new CCodeIdentifier (cl.get_type_id ()));
2557 free_call.add_argument (new CCodeIdentifier ("self"));
2559 ccode.add_return (free_call);
2561 pop_function ();
2563 cfile.add_function_declaration (function);
2564 cfile.add_function (function);
2566 return destroy_func;
2569 protected string generate_free_func_wrapper (DataType type) {
2570 string destroy_func = "_vala_%s_free".printf (type.data_type.get_cname ());
2572 if (!add_wrapper (destroy_func)) {
2573 // wrapper already defined
2574 return destroy_func;
2577 var function = new CCodeFunction (destroy_func, "void");
2578 function.modifiers = CCodeModifiers.STATIC;
2579 function.add_parameter (new CCodeParameter ("self", type.get_cname ()));
2581 push_function (function);
2583 var cl = type.data_type as Class;
2584 if (cl != null && cl.is_gboxed) {
2585 var free_call = new CCodeFunctionCall (new CCodeIdentifier ("g_boxed_free"));
2586 free_call.add_argument (new CCodeIdentifier (cl.get_type_id ()));
2587 free_call.add_argument (new CCodeIdentifier ("self"));
2589 ccode.add_expression (free_call);
2590 } else if (cl != null) {
2591 assert (cl.free_function_address_of);
2593 var free_call = new CCodeFunctionCall (new CCodeIdentifier (type.data_type.get_free_function ()));
2594 free_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, new CCodeIdentifier ("self")));
2596 ccode.add_expression (free_call);
2597 } else {
2598 var st = type.data_type as Struct;
2599 if (st != null && st.is_disposable ()) {
2600 if (!st.has_destroy_function) {
2601 generate_struct_destroy_function (st);
2604 var destroy_call = new CCodeFunctionCall (new CCodeIdentifier (st.get_destroy_function ()));
2605 destroy_call.add_argument (new CCodeIdentifier ("self"));
2606 ccode.add_expression (destroy_call);
2609 var free_call = new CCodeFunctionCall (new CCodeIdentifier ("g_free"));
2610 free_call.add_argument (new CCodeIdentifier ("self"));
2612 ccode.add_expression (free_call);
2615 pop_function ();
2617 cfile.add_function_declaration (function);
2618 cfile.add_function (function);
2620 return destroy_func;
2623 public CCodeExpression? get_destroy0_func_expression (DataType type, bool is_chainup = false) {
2624 var element_destroy_func_expression = get_destroy_func_expression (type, is_chainup);
2626 if (element_destroy_func_expression is CCodeIdentifier) {
2627 var freeid = (CCodeIdentifier) element_destroy_func_expression;
2628 string free0_func = "_%s0_".printf (freeid.name);
2630 if (add_wrapper (free0_func)) {
2631 var function = new CCodeFunction (free0_func, "void");
2632 function.modifiers = CCodeModifiers.STATIC;
2634 function.add_parameter (new CCodeParameter ("var", "gpointer"));
2636 push_function (function);
2638 ccode.add_expression (get_unref_expression (new CCodeIdentifier ("var"), type, null, true));
2640 pop_function ();
2642 cfile.add_function_declaration (function);
2643 cfile.add_function (function);
2646 element_destroy_func_expression = new CCodeIdentifier (free0_func);
2649 return element_destroy_func_expression;
2652 public CCodeExpression? get_destroy_func_expression (DataType type, bool is_chainup = false) {
2653 if (context.profile == Profile.GOBJECT && (type.data_type == glist_type || type.data_type == gslist_type || type.data_type == gnode_type)) {
2654 // create wrapper function to free list elements if necessary
2656 bool elements_require_free = false;
2657 CCodeExpression element_destroy_func_expression = null;
2659 foreach (DataType type_arg in type.get_type_arguments ()) {
2660 elements_require_free = requires_destroy (type_arg);
2661 if (elements_require_free) {
2662 element_destroy_func_expression = get_destroy0_func_expression (type_arg);
2666 if (elements_require_free && element_destroy_func_expression is CCodeIdentifier) {
2667 return new CCodeIdentifier (generate_collection_free_wrapper (type, (CCodeIdentifier) element_destroy_func_expression));
2668 } else {
2669 return new CCodeIdentifier (type.data_type.get_free_function ());
2671 } else if (type is ErrorType) {
2672 return new CCodeIdentifier ("g_error_free");
2673 } else if (type.data_type != null) {
2674 string unref_function;
2675 if (type is ReferenceType) {
2676 if (type.data_type.is_reference_counting ()) {
2677 unref_function = type.data_type.get_unref_function ();
2678 if (type.data_type is Interface && unref_function == null) {
2679 Report.error (type.source_reference, "missing class prerequisite for interface `%s', add GLib.Object to interface declaration if unsure".printf (type.data_type.get_full_name ()));
2680 return null;
2682 } else {
2683 var cl = type.data_type as Class;
2684 if (cl != null && (cl.free_function_address_of || cl.is_gboxed)) {
2685 unref_function = generate_free_func_wrapper (type);
2686 } else {
2687 unref_function = type.data_type.get_free_function ();
2690 } else {
2691 if (type.nullable) {
2692 unref_function = type.data_type.get_free_function ();
2693 if (unref_function == null) {
2694 if (type.data_type is Struct && ((Struct) type.data_type).is_disposable ()) {
2695 unref_function = generate_free_func_wrapper (type);
2696 } else {
2697 unref_function = "g_free";
2700 } else {
2701 var st = (Struct) type.data_type;
2702 if (!st.has_destroy_function) {
2703 generate_struct_destroy_function (st);
2705 unref_function = st.get_destroy_function ();
2708 if (unref_function == null) {
2709 return new CCodeConstant ("NULL");
2711 return new CCodeIdentifier (unref_function);
2712 } else if (type.type_parameter != null && current_type_symbol is Class) {
2713 string func_name = "%s_destroy_func".printf (type.type_parameter.name.down ());
2714 if (is_in_generic_type (type) && !is_chainup && !in_creation_method) {
2715 return new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (get_result_cexpression ("self"), "priv"), func_name);
2716 } else {
2717 return new CCodeIdentifier (func_name);
2719 } else if (type is ArrayType) {
2720 if (context.profile == Profile.POSIX) {
2721 return new CCodeIdentifier ("free");
2722 } else {
2723 return new CCodeIdentifier ("g_free");
2725 } else if (type is PointerType) {
2726 if (context.profile == Profile.POSIX) {
2727 return new CCodeIdentifier ("free");
2728 } else {
2729 return new CCodeIdentifier ("g_free");
2731 } else {
2732 return new CCodeConstant ("NULL");
2736 private string generate_collection_free_wrapper (DataType collection_type, CCodeIdentifier element_destroy_func_expression) {
2737 string destroy_func = "_%s_%s".printf (collection_type.data_type.get_free_function (), element_destroy_func_expression.name);
2739 if (!add_wrapper (destroy_func)) {
2740 // wrapper already defined
2741 return destroy_func;
2744 var function = new CCodeFunction (destroy_func, "void");
2745 function.modifiers = CCodeModifiers.STATIC;
2747 function.add_parameter (new CCodeParameter ("self", collection_type.get_cname ()));
2749 push_function (function);
2751 CCodeFunctionCall element_free_call;
2752 if (collection_type.data_type == gnode_type) {
2753 /* A wrapper which converts GNodeTraverseFunc into GDestroyNotify */
2754 string destroy_node_func = "%s_node".printf (destroy_func);
2755 var wrapper = new CCodeFunction (destroy_node_func, "gboolean");
2756 wrapper.modifiers = CCodeModifiers.STATIC;
2757 wrapper.add_parameter (new CCodeParameter ("node", collection_type.get_cname ()));
2758 wrapper.add_parameter (new CCodeParameter ("unused", "gpointer"));
2759 var wrapper_block = new CCodeBlock ();
2760 var free_call = new CCodeFunctionCall (element_destroy_func_expression);
2761 free_call.add_argument (new CCodeMemberAccess.pointer(new CCodeIdentifier("node"), "data"));
2762 wrapper_block.add_statement (new CCodeExpressionStatement (free_call));
2763 wrapper_block.add_statement (new CCodeReturnStatement (new CCodeConstant ("FALSE")));
2764 cfile.add_function_declaration (function);
2765 wrapper.block = wrapper_block;
2766 cfile.add_function (wrapper);
2768 /* Now the code to call g_traverse with the above */
2769 element_free_call = new CCodeFunctionCall (new CCodeIdentifier ("g_node_traverse"));
2770 element_free_call.add_argument (new CCodeIdentifier("self"));
2771 element_free_call.add_argument (new CCodeConstant ("G_POST_ORDER"));
2772 element_free_call.add_argument (new CCodeConstant ("G_TRAVERSE_ALL"));
2773 element_free_call.add_argument (new CCodeConstant ("-1"));
2774 element_free_call.add_argument (new CCodeIdentifier (destroy_node_func));
2775 element_free_call.add_argument (new CCodeConstant ("NULL"));
2776 } else {
2777 if (collection_type.data_type == glist_type) {
2778 element_free_call = new CCodeFunctionCall (new CCodeIdentifier ("g_list_foreach"));
2779 } else {
2780 element_free_call = new CCodeFunctionCall (new CCodeIdentifier ("g_slist_foreach"));
2783 element_free_call.add_argument (new CCodeIdentifier ("self"));
2784 element_free_call.add_argument (new CCodeCastExpression (element_destroy_func_expression, "GFunc"));
2785 element_free_call.add_argument (new CCodeConstant ("NULL"));
2788 ccode.add_expression (element_free_call);
2790 var cfreecall = new CCodeFunctionCall (new CCodeIdentifier (collection_type.data_type.get_free_function ()));
2791 cfreecall.add_argument (new CCodeIdentifier ("self"));
2792 ccode.add_expression (cfreecall);
2794 pop_function ();
2796 cfile.add_function_declaration (function);
2797 cfile.add_function (function);
2799 return destroy_func;
2802 public virtual string? append_struct_array_free (Struct st) {
2803 return null;
2806 // logic in this method is temporarily duplicated in destroy_value
2807 // apply changes to both methods
2808 public virtual CCodeExpression destroy_variable (Variable variable, TargetValue target_lvalue) {
2809 var type = target_lvalue.value_type;
2810 var cvar = get_cvalue_ (target_lvalue);
2812 if (type is DelegateType) {
2813 var delegate_target = get_delegate_target_cvalue (target_lvalue);
2814 var delegate_target_destroy_notify = get_delegate_target_destroy_notify_cvalue (target_lvalue);
2816 var ccall = new CCodeFunctionCall (delegate_target_destroy_notify);
2817 ccall.add_argument (delegate_target);
2819 var destroy_call = new CCodeCommaExpression ();
2820 destroy_call.append_expression (ccall);
2821 destroy_call.append_expression (new CCodeConstant ("NULL"));
2823 var cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, delegate_target_destroy_notify, new CCodeConstant ("NULL"));
2825 var ccomma = new CCodeCommaExpression ();
2826 ccomma.append_expression (new CCodeConditionalExpression (cisnull, new CCodeConstant ("NULL"), destroy_call));
2827 ccomma.append_expression (new CCodeAssignment (cvar, new CCodeConstant ("NULL")));
2828 ccomma.append_expression (new CCodeAssignment (delegate_target, new CCodeConstant ("NULL")));
2829 ccomma.append_expression (new CCodeAssignment (delegate_target_destroy_notify, new CCodeConstant ("NULL")));
2831 return ccomma;
2834 var ccall = new CCodeFunctionCall (get_destroy_func_expression (type));
2836 if (type is ValueType && !type.nullable) {
2837 // normal value type, no null check
2838 var st = type.data_type as Struct;
2839 if (st != null && st.is_simple_type ()) {
2840 // used for va_list
2841 ccall.add_argument (cvar);
2842 } else {
2843 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cvar));
2846 if (gvalue_type != null && type.data_type == gvalue_type) {
2847 // g_value_unset must not be called for already unset values
2848 var cisvalid = new CCodeFunctionCall (new CCodeIdentifier ("G_IS_VALUE"));
2849 cisvalid.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cvar));
2851 var ccomma = new CCodeCommaExpression ();
2852 ccomma.append_expression (ccall);
2853 ccomma.append_expression (new CCodeConstant ("NULL"));
2855 return new CCodeConditionalExpression (cisvalid, ccomma, new CCodeConstant ("NULL"));
2856 } else {
2857 return ccall;
2861 if (ccall.call is CCodeIdentifier && !(type is ArrayType)) {
2862 // generate and use NULL-aware free macro to simplify code
2864 var freeid = (CCodeIdentifier) ccall.call;
2865 string free0_func = "_%s0".printf (freeid.name);
2867 if (add_wrapper (free0_func)) {
2868 var macro = destroy_value (new GLibValue (type, new CCodeIdentifier ("var")), true);
2869 cfile.add_type_declaration (new CCodeMacroReplacement.with_expression ("%s(var)".printf (free0_func), macro));
2872 ccall = new CCodeFunctionCall (new CCodeIdentifier (free0_func));
2873 ccall.add_argument (cvar);
2874 return ccall;
2877 /* (foo == NULL ? NULL : foo = (unref (foo), NULL)) */
2879 /* can be simplified to
2880 * foo = (unref (foo), NULL)
2881 * if foo is of static type non-null
2884 var cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, cvar, new CCodeConstant ("NULL"));
2885 if (type.type_parameter != null) {
2886 if (!(current_type_symbol is Class) || current_class.is_compact) {
2887 return new CCodeConstant ("NULL");
2890 // unref functions are optional for type parameters
2891 var cunrefisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, get_destroy_func_expression (type), new CCodeConstant ("NULL"));
2892 cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.OR, cisnull, cunrefisnull);
2895 ccall.add_argument (cvar);
2897 /* set freed references to NULL to prevent further use */
2898 var ccomma = new CCodeCommaExpression ();
2900 if (context.profile == Profile.GOBJECT) {
2901 if (type.data_type != null && !type.data_type.is_reference_counting () &&
2902 (type.data_type == gstringbuilder_type
2903 || type.data_type == garray_type
2904 || type.data_type == gbytearray_type
2905 || type.data_type == gptrarray_type)) {
2906 ccall.add_argument (new CCodeConstant ("TRUE"));
2907 } else if (type.data_type == gthreadpool_type) {
2908 ccall.add_argument (new CCodeConstant ("FALSE"));
2909 ccall.add_argument (new CCodeConstant ("TRUE"));
2910 } else if (type is ArrayType) {
2911 var array_type = (ArrayType) type;
2912 if (requires_destroy (array_type.element_type)) {
2913 CCodeExpression csizeexpr = null;
2914 if (variable.array_null_terminated) {
2915 var len_call = new CCodeFunctionCall (new CCodeIdentifier ("_vala_array_length"));
2916 len_call.add_argument (cvar);
2917 csizeexpr = len_call;
2918 } else if (variable.has_array_length_cexpr) {
2919 csizeexpr = new CCodeConstant (variable.get_array_length_cexpr ());
2920 } else if (!variable.no_array_length) {
2921 bool first = true;
2922 for (int dim = 1; dim <= array_type.rank; dim++) {
2923 if (first) {
2924 csizeexpr = get_array_length_cvalue (target_lvalue, dim);
2925 first = false;
2926 } else {
2927 csizeexpr = new CCodeBinaryExpression (CCodeBinaryOperator.MUL, csizeexpr, get_array_length_cvalue (target_lvalue, dim));
2932 if (csizeexpr != null) {
2933 var st = array_type.element_type.data_type as Struct;
2934 if (st != null && !array_type.element_type.nullable) {
2935 ccall.call = new CCodeIdentifier (append_struct_array_free (st));
2936 ccall.add_argument (csizeexpr);
2937 } else {
2938 requires_array_free = true;
2939 ccall.call = new CCodeIdentifier ("_vala_array_free");
2940 ccall.add_argument (csizeexpr);
2941 ccall.add_argument (new CCodeCastExpression (get_destroy_func_expression (array_type.element_type), "GDestroyNotify"));
2948 ccomma.append_expression (ccall);
2949 ccomma.append_expression (new CCodeConstant ("NULL"));
2951 var cassign = new CCodeAssignment (cvar, ccomma);
2953 // g_free (NULL) is allowed
2954 bool uses_gfree = (type.data_type != null && !type.data_type.is_reference_counting () && type.data_type.get_free_function () == "g_free");
2955 uses_gfree = uses_gfree || type is ArrayType;
2956 if (uses_gfree) {
2957 return cassign;
2960 return new CCodeConditionalExpression (cisnull, new CCodeConstant ("NULL"), cassign);
2963 public CCodeExpression destroy_local (LocalVariable local) {
2964 return destroy_variable (local, get_local_cvalue (local));
2967 public CCodeExpression destroy_parameter (Parameter param) {
2968 return destroy_variable (param, get_parameter_cvalue (param));
2971 public CCodeExpression destroy_field (Field field, TargetValue? instance) {
2972 return destroy_variable (field, get_field_cvalue (field, instance));
2975 public CCodeExpression get_unref_expression (CCodeExpression cvar, DataType type, Expression? expr, bool is_macro_definition = false) {
2976 if (expr != null) {
2977 if (expr.symbol_reference is LocalVariable) {
2978 return destroy_local ((LocalVariable) expr.symbol_reference);
2979 } else if (expr.symbol_reference is Parameter) {
2980 return destroy_parameter ((Parameter) expr.symbol_reference);
2983 var value = new GLibValue (type, cvar);
2984 if (expr != null && expr.target_value != null) {
2985 value.array_length_cvalues = ((GLibValue) expr.target_value).array_length_cvalues;
2986 value.delegate_target_cvalue = get_delegate_target_cvalue (expr.target_value);
2987 value.delegate_target_destroy_notify_cvalue = get_delegate_target_destroy_notify_cvalue (expr.target_value);
2989 return destroy_value (value, is_macro_definition);
2992 // logic in this method is temporarily duplicated in destroy_variable
2993 // apply changes to both methods
2994 public virtual CCodeExpression destroy_value (TargetValue value, bool is_macro_definition = false) {
2995 var type = value.value_type;
2996 var cvar = get_cvalue_ (value);
2998 if (type is DelegateType) {
2999 var delegate_target = get_delegate_target_cvalue (value);
3000 var delegate_target_destroy_notify = get_delegate_target_destroy_notify_cvalue (value);
3002 var ccall = new CCodeFunctionCall (delegate_target_destroy_notify);
3003 ccall.add_argument (delegate_target);
3005 var destroy_call = new CCodeCommaExpression ();
3006 destroy_call.append_expression (ccall);
3007 destroy_call.append_expression (new CCodeConstant ("NULL"));
3009 var cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, delegate_target_destroy_notify, new CCodeConstant ("NULL"));
3011 var ccomma = new CCodeCommaExpression ();
3012 ccomma.append_expression (new CCodeConditionalExpression (cisnull, new CCodeConstant ("NULL"), destroy_call));
3013 ccomma.append_expression (new CCodeAssignment (cvar, new CCodeConstant ("NULL")));
3014 ccomma.append_expression (new CCodeAssignment (delegate_target, new CCodeConstant ("NULL")));
3015 ccomma.append_expression (new CCodeAssignment (delegate_target_destroy_notify, new CCodeConstant ("NULL")));
3017 return ccomma;
3020 var ccall = new CCodeFunctionCall (get_destroy_func_expression (type));
3022 if (type is ValueType && !type.nullable) {
3023 // normal value type, no null check
3024 var st = type.data_type as Struct;
3025 if (st != null && st.is_simple_type ()) {
3026 // used for va_list
3027 ccall.add_argument (cvar);
3028 } else {
3029 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cvar));
3032 if (gvalue_type != null && type.data_type == gvalue_type) {
3033 // g_value_unset must not be called for already unset values
3034 var cisvalid = new CCodeFunctionCall (new CCodeIdentifier ("G_IS_VALUE"));
3035 cisvalid.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cvar));
3037 var ccomma = new CCodeCommaExpression ();
3038 ccomma.append_expression (ccall);
3039 ccomma.append_expression (new CCodeConstant ("NULL"));
3041 return new CCodeConditionalExpression (cisvalid, ccomma, new CCodeConstant ("NULL"));
3042 } else {
3043 return ccall;
3047 if (ccall.call is CCodeIdentifier && !(type is ArrayType) && !is_macro_definition) {
3048 // generate and use NULL-aware free macro to simplify code
3050 var freeid = (CCodeIdentifier) ccall.call;
3051 string free0_func = "_%s0".printf (freeid.name);
3053 if (add_wrapper (free0_func)) {
3054 var macro = destroy_value (new GLibValue (type, new CCodeIdentifier ("var")), true);
3055 cfile.add_type_declaration (new CCodeMacroReplacement.with_expression ("%s(var)".printf (free0_func), macro));
3058 ccall = new CCodeFunctionCall (new CCodeIdentifier (free0_func));
3059 ccall.add_argument (cvar);
3060 return ccall;
3063 /* (foo == NULL ? NULL : foo = (unref (foo), NULL)) */
3065 /* can be simplified to
3066 * foo = (unref (foo), NULL)
3067 * if foo is of static type non-null
3070 var cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, cvar, new CCodeConstant ("NULL"));
3071 if (type.type_parameter != null) {
3072 if (!(current_type_symbol is Class) || current_class.is_compact) {
3073 return new CCodeConstant ("NULL");
3076 // unref functions are optional for type parameters
3077 var cunrefisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, get_destroy_func_expression (type), new CCodeConstant ("NULL"));
3078 cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.OR, cisnull, cunrefisnull);
3081 ccall.add_argument (cvar);
3083 /* set freed references to NULL to prevent further use */
3084 var ccomma = new CCodeCommaExpression ();
3086 if (context.profile == Profile.GOBJECT) {
3087 if (type.data_type != null && !type.data_type.is_reference_counting () &&
3088 (type.data_type == gstringbuilder_type
3089 || type.data_type == garray_type
3090 || type.data_type == gbytearray_type
3091 || type.data_type == gptrarray_type)) {
3092 ccall.add_argument (new CCodeConstant ("TRUE"));
3093 } else if (type.data_type == gthreadpool_type) {
3094 ccall.add_argument (new CCodeConstant ("FALSE"));
3095 ccall.add_argument (new CCodeConstant ("TRUE"));
3096 } else if (type is ArrayType) {
3097 var array_type = (ArrayType) type;
3098 if (requires_destroy (array_type.element_type)) {
3099 CCodeExpression csizeexpr = null;
3100 bool first = true;
3101 for (int dim = 1; dim <= array_type.rank; dim++) {
3102 if (first) {
3103 csizeexpr = get_array_length_cvalue (value, dim);
3104 first = false;
3105 } else {
3106 csizeexpr = new CCodeBinaryExpression (CCodeBinaryOperator.MUL, csizeexpr, get_array_length_cvalue (value, dim));
3110 var st = array_type.element_type.data_type as Struct;
3111 if (st != null && !array_type.element_type.nullable) {
3112 ccall.call = new CCodeIdentifier (append_struct_array_free (st));
3113 ccall.add_argument (csizeexpr);
3114 } else {
3115 requires_array_free = true;
3116 ccall.call = new CCodeIdentifier ("_vala_array_free");
3117 ccall.add_argument (csizeexpr);
3118 ccall.add_argument (new CCodeCastExpression (get_destroy_func_expression (array_type.element_type), "GDestroyNotify"));
3124 ccomma.append_expression (ccall);
3125 ccomma.append_expression (new CCodeConstant ("NULL"));
3127 var cassign = new CCodeAssignment (cvar, ccomma);
3129 // g_free (NULL) is allowed
3130 bool uses_gfree = (type.data_type != null && !type.data_type.is_reference_counting () && type.data_type.get_free_function () == "g_free");
3131 uses_gfree = uses_gfree || type is ArrayType;
3132 if (uses_gfree) {
3133 return cassign;
3136 return new CCodeConditionalExpression (cisnull, new CCodeConstant ("NULL"), cassign);
3139 public override void visit_end_full_expression (Expression expr) {
3140 /* expr is a full expression, i.e. an initializer, the
3141 * expression in an expression statement, the controlling
3142 * expression in if, while, for, or foreach statements
3144 * we unref temporary variables at the end of a full
3145 * expression
3147 if (temp_ref_vars.size == 0) {
3148 /* nothing to do without temporary variables */
3149 return;
3152 LocalVariable full_expr_var = null;
3154 var local_decl = expr.parent_node as LocalVariable;
3155 if (!(local_decl != null && has_simple_struct_initializer (local_decl))) {
3156 var expr_type = expr.value_type;
3157 if (expr.target_type != null) {
3158 expr_type = expr.target_type;
3161 full_expr_var = get_temp_variable (expr_type, true, expr, false);
3162 emit_temp_var (full_expr_var);
3164 ccode.add_assignment (get_variable_cexpression (full_expr_var.name), get_cvalue (expr));
3167 foreach (LocalVariable local in temp_ref_vars) {
3168 ccode.add_expression (destroy_local (local));
3171 if (full_expr_var != null) {
3172 set_cvalue (expr, get_variable_cexpression (full_expr_var.name));
3175 temp_ref_vars.clear ();
3178 public void emit_temp_var (LocalVariable local, bool always_init = false) {
3179 var vardecl = new CCodeVariableDeclarator (local.name, null, local.variable_type.get_cdeclarator_suffix ());
3181 var st = local.variable_type.data_type as Struct;
3182 var array_type = local.variable_type as ArrayType;
3184 if (local.name.has_prefix ("*")) {
3185 // do not dereference unintialized variable
3186 // initialization is not needed for these special
3187 // pointer temp variables
3188 // used to avoid side-effects in assignments
3189 } else if (local.no_init) {
3190 // no initialization necessary for this temp var
3191 } else if (!local.variable_type.nullable &&
3192 (st != null && !st.is_simple_type ()) ||
3193 (array_type != null && array_type.fixed_length)) {
3194 // 0-initialize struct with struct initializer { 0 }
3195 // necessary as they will be passed by reference
3196 var clist = new CCodeInitializerList ();
3197 clist.append (new CCodeConstant ("0"));
3199 vardecl.initializer = clist;
3200 vardecl.init0 = true;
3201 } else if (local.variable_type.is_reference_type_or_type_parameter () ||
3202 local.variable_type.nullable ||
3203 local.variable_type is DelegateType) {
3204 vardecl.initializer = new CCodeConstant ("NULL");
3205 vardecl.init0 = true;
3206 } else if (always_init) {
3207 vardecl.initializer = default_value_for_type (local.variable_type, true);
3208 vardecl.init0 = true;
3211 if (is_in_coroutine ()) {
3212 closure_struct.add_field (local.variable_type.get_cname (), local.name);
3214 // even though closure struct is zerod, we need to initialize temporary variables
3215 // as they might be used multiple times when declared in a loop
3217 if (vardecl.initializer is CCodeInitializerList) {
3218 // C does not support initializer lists in assignments, use memset instead
3219 cfile.add_include ("string.h");
3220 var memset_call = new CCodeFunctionCall (new CCodeIdentifier ("memset"));
3221 memset_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression (local.name)));
3222 memset_call.add_argument (new CCodeConstant ("0"));
3223 memset_call.add_argument (new CCodeIdentifier ("sizeof (%s)".printf (local.variable_type.get_cname ())));
3224 ccode.add_expression (memset_call);
3225 } else if (vardecl.initializer != null) {
3226 ccode.add_assignment (get_variable_cexpression (local.name), vardecl.initializer);
3228 } else {
3229 ccode.add_declaration (local.variable_type.get_cname (), vardecl);
3233 public override void visit_expression_statement (ExpressionStatement stmt) {
3234 if (stmt.expression.error) {
3235 stmt.error = true;
3236 return;
3239 /* free temporary objects and handle errors */
3241 foreach (LocalVariable local in temp_ref_vars) {
3242 ccode.add_expression (destroy_local (local));
3245 if (stmt.tree_can_fail && stmt.expression.tree_can_fail) {
3246 // simple case, no node breakdown necessary
3247 add_simple_check (stmt.expression);
3250 temp_ref_vars.clear ();
3253 public virtual void append_local_free (Symbol sym, bool stop_at_loop = false, CodeNode? stop_at = null) {
3254 var b = (Block) sym;
3256 var local_vars = b.get_local_variables ();
3257 // free in reverse order
3258 for (int i = local_vars.size - 1; i >= 0; i--) {
3259 var local = local_vars[i];
3260 if (!local.unreachable && local.active && !local.floating && !local.captured && requires_destroy (local.variable_type)) {
3261 ccode.add_expression (destroy_local (local));
3265 if (b.captured) {
3266 int block_id = get_block_id (b);
3268 var data_unref = new CCodeFunctionCall (new CCodeIdentifier ("block%d_data_unref".printf (block_id)));
3269 data_unref.add_argument (get_variable_cexpression ("_data%d_".printf (block_id)));
3270 ccode.add_expression (data_unref);
3271 ccode.add_assignment (get_variable_cexpression ("_data%d_".printf (block_id)), new CCodeConstant ("NULL"));
3274 if (stop_at_loop) {
3275 if (b.parent_node is Loop ||
3276 b.parent_node is ForeachStatement ||
3277 b.parent_node is SwitchStatement) {
3278 return;
3282 if (stop_at != null && b.parent_node == stop_at) {
3283 return;
3286 if (sym.parent_symbol is Block) {
3287 append_local_free (sym.parent_symbol, stop_at_loop, stop_at);
3288 } else if (sym.parent_symbol is Method) {
3289 append_param_free ((Method) sym.parent_symbol);
3293 private void append_param_free (Method m) {
3294 foreach (Parameter param in m.get_parameters ()) {
3295 if (!param.ellipsis && requires_destroy (param.variable_type) && param.direction == ParameterDirection.IN) {
3296 ccode.add_expression (destroy_parameter (param));
3301 public bool variable_accessible_in_finally (LocalVariable local) {
3302 if (current_try == null) {
3303 return false;
3306 var sym = current_symbol;
3308 while (!(sym is Method || sym is PropertyAccessor) && sym.scope.lookup (local.name) == null) {
3309 if ((sym.parent_node is TryStatement && ((TryStatement) sym.parent_node).finally_body != null) ||
3310 (sym.parent_node is CatchClause && ((TryStatement) sym.parent_node.parent_node).finally_body != null)) {
3312 return true;
3315 sym = sym.parent_symbol;
3318 return false;
3321 void return_out_parameter (Parameter param) {
3322 var delegate_type = param.variable_type as DelegateType;
3324 ccode.open_if (get_variable_cexpression (param.name));
3325 ccode.add_assignment (new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, get_variable_cexpression (param.name)), get_variable_cexpression ("_" + param.name));
3327 if (delegate_type != null && delegate_type.delegate_symbol.has_target) {
3328 ccode.add_assignment (new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, get_variable_cexpression (get_delegate_target_cname (param.name))), new CCodeIdentifier (get_delegate_target_cname (get_variable_cname ("_" + param.name))));
3329 if (delegate_type.value_owned) {
3330 ccode.add_assignment (new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, get_variable_cexpression (get_delegate_target_destroy_notify_cname (param.name))), new CCodeIdentifier (get_delegate_target_destroy_notify_cname (get_variable_cname ("_" + param.name))));
3334 if (param.variable_type.is_disposable ()){
3335 ccode.add_else ();
3336 ccode.add_expression (destroy_parameter (param));
3338 ccode.close ();
3340 var array_type = param.variable_type as ArrayType;
3341 if (array_type != null && !array_type.fixed_length && !param.no_array_length) {
3342 for (int dim = 1; dim <= array_type.rank; dim++) {
3343 ccode.open_if (get_variable_cexpression (get_parameter_array_length_cname (param, dim)));
3344 ccode.add_assignment (new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, get_variable_cexpression (get_parameter_array_length_cname (param, dim))), new CCodeIdentifier (get_array_length_cname (get_variable_cname ("_" + param.name), dim)));
3345 ccode.close ();
3350 public override void visit_return_statement (ReturnStatement stmt) {
3351 Symbol return_expression_symbol = null;
3353 if (stmt.return_expression != null) {
3354 // avoid unnecessary ref/unref pair
3355 var local = stmt.return_expression.symbol_reference as LocalVariable;
3356 if (current_return_type.value_owned
3357 && local != null && local.variable_type.value_owned
3358 && !local.captured
3359 && !variable_accessible_in_finally (local)) {
3360 /* return expression is local variable taking ownership and
3361 * current method is transferring ownership */
3363 return_expression_symbol = local;
3367 // return array length if appropriate
3368 if (((current_method != null && !current_method.no_array_length) || current_property_accessor != null) && current_return_type is ArrayType) {
3369 var return_expr_decl = get_temp_variable (stmt.return_expression.value_type, true, stmt, false);
3371 ccode.add_assignment (get_variable_cexpression (return_expr_decl.name), get_cvalue (stmt.return_expression));
3373 var array_type = (ArrayType) current_return_type;
3375 for (int dim = 1; dim <= array_type.rank; dim++) {
3376 var len_l = get_result_cexpression (get_array_length_cname ("result", dim));
3377 if (!is_in_coroutine ()) {
3378 len_l = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, len_l);
3380 var len_r = get_array_length_cexpression (stmt.return_expression, dim);
3381 ccode.add_assignment (len_l, len_r);
3384 set_cvalue (stmt.return_expression, get_variable_cexpression (return_expr_decl.name));
3386 emit_temp_var (return_expr_decl);
3387 } else if ((current_method != null || current_property_accessor != null) && current_return_type is DelegateType) {
3388 var delegate_type = (DelegateType) current_return_type;
3389 if (delegate_type.delegate_symbol.has_target) {
3390 var return_expr_decl = get_temp_variable (stmt.return_expression.value_type, true, stmt, false);
3392 ccode.add_assignment (get_variable_cexpression (return_expr_decl.name), get_cvalue (stmt.return_expression));
3394 var target_l = get_result_cexpression (get_delegate_target_cname ("result"));
3395 if (!is_in_coroutine ()) {
3396 target_l = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, target_l);
3398 CCodeExpression target_r_destroy_notify;
3399 var target_r = get_delegate_target_cexpression (stmt.return_expression, out target_r_destroy_notify);
3400 ccode.add_assignment (target_l, target_r);
3401 if (delegate_type.value_owned) {
3402 var target_l_destroy_notify = get_result_cexpression (get_delegate_target_destroy_notify_cname ("result"));
3403 if (!is_in_coroutine ()) {
3404 target_l_destroy_notify = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, target_l_destroy_notify);
3406 ccode.add_assignment (target_l_destroy_notify, target_r_destroy_notify);
3409 set_cvalue (stmt.return_expression, get_variable_cexpression (return_expr_decl.name));
3411 emit_temp_var (return_expr_decl);
3415 if (stmt.return_expression != null) {
3416 // assign method result to `result'
3417 CCodeExpression result_lhs = get_result_cexpression ();
3418 if (current_return_type.is_real_non_null_struct_type () && !is_in_coroutine ()) {
3419 result_lhs = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, result_lhs);
3421 ccode.add_assignment (result_lhs, get_cvalue (stmt.return_expression));
3424 // free local variables
3425 append_local_free (current_symbol);
3427 if (current_method != null) {
3428 // check postconditions
3429 foreach (Expression postcondition in current_method.get_postconditions ()) {
3430 create_postcondition_statement (postcondition);
3434 if (current_method != null && !current_method.coroutine) {
3435 // assign values to output parameters if they are not NULL
3436 // otherwise, free the value if necessary
3437 foreach (var param in current_method.get_parameters ()) {
3438 if (param.direction != ParameterDirection.OUT) {
3439 continue;
3442 return_out_parameter (param);
3446 if (is_in_constructor ()) {
3447 ccode.add_return (new CCodeIdentifier ("obj"));
3448 } else if (is_in_destructor ()) {
3449 // do not call return as member cleanup and chain up to base finalizer
3450 // stil need to be executed
3451 ccode.add_goto ("_return");
3452 } else if (current_method is CreationMethod) {
3453 ccode.add_return (new CCodeIdentifier ("self"));
3454 } else if (is_in_coroutine ()) {
3455 } else if (current_return_type is VoidType || current_return_type.is_real_non_null_struct_type ()) {
3456 // structs are returned via out parameter
3457 ccode.add_return ();
3458 } else {
3459 ccode.add_return (new CCodeIdentifier ("result"));
3462 if (return_expression_symbol != null) {
3463 return_expression_symbol.active = true;
3466 // required for destructors
3467 current_method_return = true;
3470 public string get_symbol_lock_name (string symname) {
3471 return "__lock_%s".printf (symname);
3474 private CCodeExpression get_lock_expression (Statement stmt, Expression resource) {
3475 CCodeExpression l = null;
3476 var inner_node = ((MemberAccess)resource).inner;
3477 var member = resource.symbol_reference;
3478 var parent = (TypeSymbol)resource.symbol_reference.parent_symbol;
3480 if (member.is_instance_member ()) {
3481 if (inner_node == null) {
3482 l = new CCodeIdentifier ("self");
3483 } else if (resource.symbol_reference.parent_symbol != current_type_symbol) {
3484 l = generate_instance_cast (get_cvalue (inner_node), parent);
3485 } else {
3486 l = get_cvalue (inner_node);
3489 l = new CCodeMemberAccess.pointer (new CCodeMemberAccess.pointer (l, "priv"), get_symbol_lock_name (resource.symbol_reference.name));
3490 } else if (member.is_class_member ()) {
3491 CCodeExpression klass;
3493 if (current_method != null && current_method.binding == MemberBinding.INSTANCE ||
3494 current_property_accessor != null && current_property_accessor.prop.binding == MemberBinding.INSTANCE ||
3495 (in_constructor && !in_static_or_class_context)) {
3496 var k = new CCodeFunctionCall (new CCodeIdentifier ("G_OBJECT_GET_CLASS"));
3497 k.add_argument (new CCodeIdentifier ("self"));
3498 klass = k;
3499 } else {
3500 klass = new CCodeIdentifier ("klass");
3503 var get_class_private_call = new CCodeFunctionCall (new CCodeIdentifier ("%s_GET_CLASS_PRIVATE".printf(parent.get_upper_case_cname ())));
3504 get_class_private_call.add_argument (klass);
3505 l = new CCodeMemberAccess.pointer (get_class_private_call, get_symbol_lock_name (resource.symbol_reference.name));
3506 } else {
3507 string lock_name = "%s_%s".printf(parent.get_lower_case_cname (), resource.symbol_reference.name);
3508 l = new CCodeIdentifier (get_symbol_lock_name (lock_name));
3510 return l;
3513 public override void visit_lock_statement (LockStatement stmt) {
3514 var l = get_lock_expression (stmt, stmt.resource);
3516 var fc = new CCodeFunctionCall (new CCodeIdentifier (((Method) mutex_type.scope.lookup ("lock")).get_cname ()));
3517 fc.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));
3519 ccode.add_expression (fc);
3522 public override void visit_unlock_statement (UnlockStatement stmt) {
3523 var l = get_lock_expression (stmt, stmt.resource);
3525 var fc = new CCodeFunctionCall (new CCodeIdentifier (((Method) mutex_type.scope.lookup ("unlock")).get_cname ()));
3526 fc.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, l));
3528 ccode.add_expression (fc);
3531 public override void visit_delete_statement (DeleteStatement stmt) {
3532 var pointer_type = (PointerType) stmt.expression.value_type;
3533 DataType type = pointer_type;
3534 if (pointer_type.base_type.data_type != null && pointer_type.base_type.data_type.is_reference_type ()) {
3535 type = pointer_type.base_type;
3538 var ccall = new CCodeFunctionCall (get_destroy_func_expression (type));
3539 ccall.add_argument (get_cvalue (stmt.expression));
3540 ccode.add_expression (ccall);
3543 public override void visit_expression (Expression expr) {
3544 if (get_cvalue (expr) != null && !expr.lvalue) {
3545 if (expr.formal_value_type is GenericType && !(expr.value_type is GenericType)) {
3546 var st = expr.formal_value_type.type_parameter.parent_symbol.parent_symbol as Struct;
3547 if (expr.formal_value_type.type_parameter.parent_symbol != garray_type &&
3548 (st == null || st.get_cname () != "va_list")) {
3549 // GArray and va_list don't use pointer-based generics
3550 set_cvalue (expr, convert_from_generic_pointer (get_cvalue (expr), expr.value_type));
3554 // memory management, implicit casts, and boxing/unboxing
3555 set_cvalue (expr, transform_expression (get_cvalue (expr), expr.value_type, expr.target_type, expr));
3557 if (expr.formal_target_type is GenericType && !(expr.target_type is GenericType)) {
3558 if (expr.formal_target_type.type_parameter.parent_symbol != garray_type) {
3559 // GArray doesn't use pointer-based generics
3560 set_cvalue (expr, convert_to_generic_pointer (get_cvalue (expr), expr.target_type));
3566 public override void visit_boolean_literal (BooleanLiteral expr) {
3567 if (context.profile == Profile.GOBJECT) {
3568 set_cvalue (expr, new CCodeConstant (expr.value ? "TRUE" : "FALSE"));
3569 } else {
3570 cfile.add_include ("stdbool.h");
3571 set_cvalue (expr, new CCodeConstant (expr.value ? "true" : "false"));
3575 public override void visit_character_literal (CharacterLiteral expr) {
3576 if (expr.get_char () >= 0x20 && expr.get_char () < 0x80) {
3577 set_cvalue (expr, new CCodeConstant (expr.value));
3578 } else {
3579 set_cvalue (expr, new CCodeConstant ("%uU".printf (expr.get_char ())));
3583 public override void visit_integer_literal (IntegerLiteral expr) {
3584 set_cvalue (expr, new CCodeConstant (expr.value + expr.type_suffix));
3587 public override void visit_real_literal (RealLiteral expr) {
3588 string c_literal = expr.value;
3589 if (c_literal.has_suffix ("d") || c_literal.has_suffix ("D")) {
3590 // there is no suffix for double in C
3591 c_literal = c_literal.substring (0, c_literal.length - 1);
3593 if (!("." in c_literal || "e" in c_literal || "E" in c_literal)) {
3594 // C requires period or exponent part for floating constants
3595 if ("f" in c_literal || "F" in c_literal) {
3596 c_literal = c_literal.substring (0, c_literal.length - 1) + ".f";
3597 } else {
3598 c_literal += ".";
3601 set_cvalue (expr, new CCodeConstant (c_literal));
3604 public override void visit_string_literal (StringLiteral expr) {
3605 set_cvalue (expr, new CCodeConstant.string (expr.value.replace ("\n", "\\n")));
3607 if (expr.translate) {
3608 // translated string constant
3610 var m = (Method) root_symbol.scope.lookup ("GLib").scope.lookup ("_");
3611 add_symbol_declaration (cfile, m, m.get_cname ());
3613 var translate = new CCodeFunctionCall (new CCodeIdentifier ("_"));
3614 translate.add_argument (get_cvalue (expr));
3615 set_cvalue (expr, translate);
3619 public override void visit_regex_literal (RegexLiteral expr) {
3620 string[] parts = expr.value.split ("/", 3);
3621 string re = parts[2].escape ("");
3622 string flags = "0";
3624 if (parts[1].contains ("i")) {
3625 flags += " | G_REGEX_CASELESS";
3627 if (parts[1].contains ("m")) {
3628 flags += " | G_REGEX_MULTILINE";
3630 if (parts[1].contains ("s")) {
3631 flags += " | G_REGEX_DOTALL";
3633 if (parts[1].contains ("x")) {
3634 flags += " | G_REGEX_EXTENDED";
3637 var regex_var = get_temp_variable (regex_type, true, expr, false);
3638 emit_temp_var (regex_var);
3640 var cdecl = new CCodeDeclaration ("GRegex*");
3642 var cname = regex_var.name + "regex_" + next_regex_id.to_string ();
3643 if (this.next_regex_id == 0) {
3644 var fun = new CCodeFunction ("_thread_safe_regex_init", "GRegex*");
3645 fun.modifiers = CCodeModifiers.STATIC | CCodeModifiers.INLINE;
3646 fun.add_parameter (new CCodeParameter ("re", "GRegex**"));
3647 fun.add_parameter (new CCodeParameter ("pattern", "const gchar *"));
3648 fun.add_parameter (new CCodeParameter ("match_options", "GRegexMatchFlags"));
3650 push_function (fun);
3652 var once_enter_call = new CCodeFunctionCall (new CCodeIdentifier ("g_once_init_enter"));
3653 once_enter_call.add_argument (new CCodeConstant ("(volatile gsize*) re"));
3654 ccode.open_if (once_enter_call);
3656 var regex_new_call = new CCodeFunctionCall (new CCodeIdentifier ("g_regex_new"));
3657 regex_new_call.add_argument (new CCodeConstant ("pattern"));
3658 regex_new_call.add_argument (new CCodeConstant ("match_options"));
3659 regex_new_call.add_argument (new CCodeConstant ("0"));
3660 regex_new_call.add_argument (new CCodeConstant ("NULL"));
3661 ccode.add_assignment (new CCodeIdentifier ("GRegex* val"), regex_new_call);
3663 var once_leave_call = new CCodeFunctionCall (new CCodeIdentifier ("g_once_init_leave"));
3664 once_leave_call.add_argument (new CCodeConstant ("(volatile gsize*) re"));
3665 once_leave_call.add_argument (new CCodeConstant ("(gsize) val"));
3666 ccode.add_expression (once_leave_call);
3668 ccode.close ();
3670 ccode.add_return (new CCodeIdentifier ("*re"));
3672 pop_function ();
3674 cfile.add_function (fun);
3676 this.next_regex_id++;
3678 cdecl.add_declarator (new CCodeVariableDeclarator (cname + " = NULL"));
3679 cdecl.modifiers = CCodeModifiers.STATIC;
3681 var regex_const = new CCodeConstant ("_thread_safe_regex_init (&%s, \"%s\", %s)".printf (cname, re, flags));
3683 cfile.add_constant_declaration (cdecl);
3684 set_cvalue (expr, regex_const);
3687 public override void visit_null_literal (NullLiteral expr) {
3688 if (context.profile != Profile.GOBJECT) {
3689 cfile.add_include ("stddef.h");
3691 set_cvalue (expr, new CCodeConstant ("NULL"));
3693 var array_type = expr.target_type as ArrayType;
3694 var delegate_type = expr.target_type as DelegateType;
3695 if (array_type != null) {
3696 for (int dim = 1; dim <= array_type.rank; dim++) {
3697 append_array_length (expr, new CCodeConstant ("0"));
3699 } else if (delegate_type != null && delegate_type.delegate_symbol.has_target) {
3700 set_delegate_target (expr, new CCodeConstant ("NULL"));
3701 set_delegate_target_destroy_notify (expr, new CCodeConstant ("NULL"));
3705 public abstract TargetValue get_local_cvalue (LocalVariable local);
3707 public abstract TargetValue get_parameter_cvalue (Parameter param);
3709 public abstract TargetValue get_field_cvalue (Field field, TargetValue? instance);
3711 public abstract TargetValue load_this_parameter (TypeSymbol sym);
3713 public virtual string get_delegate_target_cname (string delegate_cname) {
3714 assert_not_reached ();
3717 public virtual CCodeExpression get_delegate_target_cexpression (Expression delegate_expr, out CCodeExpression delegate_target_destroy_notify) {
3718 assert_not_reached ();
3721 public virtual CCodeExpression get_delegate_target_cvalue (TargetValue value) {
3722 return new CCodeInvalidExpression ();
3725 public virtual CCodeExpression get_delegate_target_destroy_notify_cvalue (TargetValue value) {
3726 return new CCodeInvalidExpression ();
3729 public virtual string get_delegate_target_destroy_notify_cname (string delegate_cname) {
3730 assert_not_reached ();
3733 public override void visit_base_access (BaseAccess expr) {
3734 CCodeExpression this_access;
3735 if (is_in_coroutine ()) {
3736 // use closure
3737 this_access = new CCodeMemberAccess.pointer (new CCodeIdentifier ("data"), "self");
3738 } else {
3739 this_access = new CCodeIdentifier ("self");
3742 set_cvalue (expr, generate_instance_cast (this_access, expr.value_type.data_type));
3745 public override void visit_postfix_expression (PostfixExpression expr) {
3746 MemberAccess ma = find_property_access (expr.inner);
3747 if (ma != null) {
3748 // property postfix expression
3749 var prop = (Property) ma.symbol_reference;
3751 // assign current value to temp variable
3752 var temp_decl = get_temp_variable (prop.property_type, true, expr, false);
3753 emit_temp_var (temp_decl);
3754 ccode.add_assignment (get_variable_cexpression (temp_decl.name), get_cvalue (expr.inner));
3756 // increment/decrement property
3757 var op = expr.increment ? CCodeBinaryOperator.PLUS : CCodeBinaryOperator.MINUS;
3758 var cexpr = new CCodeBinaryExpression (op, get_variable_cexpression (temp_decl.name), new CCodeConstant ("1"));
3759 store_property (prop, ma.inner, new GLibValue (expr.value_type, cexpr));
3761 // return previous value
3762 set_cvalue (expr, get_variable_cexpression (temp_decl.name));
3763 return;
3766 if (expr.parent_node is ExpressionStatement) {
3767 var op = expr.increment ? CCodeUnaryOperator.POSTFIX_INCREMENT : CCodeUnaryOperator.POSTFIX_DECREMENT;
3769 ccode.add_expression (new CCodeUnaryExpression (op, get_cvalue (expr.inner)));
3770 } else {
3771 // assign current value to temp variable
3772 var temp_decl = get_temp_variable (expr.inner.value_type, true, expr, false);
3773 emit_temp_var (temp_decl);
3774 ccode.add_assignment (get_variable_cexpression (temp_decl.name), get_cvalue (expr.inner));
3776 // increment/decrement variable
3777 var op = expr.increment ? CCodeBinaryOperator.PLUS : CCodeBinaryOperator.MINUS;
3778 var cexpr = new CCodeBinaryExpression (op, get_variable_cexpression (temp_decl.name), new CCodeConstant ("1"));
3779 ccode.add_assignment (get_cvalue (expr.inner), cexpr);
3781 // return previous value
3782 set_cvalue (expr, get_variable_cexpression (temp_decl.name));
3786 private MemberAccess? find_property_access (Expression expr) {
3787 if (!(expr is MemberAccess)) {
3788 return null;
3791 var ma = (MemberAccess) expr;
3792 if (ma.symbol_reference is Property) {
3793 return ma;
3796 return null;
3799 bool is_limited_generic_type (DataType type) {
3800 var cl = type.type_parameter.parent_symbol as Class;
3801 var st = type.type_parameter.parent_symbol as Struct;
3802 if ((cl != null && cl.is_compact) || st != null) {
3803 // compact classes and structs only
3804 // have very limited generics support
3805 return true;
3807 return false;
3810 public bool requires_copy (DataType type) {
3811 if (!type.is_disposable ()) {
3812 return false;
3815 var cl = type.data_type as Class;
3816 if (cl != null && cl.is_reference_counting ()
3817 && cl.get_ref_function () == "") {
3818 // empty ref_function => no ref necessary
3819 return false;
3822 if (type.type_parameter != null) {
3823 if (is_limited_generic_type (type)) {
3824 return false;
3828 return true;
3831 public bool requires_destroy (DataType type) {
3832 if (!type.is_disposable ()) {
3833 return false;
3836 var array_type = type as ArrayType;
3837 if (array_type != null && array_type.fixed_length) {
3838 return requires_destroy (array_type.element_type);
3841 var cl = type.data_type as Class;
3842 if (cl != null && cl.is_reference_counting ()
3843 && cl.get_unref_function () == "") {
3844 // empty unref_function => no unref necessary
3845 return false;
3848 if (type.type_parameter != null) {
3849 if (is_limited_generic_type (type)) {
3850 return false;
3854 return true;
3857 bool is_ref_function_void (DataType type) {
3858 var cl = type.data_type as Class;
3859 if (cl != null && cl.ref_function_void) {
3860 return true;
3861 } else {
3862 return false;
3866 public virtual CCodeExpression? get_ref_cexpression (DataType expression_type, CCodeExpression cexpr, Expression? expr, CodeNode node) {
3867 if (expression_type is DelegateType) {
3868 return cexpr;
3871 if (expression_type is ValueType && !expression_type.nullable) {
3872 // normal value type, no null check
3874 var decl = get_temp_variable (expression_type, false, node);
3875 emit_temp_var (decl);
3876 var ctemp = get_variable_cexpression (decl.name);
3878 var vt = (ValueType) expression_type;
3879 var st = (Struct) vt.type_symbol;
3880 var copy_call = new CCodeFunctionCall (new CCodeIdentifier (st.get_copy_function ()));
3881 copy_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cexpr));
3882 copy_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, ctemp));
3884 if (!st.has_copy_function) {
3885 generate_struct_copy_function (st);
3888 if (gvalue_type != null && expression_type.data_type == gvalue_type) {
3889 var cisvalid = new CCodeFunctionCall (new CCodeIdentifier ("G_IS_VALUE"));
3890 cisvalid.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cexpr));
3892 ccode.open_if (cisvalid);
3894 // GValue requires g_value_init in addition to g_value_copy
3895 var value_type_call = new CCodeFunctionCall (new CCodeIdentifier ("G_VALUE_TYPE"));
3896 value_type_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cexpr));
3898 var init_call = new CCodeFunctionCall (new CCodeIdentifier ("g_value_init"));
3899 init_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, ctemp));
3900 init_call.add_argument (value_type_call);
3901 ccode.add_expression (init_call);
3902 ccode.add_expression (copy_call);
3904 ccode.add_else ();
3906 // g_value_init/copy must not be called for uninitialized values
3907 ccode.add_assignment (ctemp, cexpr);
3908 ccode.close ();
3909 } else {
3910 ccode.add_expression (copy_call);
3913 return ctemp;
3916 /* (temp = expr, temp == NULL ? NULL : ref (temp))
3918 * can be simplified to
3919 * ref (expr)
3920 * if static type of expr is non-null
3923 var dupexpr = get_dup_func_expression (expression_type, node.source_reference);
3925 if (dupexpr == null) {
3926 node.error = true;
3927 return null;
3930 if (dupexpr is CCodeIdentifier && !(expression_type is ArrayType) && !(expression_type is GenericType) && !is_ref_function_void (expression_type)) {
3931 // generate and call NULL-aware ref function to reduce number
3932 // of temporary variables and simplify code
3934 var dupid = (CCodeIdentifier) dupexpr;
3935 string dup0_func = "_%s0".printf (dupid.name);
3937 // g_strdup is already NULL-safe
3938 if (dupid.name == "g_strdup") {
3939 dup0_func = dupid.name;
3940 } else if (add_wrapper (dup0_func)) {
3941 string pointer_cname = "gpointer";
3942 if (context.profile == Profile.POSIX) {
3943 pointer_cname = "void*";
3945 var dup0_fun = new CCodeFunction (dup0_func, pointer_cname);
3946 dup0_fun.add_parameter (new CCodeParameter ("self", pointer_cname));
3947 dup0_fun.modifiers = CCodeModifiers.STATIC;
3949 push_function (dup0_fun);
3951 var dup_call = new CCodeFunctionCall (dupexpr);
3952 dup_call.add_argument (new CCodeIdentifier ("self"));
3954 ccode.add_return (new CCodeConditionalExpression (new CCodeIdentifier ("self"), dup_call, new CCodeConstant ("NULL")));
3956 pop_function ();
3958 cfile.add_function (dup0_fun);
3961 var ccall = new CCodeFunctionCall (new CCodeIdentifier (dup0_func));
3962 ccall.add_argument (cexpr);
3963 return ccall;
3966 var ccall = new CCodeFunctionCall (dupexpr);
3968 if (!(expression_type is ArrayType) && expr != null && expr.is_non_null ()
3969 && !is_ref_function_void (expression_type)) {
3970 // expression is non-null
3971 ccall.add_argument (get_cvalue (expr));
3973 return ccall;
3974 } else {
3975 var decl = get_temp_variable (expression_type, false, node, false);
3976 emit_temp_var (decl);
3978 var ctemp = get_variable_cexpression (decl.name);
3980 var cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, ctemp, new CCodeConstant ("NULL"));
3981 if (expression_type.type_parameter != null) {
3982 // dup functions are optional for type parameters
3983 var cdupisnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, get_dup_func_expression (expression_type, node.source_reference), new CCodeConstant ("NULL"));
3984 cisnull = new CCodeBinaryExpression (CCodeBinaryOperator.OR, cisnull, cdupisnull);
3987 if (expression_type.type_parameter != null) {
3988 // cast from gconstpointer to gpointer as GBoxedCopyFunc expects gpointer
3989 ccall.add_argument (new CCodeCastExpression (ctemp, "gpointer"));
3990 } else {
3991 ccall.add_argument (ctemp);
3994 if (expression_type is ArrayType) {
3995 var array_type = (ArrayType) expression_type;
3996 bool first = true;
3997 CCodeExpression csizeexpr = null;
3998 for (int dim = 1; dim <= array_type.rank; dim++) {
3999 if (first) {
4000 csizeexpr = get_array_length_cexpression (expr, dim);
4001 first = false;
4002 } else {
4003 csizeexpr = new CCodeBinaryExpression (CCodeBinaryOperator.MUL, csizeexpr, get_array_length_cexpression (expr, dim));
4007 ccall.add_argument (csizeexpr);
4009 if (array_type.element_type is GenericType) {
4010 var elem_dupexpr = get_dup_func_expression (array_type.element_type, node.source_reference);
4011 if (elem_dupexpr == null) {
4012 elem_dupexpr = new CCodeConstant ("NULL");
4014 ccall.add_argument (elem_dupexpr);
4018 var ccomma = new CCodeCommaExpression ();
4019 ccomma.append_expression (new CCodeAssignment (ctemp, cexpr));
4021 CCodeExpression cifnull;
4022 if (expression_type.data_type != null) {
4023 cifnull = new CCodeConstant ("NULL");
4024 } else {
4025 // the value might be non-null even when the dup function is null,
4026 // so we may not just use NULL for type parameters
4028 // cast from gconstpointer to gpointer as methods in
4029 // generic classes may not return gconstpointer
4030 cifnull = new CCodeCastExpression (ctemp, "gpointer");
4032 ccomma.append_expression (new CCodeConditionalExpression (cisnull, cifnull, ccall));
4034 // repeat temp variable at the end of the comma expression
4035 // if the ref function returns void
4036 if (is_ref_function_void (expression_type)) {
4037 ccomma.append_expression (ctemp);
4040 return ccomma;
4044 bool is_reference_type_argument (DataType type_arg) {
4045 if (type_arg is ErrorType || (type_arg.data_type != null && type_arg.data_type.is_reference_type ())) {
4046 return true;
4047 } else {
4048 return false;
4052 bool is_nullable_value_type_argument (DataType type_arg) {
4053 if (type_arg is ValueType && type_arg.nullable) {
4054 return true;
4055 } else {
4056 return false;
4060 bool is_signed_integer_type_argument (DataType type_arg) {
4061 var st = type_arg.data_type as Struct;
4062 if (type_arg.nullable) {
4063 return false;
4064 } else if (st == bool_type.data_type) {
4065 return true;
4066 } else if (st == char_type.data_type) {
4067 return true;
4068 } else if (unichar_type != null && st == unichar_type.data_type) {
4069 return true;
4070 } else if (st == short_type.data_type) {
4071 return true;
4072 } else if (st == int_type.data_type) {
4073 return true;
4074 } else if (st == long_type.data_type) {
4075 return true;
4076 } else if (st == int8_type.data_type) {
4077 return true;
4078 } else if (st == int16_type.data_type) {
4079 return true;
4080 } else if (st == int32_type.data_type) {
4081 return true;
4082 } else if (st == gtype_type) {
4083 return true;
4084 } else if (type_arg is EnumValueType) {
4085 return true;
4086 } else {
4087 return false;
4091 bool is_unsigned_integer_type_argument (DataType type_arg) {
4092 var st = type_arg.data_type as Struct;
4093 if (type_arg.nullable) {
4094 return false;
4095 } else if (st == uchar_type.data_type) {
4096 return true;
4097 } else if (st == ushort_type.data_type) {
4098 return true;
4099 } else if (st == uint_type.data_type) {
4100 return true;
4101 } else if (st == ulong_type.data_type) {
4102 return true;
4103 } else if (st == uint8_type.data_type) {
4104 return true;
4105 } else if (st == uint16_type.data_type) {
4106 return true;
4107 } else if (st == uint32_type.data_type) {
4108 return true;
4109 } else {
4110 return false;
4114 public void check_type (DataType type) {
4115 var array_type = type as ArrayType;
4116 if (array_type != null) {
4117 check_type (array_type.element_type);
4118 if (array_type.element_type is ArrayType) {
4119 Report.error (type.source_reference, "Stacked arrays are not supported");
4120 } else if (array_type.element_type is DelegateType) {
4121 var delegate_type = (DelegateType) array_type.element_type;
4122 if (delegate_type.delegate_symbol.has_target) {
4123 Report.error (type.source_reference, "Delegates with target are not supported as array element type");
4127 foreach (var type_arg in type.get_type_arguments ()) {
4128 check_type (type_arg);
4129 check_type_argument (type_arg);
4133 void check_type_argument (DataType type_arg) {
4134 if (type_arg is GenericType
4135 || type_arg is PointerType
4136 || is_reference_type_argument (type_arg)
4137 || is_nullable_value_type_argument (type_arg)
4138 || is_signed_integer_type_argument (type_arg)
4139 || is_unsigned_integer_type_argument (type_arg)) {
4140 // no error
4141 } else if (type_arg is DelegateType) {
4142 var delegate_type = (DelegateType) type_arg;
4143 if (delegate_type.delegate_symbol.has_target) {
4144 Report.error (type_arg.source_reference, "Delegates with target are not supported as generic type arguments");
4146 } else {
4147 Report.error (type_arg.source_reference, "`%s' is not a supported generic type argument, use `?' to box value types".printf (type_arg.to_string ()));
4151 public virtual void generate_class_declaration (Class cl, CCodeFile decl_space) {
4152 if (add_symbol_declaration (decl_space, cl, cl.get_cname ())) {
4153 return;
4157 public virtual void generate_interface_declaration (Interface iface, CCodeFile decl_space) {
4160 public virtual void generate_method_declaration (Method m, CCodeFile decl_space) {
4163 public virtual void generate_error_domain_declaration (ErrorDomain edomain, CCodeFile decl_space) {
4166 public void add_generic_type_arguments (Map<int,CCodeExpression> arg_map, List<DataType> type_args, CodeNode expr, bool is_chainup = false) {
4167 int type_param_index = 0;
4168 foreach (var type_arg in type_args) {
4169 arg_map.set (get_param_pos (0.1 * type_param_index + 0.01), get_type_id_expression (type_arg, is_chainup));
4170 if (requires_copy (type_arg)) {
4171 var dup_func = get_dup_func_expression (type_arg, type_arg.source_reference, is_chainup);
4172 if (dup_func == null) {
4173 // type doesn't contain a copy function
4174 expr.error = true;
4175 return;
4177 arg_map.set (get_param_pos (0.1 * type_param_index + 0.02), new CCodeCastExpression (dup_func, "GBoxedCopyFunc"));
4178 arg_map.set (get_param_pos (0.1 * type_param_index + 0.03), get_destroy_func_expression (type_arg, is_chainup));
4179 } else {
4180 arg_map.set (get_param_pos (0.1 * type_param_index + 0.02), new CCodeConstant ("NULL"));
4181 arg_map.set (get_param_pos (0.1 * type_param_index + 0.03), new CCodeConstant ("NULL"));
4183 type_param_index++;
4187 public override void visit_object_creation_expression (ObjectCreationExpression expr) {
4188 CCodeExpression instance = null;
4189 CCodeExpression creation_expr = null;
4191 check_type (expr.type_reference);
4193 var st = expr.type_reference.data_type as Struct;
4194 if ((st != null && (!st.is_simple_type () || st.get_cname () == "va_list")) || expr.get_object_initializer ().size > 0) {
4195 // value-type initialization or object creation expression with object initializer
4197 var local = expr.parent_node as LocalVariable;
4198 if (local != null && has_simple_struct_initializer (local)) {
4199 if (local.captured) {
4200 var block = (Block) local.parent_symbol;
4201 instance = new CCodeMemberAccess.pointer (get_variable_cexpression ("_data%d_".printf (get_block_id (block))), get_variable_cname (local.name));
4202 } else {
4203 instance = get_variable_cexpression (get_variable_cname (local.name));
4205 } else {
4206 var temp_decl = get_temp_variable (expr.type_reference, false, expr);
4207 emit_temp_var (temp_decl);
4209 instance = get_variable_cexpression (get_variable_cname (temp_decl.name));
4213 if (expr.symbol_reference == null) {
4214 // no creation method
4215 if (expr.type_reference.data_type is Struct) {
4216 // memset needs string.h
4217 cfile.add_include ("string.h");
4218 var creation_call = new CCodeFunctionCall (new CCodeIdentifier ("memset"));
4219 creation_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, instance));
4220 creation_call.add_argument (new CCodeConstant ("0"));
4221 creation_call.add_argument (new CCodeIdentifier ("sizeof (%s)".printf (expr.type_reference.get_cname ())));
4223 creation_expr = creation_call;
4225 } else if (expr.type_reference.data_type == glist_type ||
4226 expr.type_reference.data_type == gslist_type) {
4227 // NULL is an empty list
4228 set_cvalue (expr, new CCodeConstant ("NULL"));
4229 } else if (expr.symbol_reference is Method) {
4230 // use creation method
4231 var m = (Method) expr.symbol_reference;
4232 var params = m.get_parameters ();
4233 CCodeFunctionCall creation_call;
4235 generate_method_declaration (m, cfile);
4237 var cl = expr.type_reference.data_type as Class;
4239 if (!m.has_new_function) {
4240 // use construct function directly
4241 creation_call = new CCodeFunctionCall (new CCodeIdentifier (m.get_real_cname ()));
4242 creation_call.add_argument (new CCodeIdentifier (cl.get_type_id ()));
4243 } else {
4244 creation_call = new CCodeFunctionCall (new CCodeIdentifier (m.get_cname ()));
4247 if ((st != null && !st.is_simple_type ()) && !(m.cinstance_parameter_position < 0)) {
4248 creation_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, instance));
4249 } else if (st != null && st.get_cname () == "va_list") {
4250 creation_call.add_argument (instance);
4251 if (m.get_cname () == "va_start") {
4252 Parameter last_param = null;
4253 foreach (var param in current_method.get_parameters ()) {
4254 if (param.ellipsis) {
4255 break;
4257 last_param = param;
4259 creation_call.add_argument (new CCodeIdentifier (get_variable_cname (last_param.name)));
4263 generate_type_declaration (expr.type_reference, cfile);
4265 var carg_map = new HashMap<int,CCodeExpression> (direct_hash, direct_equal);
4267 if (cl != null && !cl.is_compact) {
4268 add_generic_type_arguments (carg_map, expr.type_reference.get_type_arguments (), expr);
4269 } else if (cl != null && m.simple_generics) {
4270 int type_param_index = 0;
4271 foreach (var type_arg in expr.type_reference.get_type_arguments ()) {
4272 if (requires_copy (type_arg)) {
4273 carg_map.set (get_param_pos (-1 + 0.1 * type_param_index + 0.03), get_destroy0_func_expression (type_arg));
4274 } else {
4275 carg_map.set (get_param_pos (-1 + 0.1 * type_param_index + 0.03), new CCodeConstant ("NULL"));
4277 type_param_index++;
4281 bool ellipsis = false;
4283 int i = 1;
4284 int arg_pos;
4285 Iterator<Parameter> params_it = params.iterator ();
4286 foreach (Expression arg in expr.get_argument_list ()) {
4287 CCodeExpression cexpr = get_cvalue (arg);
4288 Parameter param = null;
4289 if (params_it.next ()) {
4290 param = params_it.get ();
4291 ellipsis = param.ellipsis;
4292 if (!ellipsis) {
4293 if (!param.no_array_length && param.variable_type is ArrayType) {
4294 var array_type = (ArrayType) param.variable_type;
4295 for (int dim = 1; dim <= array_type.rank; dim++) {
4296 carg_map.set (get_param_pos (param.carray_length_parameter_position + 0.01 * dim), get_array_length_cexpression (arg, dim));
4298 } else if (param.variable_type is DelegateType) {
4299 var deleg_type = (DelegateType) param.variable_type;
4300 var d = deleg_type.delegate_symbol;
4301 if (d.has_target) {
4302 CCodeExpression delegate_target_destroy_notify;
4303 var delegate_target = get_delegate_target_cexpression (arg, out delegate_target_destroy_notify);
4304 carg_map.set (get_param_pos (param.cdelegate_target_parameter_position), delegate_target);
4305 if (deleg_type.value_owned) {
4306 carg_map.set (get_param_pos (param.cdelegate_target_parameter_position + 0.01), delegate_target_destroy_notify);
4311 cexpr = handle_struct_argument (param, arg, cexpr);
4313 if (param.ctype != null) {
4314 cexpr = new CCodeCastExpression (cexpr, param.ctype);
4316 } else {
4317 cexpr = handle_struct_argument (null, arg, cexpr);
4320 arg_pos = get_param_pos (param.cparameter_position, ellipsis);
4321 } else {
4322 // default argument position
4323 cexpr = handle_struct_argument (null, arg, cexpr);
4324 arg_pos = get_param_pos (i, ellipsis);
4327 carg_map.set (arg_pos, cexpr);
4329 i++;
4331 while (params_it.next ()) {
4332 var param = params_it.get ();
4334 if (param.ellipsis) {
4335 ellipsis = true;
4336 break;
4339 if (param.initializer == null) {
4340 Report.error (expr.source_reference, "no default expression for argument %d".printf (i));
4341 return;
4344 /* evaluate default expression here as the code
4345 * generator might not have visited the formal
4346 * parameter yet */
4347 param.initializer.emit (this);
4349 carg_map.set (get_param_pos (param.cparameter_position), get_cvalue (param.initializer));
4350 i++;
4353 // append C arguments in the right order
4354 int last_pos = -1;
4355 int min_pos;
4356 while (true) {
4357 min_pos = -1;
4358 foreach (int pos in carg_map.get_keys ()) {
4359 if (pos > last_pos && (min_pos == -1 || pos < min_pos)) {
4360 min_pos = pos;
4363 if (min_pos == -1) {
4364 break;
4366 creation_call.add_argument (carg_map.get (min_pos));
4367 last_pos = min_pos;
4370 if ((st != null && !st.is_simple_type ()) && m.cinstance_parameter_position < 0) {
4371 // instance parameter is at the end in a struct creation method
4372 creation_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, instance));
4375 if (expr.tree_can_fail) {
4376 // method can fail
4377 current_method_inner_error = true;
4378 creation_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression ("_inner_error_")));
4381 if (ellipsis) {
4382 /* ensure variable argument list ends with NULL
4383 * except when using printf-style arguments */
4384 if (!m.printf_format && !m.scanf_format && m.sentinel != "") {
4385 creation_call.add_argument (new CCodeConstant (m.sentinel));
4389 creation_expr = creation_call;
4391 // cast the return value of the creation method back to the intended type if
4392 // it requested a special C return type
4393 if (get_custom_creturn_type (m) != null) {
4394 creation_expr = new CCodeCastExpression (creation_expr, expr.type_reference.get_cname ());
4396 } else if (expr.symbol_reference is ErrorCode) {
4397 var ecode = (ErrorCode) expr.symbol_reference;
4398 var edomain = (ErrorDomain) ecode.parent_symbol;
4399 CCodeFunctionCall creation_call;
4401 generate_error_domain_declaration (edomain, cfile);
4403 if (expr.get_argument_list ().size == 1) {
4404 // must not be a format argument
4405 creation_call = new CCodeFunctionCall (new CCodeIdentifier ("g_error_new_literal"));
4406 } else {
4407 creation_call = new CCodeFunctionCall (new CCodeIdentifier ("g_error_new"));
4409 creation_call.add_argument (new CCodeIdentifier (edomain.get_upper_case_cname ()));
4410 creation_call.add_argument (new CCodeIdentifier (ecode.get_cname ()));
4412 foreach (Expression arg in expr.get_argument_list ()) {
4413 creation_call.add_argument (get_cvalue (arg));
4416 creation_expr = creation_call;
4417 } else {
4418 assert (false);
4421 var local = expr.parent_node as LocalVariable;
4422 if (local != null && has_simple_struct_initializer (local)) {
4423 // no temporary variable necessary
4424 ccode.add_expression (creation_expr);
4425 set_cvalue (expr, instance);
4426 return;
4427 } else if (instance != null) {
4428 if (expr.type_reference.data_type is Struct) {
4429 ccode.add_expression (creation_expr);
4430 } else {
4431 ccode.add_assignment (instance, creation_expr);
4434 foreach (MemberInitializer init in expr.get_object_initializer ()) {
4435 if (init.symbol_reference is Field) {
4436 var f = (Field) init.symbol_reference;
4437 var instance_target_type = get_data_type_for_symbol ((TypeSymbol) f.parent_symbol);
4438 var typed_inst = transform_expression (instance, expr.type_reference, instance_target_type);
4439 CCodeExpression lhs;
4440 if (expr.type_reference.data_type is Struct) {
4441 lhs = new CCodeMemberAccess (typed_inst, f.get_cname ());
4442 } else {
4443 lhs = new CCodeMemberAccess.pointer (typed_inst, f.get_cname ());
4445 ccode.add_assignment (lhs, get_cvalue (init.initializer));
4447 if (f.variable_type is ArrayType && !f.no_array_length) {
4448 var array_type = (ArrayType) f.variable_type;
4449 for (int dim = 1; dim <= array_type.rank; dim++) {
4450 if (expr.type_reference.data_type is Struct) {
4451 lhs = new CCodeMemberAccess (typed_inst, get_array_length_cname (f.get_cname (), dim));
4452 } else {
4453 lhs = new CCodeMemberAccess.pointer (typed_inst, get_array_length_cname (f.get_cname (), dim));
4455 var rhs_array_len = get_array_length_cexpression (init.initializer, dim);
4456 ccode.add_assignment (lhs, rhs_array_len);
4458 } else if (f.variable_type is DelegateType && (f.variable_type as DelegateType).delegate_symbol.has_target && !f.no_delegate_target) {
4459 if (expr.type_reference.data_type is Struct) {
4460 lhs = new CCodeMemberAccess (typed_inst, get_delegate_target_cname (f.get_cname ()));
4461 } else {
4462 lhs = new CCodeMemberAccess.pointer (typed_inst, get_delegate_target_cname (f.get_cname ()));
4464 CCodeExpression rhs_delegate_target_destroy_notify;
4465 var rhs_delegate_target = get_delegate_target_cexpression (init.initializer, out rhs_delegate_target_destroy_notify);
4466 ccode.add_assignment (lhs, rhs_delegate_target);
4469 var cl = f.parent_symbol as Class;
4470 if (cl != null) {
4471 generate_class_struct_declaration (cl, cfile);
4473 } else if (init.symbol_reference is Property) {
4474 var inst_ma = new MemberAccess.simple ("new");
4475 inst_ma.value_type = expr.type_reference;
4476 set_cvalue (inst_ma, instance);
4477 store_property ((Property) init.symbol_reference, inst_ma, init.initializer.target_value);
4481 creation_expr = instance;
4484 if (creation_expr != null) {
4485 var temp_var = get_temp_variable (expr.value_type);
4486 var temp_ref = get_variable_cexpression (temp_var.name);
4488 emit_temp_var (temp_var);
4490 ccode.add_assignment (temp_ref, creation_expr);
4491 set_cvalue (expr, temp_ref);
4495 public CCodeExpression? handle_struct_argument (Parameter? param, Expression arg, CCodeExpression? cexpr) {
4496 DataType type;
4497 if (param != null) {
4498 type = param.variable_type;
4499 } else {
4500 // varargs
4501 type = arg.value_type;
4504 // pass non-simple struct instances always by reference
4505 if (!(arg.value_type is NullType) && type.is_real_struct_type ()) {
4506 // we already use a reference for arguments of ref, out, and nullable parameters
4507 if ((param == null || param.direction == ParameterDirection.IN) && !type.nullable) {
4508 var unary = cexpr as CCodeUnaryExpression;
4509 if (unary != null && unary.operator == CCodeUnaryOperator.POINTER_INDIRECTION) {
4510 // *expr => expr
4511 return unary.inner;
4512 } else if (cexpr is CCodeIdentifier || cexpr is CCodeMemberAccess) {
4513 return new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cexpr);
4514 } else {
4515 // if cexpr is e.g. a function call, we can't take the address of the expression
4516 var temp_var = get_temp_variable (type, true, null, false);
4517 emit_temp_var (temp_var);
4519 ccode.add_assignment (get_variable_cexpression (temp_var.name), cexpr);
4520 return new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression (temp_var.name));
4525 return cexpr;
4528 public override void visit_sizeof_expression (SizeofExpression expr) {
4529 generate_type_declaration (expr.type_reference, cfile);
4531 var csizeof = new CCodeFunctionCall (new CCodeIdentifier ("sizeof"));
4532 csizeof.add_argument (new CCodeIdentifier (expr.type_reference.get_cname ()));
4533 set_cvalue (expr, csizeof);
4536 public override void visit_typeof_expression (TypeofExpression expr) {
4537 set_cvalue (expr, get_type_id_expression (expr.type_reference));
4540 public override void visit_unary_expression (UnaryExpression expr) {
4541 if (expr.operator == UnaryOperator.REF || expr.operator == UnaryOperator.OUT) {
4542 var glib_value = (GLibValue) expr.inner.target_value;
4544 var ref_value = new GLibValue (glib_value.value_type);
4545 ref_value.cvalue = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, glib_value.cvalue);
4547 if (glib_value.array_length_cvalues != null) {
4548 for (int i = 0; i < glib_value.array_length_cvalues.size; i++) {
4549 ref_value.append_array_length_cvalue (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, glib_value.array_length_cvalues[i]));
4553 if (glib_value.delegate_target_cvalue != null) {
4554 ref_value.delegate_target_cvalue = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, glib_value.delegate_target_cvalue);
4556 if (glib_value.delegate_target_destroy_notify_cvalue != null) {
4557 ref_value.delegate_target_destroy_notify_cvalue = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, glib_value.delegate_target_destroy_notify_cvalue);
4560 expr.target_value = ref_value;
4561 return;
4564 CCodeUnaryOperator op;
4565 if (expr.operator == UnaryOperator.PLUS) {
4566 op = CCodeUnaryOperator.PLUS;
4567 } else if (expr.operator == UnaryOperator.MINUS) {
4568 op = CCodeUnaryOperator.MINUS;
4569 } else if (expr.operator == UnaryOperator.LOGICAL_NEGATION) {
4570 op = CCodeUnaryOperator.LOGICAL_NEGATION;
4571 } else if (expr.operator == UnaryOperator.BITWISE_COMPLEMENT) {
4572 op = CCodeUnaryOperator.BITWISE_COMPLEMENT;
4573 } else if (expr.operator == UnaryOperator.INCREMENT) {
4574 op = CCodeUnaryOperator.PREFIX_INCREMENT;
4575 } else if (expr.operator == UnaryOperator.DECREMENT) {
4576 op = CCodeUnaryOperator.PREFIX_DECREMENT;
4577 } else {
4578 assert_not_reached ();
4580 set_cvalue (expr, new CCodeUnaryExpression (op, get_cvalue (expr.inner)));
4583 public CCodeExpression? try_cast_value_to_type (CCodeExpression ccodeexpr, DataType from, DataType to, Expression? expr = null) {
4584 if (from == null || gvalue_type == null || from.data_type != gvalue_type || to.get_type_id () == null) {
4585 return null;
4588 // explicit conversion from GValue
4589 var ccall = new CCodeFunctionCall (get_value_getter_function (to));
4590 CCodeExpression gvalue;
4591 if (from.nullable) {
4592 gvalue = ccodeexpr;
4593 } else {
4594 gvalue = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, ccodeexpr);
4596 ccall.add_argument (gvalue);
4598 CCodeExpression rv = ccall;
4600 if (expr != null && to is ArrayType) {
4601 // null-terminated string array
4602 var len_call = new CCodeFunctionCall (new CCodeIdentifier ("g_strv_length"));
4603 len_call.add_argument (rv);
4604 append_array_length (expr, len_call);
4605 } else if (to is StructValueType) {
4606 var temp_decl = get_temp_variable (to, true, null, true);
4607 emit_temp_var (temp_decl);
4608 var ctemp = get_variable_cexpression (temp_decl.name);
4610 rv = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, new CCodeCastExpression (rv, (new PointerType(to)).get_cname ()));
4611 var holds = new CCodeFunctionCall (new CCodeIdentifier ("G_VALUE_HOLDS"));
4612 holds.add_argument (gvalue);
4613 holds.add_argument (new CCodeIdentifier (to.get_type_id ()));
4614 var cond = new CCodeBinaryExpression (CCodeBinaryOperator.AND, holds, ccall);
4615 var warn = new CCodeFunctionCall (new CCodeIdentifier ("g_warning"));
4616 warn.add_argument (new CCodeConstant ("\"Invalid GValue unboxing (wrong type or NULL)\""));
4617 var fail = new CCodeCommaExpression ();
4618 fail.append_expression (warn);
4619 fail.append_expression (ctemp);
4620 rv = new CCodeConditionalExpression (cond, rv, fail);
4623 return rv;
4626 int next_variant_function_id = 0;
4628 public CCodeExpression? try_cast_variant_to_type (CCodeExpression ccodeexpr, DataType from, DataType to, Expression? expr = null) {
4629 if (from == null || gvariant_type == null || from.data_type != gvariant_type) {
4630 return null;
4633 string variant_func = "_variant_get%d".printf (++next_variant_function_id);
4635 var ccall = new CCodeFunctionCall (new CCodeIdentifier (variant_func));
4636 ccall.add_argument (ccodeexpr);
4638 var cfunc = new CCodeFunction (variant_func);
4639 cfunc.modifiers = CCodeModifiers.STATIC;
4640 cfunc.add_parameter (new CCodeParameter ("value", "GVariant*"));
4642 if (!to.is_real_non_null_struct_type ()) {
4643 cfunc.return_type = to.get_cname ();
4646 if (to.is_real_non_null_struct_type ()) {
4647 // structs are returned via out parameter
4648 cfunc.add_parameter (new CCodeParameter ("result", to.get_cname () + "*"));
4649 } else if (to is ArrayType) {
4650 // return array length if appropriate
4651 var array_type = (ArrayType) to;
4653 for (int dim = 1; dim <= array_type.rank; dim++) {
4654 var temp_decl = get_temp_variable (int_type, false, expr);
4655 emit_temp_var (temp_decl);
4657 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression (temp_decl.name)));
4658 cfunc.add_parameter (new CCodeParameter (get_array_length_cname ("result", dim), "int*"));
4659 append_array_length (expr, get_variable_cexpression (temp_decl.name));
4663 push_function (cfunc);
4665 var result = deserialize_expression (to, new CCodeIdentifier ("value"), new CCodeIdentifier ("*result"));
4666 ccode.add_return (result);
4668 pop_function ();
4670 cfile.add_function_declaration (cfunc);
4671 cfile.add_function (cfunc);
4673 return ccall;
4676 public virtual CCodeExpression? deserialize_expression (DataType type, CCodeExpression variant_expr, CCodeExpression? expr, CCodeExpression? error_expr = null, out bool may_fail = null) {
4677 return null;
4680 public virtual CCodeExpression? serialize_expression (DataType type, CCodeExpression expr) {
4681 return null;
4684 public override void visit_cast_expression (CastExpression expr) {
4685 var valuecast = try_cast_value_to_type (get_cvalue (expr.inner), expr.inner.value_type, expr.type_reference, expr);
4686 if (valuecast != null) {
4687 set_cvalue (expr, valuecast);
4688 return;
4691 var variantcast = try_cast_variant_to_type (get_cvalue (expr.inner), expr.inner.value_type, expr.type_reference, expr);
4692 if (variantcast != null) {
4693 set_cvalue (expr, variantcast);
4694 return;
4697 generate_type_declaration (expr.type_reference, cfile);
4699 var cl = expr.type_reference.data_type as Class;
4700 var iface = expr.type_reference.data_type as Interface;
4701 if (context.profile == Profile.GOBJECT && (iface != null || (cl != null && !cl.is_compact))) {
4702 // checked cast for strict subtypes of GTypeInstance
4703 if (expr.is_silent_cast) {
4704 var temp_decl = get_temp_variable (expr.inner.value_type, expr.inner.value_type.value_owned, expr, false);
4705 emit_temp_var (temp_decl);
4706 var ctemp = get_variable_cexpression (temp_decl.name);
4708 ccode.add_assignment (ctemp, get_cvalue (expr.inner));
4709 var ccheck = create_type_check (ctemp, expr.type_reference);
4710 var ccast = new CCodeCastExpression (ctemp, expr.type_reference.get_cname ());
4711 var cnull = new CCodeConstant ("NULL");
4713 set_cvalue (expr, new CCodeConditionalExpression (ccheck, ccast, cnull));
4714 } else {
4715 set_cvalue (expr, generate_instance_cast (get_cvalue (expr.inner), expr.type_reference.data_type));
4717 } else {
4718 if (expr.is_silent_cast) {
4719 expr.error = true;
4720 Report.error (expr.source_reference, "Operation not supported for this type");
4721 return;
4724 // retain array length
4725 var array_type = expr.type_reference as ArrayType;
4726 if (array_type != null && expr.inner.value_type is ArrayType) {
4727 for (int dim = 1; dim <= array_type.rank; dim++) {
4728 append_array_length (expr, get_array_length_cexpression (expr.inner, dim));
4730 } else if (array_type != null) {
4731 // cast from non-array to array, set invalid length
4732 // required by string.data, e.g.
4733 for (int dim = 1; dim <= array_type.rank; dim++) {
4734 append_array_length (expr, new CCodeConstant ("-1"));
4738 var innercexpr = get_cvalue (expr.inner);
4739 if (expr.type_reference.data_type is Struct && !expr.type_reference.nullable &&
4740 expr.inner.value_type.data_type is Struct && expr.inner.value_type.nullable) {
4741 // nullable integer or float or boolean or struct cast to non-nullable
4742 innercexpr = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, innercexpr);
4744 set_cvalue (expr, new CCodeCastExpression (innercexpr, expr.type_reference.get_cname ()));
4746 if (expr.type_reference is DelegateType) {
4747 if (get_delegate_target (expr.inner) != null) {
4748 set_delegate_target (expr, get_delegate_target (expr.inner));
4749 } else {
4750 set_delegate_target (expr, new CCodeConstant ("NULL"));
4752 if (get_delegate_target_destroy_notify (expr.inner) != null) {
4753 set_delegate_target_destroy_notify (expr, get_delegate_target_destroy_notify (expr.inner));
4754 } else {
4755 set_delegate_target_destroy_notify (expr, new CCodeConstant ("NULL"));
4761 public override void visit_named_argument (NamedArgument expr) {
4762 set_cvalue (expr, get_cvalue (expr.inner));
4765 public override void visit_pointer_indirection (PointerIndirection expr) {
4766 set_cvalue (expr, new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, get_cvalue (expr.inner)));
4769 public override void visit_addressof_expression (AddressofExpression expr) {
4770 set_cvalue (expr, new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_cvalue (expr.inner)));
4773 public override void visit_reference_transfer_expression (ReferenceTransferExpression expr) {
4774 /* (tmp = var, var = null, tmp) */
4775 var temp_decl = get_temp_variable (expr.value_type, true, expr, false);
4776 emit_temp_var (temp_decl);
4777 var cvar = get_variable_cexpression (temp_decl.name);
4779 ccode.add_assignment (cvar, get_cvalue (expr.inner));
4780 if (!(expr.value_type is DelegateType)) {
4781 ccode.add_assignment (get_cvalue (expr.inner), new CCodeConstant ("NULL"));
4784 set_cvalue (expr, cvar);
4786 var array_type = expr.value_type as ArrayType;
4787 if (array_type != null) {
4788 for (int dim = 1; dim <= array_type.rank; dim++) {
4789 append_array_length (expr, get_array_length_cexpression (expr.inner, dim));
4793 var delegate_type = expr.value_type as DelegateType;
4794 if (delegate_type != null && delegate_type.delegate_symbol.has_target) {
4795 var temp_target_decl = get_temp_variable (new PointerType (new VoidType ()), true, expr, false);
4796 emit_temp_var (temp_target_decl);
4797 var target_cvar = get_variable_cexpression (temp_target_decl.name);
4798 CCodeExpression target_destroy_notify;
4799 var target = get_delegate_target_cexpression (expr.inner, out target_destroy_notify);
4800 ccode.add_assignment (target_cvar, target);
4801 set_delegate_target (expr, target_cvar);
4802 if (target_destroy_notify != null) {
4803 var temp_target_destroy_notify_decl = get_temp_variable (gdestroynotify_type, true, expr, false);
4804 emit_temp_var (temp_target_destroy_notify_decl);
4805 var target_destroy_notify_cvar = get_variable_cexpression (temp_target_destroy_notify_decl.name);
4806 ccode.add_assignment (target_destroy_notify_cvar, target_destroy_notify);
4807 ccode.add_assignment (target_destroy_notify, new CCodeConstant ("NULL"));
4808 set_delegate_target_destroy_notify (expr, target_destroy_notify_cvar);
4813 public override void visit_binary_expression (BinaryExpression expr) {
4814 var cleft = get_cvalue (expr.left);
4815 var cright = get_cvalue (expr.right);
4817 CCodeExpression? left_chain = null;
4818 if (expr.chained) {
4819 var lbe = (BinaryExpression) expr.left;
4821 var temp_decl = get_temp_variable (lbe.right.value_type, true, null, false);
4822 emit_temp_var (temp_decl);
4823 var cvar = get_variable_cexpression (temp_decl.name);
4824 var clbe = (CCodeBinaryExpression) get_cvalue (lbe);
4825 if (lbe.chained) {
4826 clbe = (CCodeBinaryExpression) clbe.right;
4828 ccode.add_assignment (cvar, get_cvalue (lbe.right));
4829 clbe.right = get_variable_cexpression (temp_decl.name);
4830 left_chain = cleft;
4831 cleft = cvar;
4834 CCodeBinaryOperator op;
4835 if (expr.operator == BinaryOperator.PLUS) {
4836 op = CCodeBinaryOperator.PLUS;
4837 } else if (expr.operator == BinaryOperator.MINUS) {
4838 op = CCodeBinaryOperator.MINUS;
4839 } else if (expr.operator == BinaryOperator.MUL) {
4840 op = CCodeBinaryOperator.MUL;
4841 } else if (expr.operator == BinaryOperator.DIV) {
4842 op = CCodeBinaryOperator.DIV;
4843 } else if (expr.operator == BinaryOperator.MOD) {
4844 if (expr.value_type.equals (double_type)) {
4845 cfile.add_include ("math.h");
4846 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("fmod"));
4847 ccall.add_argument (cleft);
4848 ccall.add_argument (cright);
4849 set_cvalue (expr, ccall);
4850 return;
4851 } else if (expr.value_type.equals (float_type)) {
4852 cfile.add_include ("math.h");
4853 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("fmodf"));
4854 ccall.add_argument (cleft);
4855 ccall.add_argument (cright);
4856 set_cvalue (expr, ccall);
4857 return;
4858 } else {
4859 op = CCodeBinaryOperator.MOD;
4861 } else if (expr.operator == BinaryOperator.SHIFT_LEFT) {
4862 op = CCodeBinaryOperator.SHIFT_LEFT;
4863 } else if (expr.operator == BinaryOperator.SHIFT_RIGHT) {
4864 op = CCodeBinaryOperator.SHIFT_RIGHT;
4865 } else if (expr.operator == BinaryOperator.LESS_THAN) {
4866 op = CCodeBinaryOperator.LESS_THAN;
4867 } else if (expr.operator == BinaryOperator.GREATER_THAN) {
4868 op = CCodeBinaryOperator.GREATER_THAN;
4869 } else if (expr.operator == BinaryOperator.LESS_THAN_OR_EQUAL) {
4870 op = CCodeBinaryOperator.LESS_THAN_OR_EQUAL;
4871 } else if (expr.operator == BinaryOperator.GREATER_THAN_OR_EQUAL) {
4872 op = CCodeBinaryOperator.GREATER_THAN_OR_EQUAL;
4873 } else if (expr.operator == BinaryOperator.EQUALITY) {
4874 op = CCodeBinaryOperator.EQUALITY;
4875 } else if (expr.operator == BinaryOperator.INEQUALITY) {
4876 op = CCodeBinaryOperator.INEQUALITY;
4877 } else if (expr.operator == BinaryOperator.BITWISE_AND) {
4878 op = CCodeBinaryOperator.BITWISE_AND;
4879 } else if (expr.operator == BinaryOperator.BITWISE_OR) {
4880 op = CCodeBinaryOperator.BITWISE_OR;
4881 } else if (expr.operator == BinaryOperator.BITWISE_XOR) {
4882 op = CCodeBinaryOperator.BITWISE_XOR;
4883 } else if (expr.operator == BinaryOperator.AND) {
4884 op = CCodeBinaryOperator.AND;
4885 } else if (expr.operator == BinaryOperator.OR) {
4886 op = CCodeBinaryOperator.OR;
4887 } else if (expr.operator == BinaryOperator.IN) {
4888 if (expr.right.value_type is ArrayType) {
4889 var array_type = (ArrayType) expr.right.value_type;
4890 var node = new CCodeFunctionCall (new CCodeIdentifier (generate_array_contains_wrapper (array_type)));
4891 node.add_argument (cright);
4892 node.add_argument (get_array_length_cexpression (expr.right));
4893 if (array_type.element_type is StructValueType) {
4894 node.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cleft));
4895 } else {
4896 node.add_argument (cleft);
4898 set_cvalue (expr, node);
4899 } else {
4900 set_cvalue (expr, new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeBinaryExpression (CCodeBinaryOperator.BITWISE_AND, cright, cleft), cleft));
4902 return;
4903 } else {
4904 assert_not_reached ();
4907 if (expr.operator == BinaryOperator.EQUALITY ||
4908 expr.operator == BinaryOperator.INEQUALITY) {
4909 var left_type = expr.left.target_type;
4910 var right_type = expr.right.target_type;
4911 make_comparable_cexpression (ref left_type, ref cleft, ref right_type, ref cright);
4913 if (left_type is StructValueType && right_type is StructValueType) {
4914 var equalfunc = generate_struct_equal_function ((Struct) left_type.data_type as Struct);
4915 var ccall = new CCodeFunctionCall (new CCodeIdentifier (equalfunc));
4916 ccall.add_argument (cleft);
4917 ccall.add_argument (cright);
4918 cleft = ccall;
4919 cright = new CCodeConstant ("TRUE");
4920 } else if ((left_type is IntegerType || left_type is FloatingType || left_type is BooleanType) && left_type.nullable &&
4921 (right_type is IntegerType || right_type is FloatingType || right_type is BooleanType) && right_type.nullable) {
4922 var equalfunc = generate_numeric_equal_function ((Struct) left_type.data_type as Struct);
4923 var ccall = new CCodeFunctionCall (new CCodeIdentifier (equalfunc));
4924 ccall.add_argument (cleft);
4925 ccall.add_argument (cright);
4926 cleft = ccall;
4927 cright = new CCodeConstant ("TRUE");
4931 if (!(expr.left.value_type is NullType)
4932 && expr.left.value_type.compatible (string_type)
4933 && !(expr.right.value_type is NullType)
4934 && expr.right.value_type.compatible (string_type)) {
4935 if (expr.operator == BinaryOperator.PLUS) {
4936 // string concatenation
4937 if (expr.left.is_constant () && expr.right.is_constant ()) {
4938 string left, right;
4940 if (cleft is CCodeIdentifier) {
4941 left = ((CCodeIdentifier) cleft).name;
4942 } else if (cleft is CCodeConstant) {
4943 left = ((CCodeConstant) cleft).name;
4944 } else {
4945 assert_not_reached ();
4947 if (cright is CCodeIdentifier) {
4948 right = ((CCodeIdentifier) cright).name;
4949 } else if (cright is CCodeConstant) {
4950 right = ((CCodeConstant) cright).name;
4951 } else {
4952 assert_not_reached ();
4955 set_cvalue (expr, new CCodeConstant ("%s %s".printf (left, right)));
4956 return;
4957 } else {
4958 if (context.profile == Profile.POSIX) {
4959 // convert to strcat(strcpy(malloc(1+strlen(a)+strlen(b)),a),b)
4960 var strcat = new CCodeFunctionCall (new CCodeIdentifier ("strcat"));
4961 var strcpy = new CCodeFunctionCall (new CCodeIdentifier ("strcpy"));
4962 var malloc = new CCodeFunctionCall (new CCodeIdentifier ("malloc"));
4964 var strlen_a = new CCodeFunctionCall (new CCodeIdentifier ("strlen"));
4965 strlen_a.add_argument(cleft);
4966 var strlen_b = new CCodeFunctionCall (new CCodeIdentifier ("strlen"));
4967 strlen_b.add_argument(cright);
4968 var newlength = new CCodeBinaryExpression (CCodeBinaryOperator.PLUS, new CCodeIdentifier("1"),
4969 new CCodeBinaryExpression (CCodeBinaryOperator.PLUS, strlen_a, strlen_b));
4970 malloc.add_argument(newlength);
4972 strcpy.add_argument(malloc);
4973 strcpy.add_argument(cleft);
4975 strcat.add_argument(strcpy);
4976 strcat.add_argument(cright);
4977 set_cvalue (expr, strcat);
4978 } else {
4979 // convert to g_strconcat (a, b, NULL)
4980 var temp_var = get_temp_variable (expr.value_type, true, null, false);
4981 var temp_ref = get_variable_cexpression (temp_var.name);
4982 emit_temp_var (temp_var);
4984 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_strconcat"));
4985 ccall.add_argument (cleft);
4986 ccall.add_argument (cright);
4987 ccall.add_argument (new CCodeConstant("NULL"));
4989 ccode.add_assignment (temp_ref, ccall);
4990 set_cvalue (expr, temp_ref);
4992 return;
4994 } else if (expr.operator == BinaryOperator.EQUALITY
4995 || expr.operator == BinaryOperator.INEQUALITY
4996 || expr.operator == BinaryOperator.LESS_THAN
4997 || expr.operator == BinaryOperator.GREATER_THAN
4998 || expr.operator == BinaryOperator.LESS_THAN_OR_EQUAL
4999 || expr.operator == BinaryOperator.GREATER_THAN_OR_EQUAL) {
5000 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_strcmp0"));
5001 ccall.add_argument (cleft);
5002 ccall.add_argument (cright);
5003 cleft = ccall;
5004 cright = new CCodeConstant ("0");
5008 set_cvalue (expr, new CCodeBinaryExpression (op, cleft, cright));
5009 if (left_chain != null) {
5010 set_cvalue (expr, new CCodeBinaryExpression (CCodeBinaryOperator.AND, left_chain, get_cvalue (expr)));
5014 public string? get_type_check_function (TypeSymbol type) {
5015 var cl = type as Class;
5016 if (cl != null && cl.type_check_function != null) {
5017 return cl.type_check_function;
5018 } else if ((cl != null && cl.is_compact) || type is Struct || type is Enum || type is Delegate) {
5019 return null;
5020 } else {
5021 return type.get_upper_case_cname ("IS_");
5025 CCodeExpression? create_type_check (CCodeNode ccodenode, DataType type) {
5026 var et = type as ErrorType;
5027 if (et != null && et.error_code != null) {
5028 var matches_call = new CCodeFunctionCall (new CCodeIdentifier ("g_error_matches"));
5029 matches_call.add_argument ((CCodeExpression) ccodenode);
5030 matches_call.add_argument (new CCodeIdentifier (et.error_domain.get_upper_case_cname ()));
5031 matches_call.add_argument (new CCodeIdentifier (et.error_code.get_cname ()));
5032 return matches_call;
5033 } else if (et != null && et.error_domain != null) {
5034 var instance_domain = new CCodeMemberAccess.pointer ((CCodeExpression) ccodenode, "domain");
5035 var type_domain = new CCodeIdentifier (et.error_domain.get_upper_case_cname ());
5036 return new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, instance_domain, type_domain);
5037 } else {
5038 string type_check_func = get_type_check_function (type.data_type);
5039 if (type_check_func == null) {
5040 return new CCodeInvalidExpression ();
5042 var ccheck = new CCodeFunctionCall (new CCodeIdentifier (type_check_func));
5043 ccheck.add_argument ((CCodeExpression) ccodenode);
5044 return ccheck;
5048 string generate_array_contains_wrapper (ArrayType array_type) {
5049 string array_contains_func = "_vala_%s_array_contains".printf (array_type.element_type.get_lower_case_cname ());
5051 if (!add_wrapper (array_contains_func)) {
5052 return array_contains_func;
5055 var function = new CCodeFunction (array_contains_func, "gboolean");
5056 function.modifiers = CCodeModifiers.STATIC;
5058 function.add_parameter (new CCodeParameter ("stack", array_type.get_cname ()));
5059 function.add_parameter (new CCodeParameter ("stack_length", "int"));
5060 if (array_type.element_type is StructValueType) {
5061 function.add_parameter (new CCodeParameter ("needle", array_type.element_type.get_cname () + "*"));
5062 } else {
5063 function.add_parameter (new CCodeParameter ("needle", array_type.element_type.get_cname ()));
5066 push_function (function);
5068 ccode.add_declaration ("int", new CCodeVariableDeclarator ("i"));
5070 var cloop_initializer = new CCodeAssignment (new CCodeIdentifier ("i"), new CCodeConstant ("0"));
5071 var cloop_condition = new CCodeBinaryExpression (CCodeBinaryOperator.LESS_THAN, new CCodeIdentifier ("i"), new CCodeIdentifier ("stack_length"));
5072 var cloop_iterator = new CCodeUnaryExpression (CCodeUnaryOperator.POSTFIX_INCREMENT, new CCodeIdentifier ("i"));
5073 ccode.open_for (cloop_initializer, cloop_condition, cloop_iterator);
5075 var celement = new CCodeElementAccess (new CCodeIdentifier ("stack"), new CCodeIdentifier ("i"));
5076 var cneedle = new CCodeIdentifier ("needle");
5077 CCodeBinaryExpression cif_condition;
5078 if (array_type.element_type.compatible (string_type)) {
5079 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_strcmp0"));
5080 ccall.add_argument (celement);
5081 ccall.add_argument (cneedle);
5082 cif_condition = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, ccall, new CCodeConstant ("0"));
5083 } else if (array_type.element_type is StructValueType) {
5084 var equalfunc = generate_struct_equal_function ((Struct) array_type.element_type.data_type as Struct);
5085 var ccall = new CCodeFunctionCall (new CCodeIdentifier (equalfunc));
5086 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, celement));
5087 ccall.add_argument (cneedle);
5088 cif_condition = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, ccall, new CCodeConstant ("TRUE"));
5089 } else {
5090 cif_condition = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, cneedle, celement);
5093 ccode.open_if (cif_condition);
5094 ccode.add_return (new CCodeConstant ("TRUE"));
5095 ccode.close ();
5097 ccode.close ();
5099 ccode.add_return (new CCodeConstant ("FALSE"));
5101 pop_function ();
5103 cfile.add_function_declaration (function);
5104 cfile.add_function (function);
5106 return array_contains_func;
5109 public override void visit_type_check (TypeCheck expr) {
5110 generate_type_declaration (expr.type_reference, cfile);
5112 set_cvalue (expr, create_type_check (get_cvalue (expr.expression), expr.type_reference));
5113 if (get_cvalue (expr) is CCodeInvalidExpression) {
5114 Report.error (expr.source_reference, "type check expressions not supported for compact classes, structs, and enums");
5118 public override void visit_lambda_expression (LambdaExpression lambda) {
5119 // use instance position from delegate
5120 var dt = (DelegateType) lambda.target_type;
5121 lambda.method.cinstance_parameter_position = dt.delegate_symbol.cinstance_parameter_position;
5123 lambda.accept_children (this);
5125 bool expr_owned = lambda.value_type.value_owned;
5127 set_cvalue (lambda, new CCodeIdentifier (lambda.method.get_cname ()));
5129 var delegate_type = (DelegateType) lambda.target_type;
5130 if (lambda.method.closure) {
5131 int block_id = get_block_id (current_closure_block);
5132 var delegate_target = get_variable_cexpression ("_data%d_".printf (block_id));
5133 if (expr_owned || delegate_type.is_called_once) {
5134 var ref_call = new CCodeFunctionCall (new CCodeIdentifier ("block%d_data_ref".printf (block_id)));
5135 ref_call.add_argument (delegate_target);
5136 delegate_target = ref_call;
5137 set_delegate_target_destroy_notify (lambda, new CCodeIdentifier ("block%d_data_unref".printf (block_id)));
5138 } else {
5139 set_delegate_target_destroy_notify (lambda, new CCodeConstant ("NULL"));
5141 set_delegate_target (lambda, delegate_target);
5142 } else if (get_this_type () != null || in_constructor) {
5143 CCodeExpression delegate_target = get_result_cexpression ("self");
5144 if (expr_owned || delegate_type.is_called_once) {
5145 if (get_this_type () != null) {
5146 var ref_call = new CCodeFunctionCall (get_dup_func_expression (get_this_type (), lambda.source_reference));
5147 ref_call.add_argument (delegate_target);
5148 delegate_target = ref_call;
5149 set_delegate_target_destroy_notify (lambda, get_destroy_func_expression (get_this_type ()));
5150 } else {
5151 // in constructor
5152 var ref_call = new CCodeFunctionCall (new CCodeIdentifier ("g_object_ref"));
5153 ref_call.add_argument (delegate_target);
5154 delegate_target = ref_call;
5155 set_delegate_target_destroy_notify (lambda, new CCodeIdentifier ("g_object_unref"));
5157 } else {
5158 set_delegate_target_destroy_notify (lambda, new CCodeConstant ("NULL"));
5160 set_delegate_target (lambda, delegate_target);
5161 } else {
5162 set_delegate_target (lambda, new CCodeConstant ("NULL"));
5163 set_delegate_target_destroy_notify (lambda, new CCodeConstant ("NULL"));
5167 public CCodeExpression convert_from_generic_pointer (CCodeExpression cexpr, DataType actual_type) {
5168 var result = cexpr;
5169 if (is_reference_type_argument (actual_type) || is_nullable_value_type_argument (actual_type)) {
5170 result = new CCodeCastExpression (cexpr, actual_type.get_cname ());
5171 } else if (is_signed_integer_type_argument (actual_type)) {
5172 var cconv = new CCodeFunctionCall (new CCodeIdentifier ("GPOINTER_TO_INT"));
5173 cconv.add_argument (cexpr);
5174 result = cconv;
5175 } else if (is_unsigned_integer_type_argument (actual_type)) {
5176 var cconv = new CCodeFunctionCall (new CCodeIdentifier ("GPOINTER_TO_UINT"));
5177 cconv.add_argument (cexpr);
5178 result = cconv;
5180 return result;
5183 public CCodeExpression convert_to_generic_pointer (CCodeExpression cexpr, DataType actual_type) {
5184 var result = cexpr;
5185 if (is_signed_integer_type_argument (actual_type)) {
5186 var cconv = new CCodeFunctionCall (new CCodeIdentifier ("GINT_TO_POINTER"));
5187 cconv.add_argument (cexpr);
5188 result = cconv;
5189 } else if (is_unsigned_integer_type_argument (actual_type)) {
5190 var cconv = new CCodeFunctionCall (new CCodeIdentifier ("GUINT_TO_POINTER"));
5191 cconv.add_argument (cexpr);
5192 result = cconv;
5194 return result;
5197 // manage memory and implicit casts
5198 public CCodeExpression transform_expression (CCodeExpression source_cexpr, DataType? expression_type, DataType? target_type, Expression? expr = null) {
5199 var cexpr = source_cexpr;
5200 if (expression_type == null) {
5201 return cexpr;
5205 if (expression_type.value_owned
5206 && expression_type.floating_reference) {
5207 /* floating reference, sink it.
5209 var cl = expression_type.data_type as ObjectTypeSymbol;
5210 var sink_func = (cl != null) ? cl.get_ref_sink_function () : null;
5212 if (sink_func != null) {
5213 var csink = new CCodeFunctionCall (new CCodeIdentifier (sink_func));
5214 csink.add_argument (cexpr);
5216 cexpr = csink;
5217 } else {
5218 Report.error (null, "type `%s' does not support floating references".printf (expression_type.data_type.name));
5222 bool boxing = (expression_type is ValueType && !expression_type.nullable
5223 && target_type is ValueType && target_type.nullable);
5224 bool unboxing = (expression_type is ValueType && expression_type.nullable
5225 && target_type is ValueType && !target_type.nullable);
5227 bool gvalue_boxing = (context.profile == Profile.GOBJECT
5228 && target_type != null
5229 && target_type.data_type == gvalue_type
5230 && !(expression_type is NullType)
5231 && expression_type.get_type_id () != "G_TYPE_VALUE");
5232 bool gvariant_boxing = (context.profile == Profile.GOBJECT
5233 && target_type != null
5234 && target_type.data_type == gvariant_type
5235 && !(expression_type is NullType)
5236 && expression_type.data_type != gvariant_type);
5238 if (expression_type.value_owned
5239 && (target_type == null || !target_type.value_owned || boxing || unboxing)
5240 && !gvalue_boxing /* gvalue can assume ownership of value, no need to free it */) {
5241 // value leaked, destroy it
5242 var pointer_type = target_type as PointerType;
5243 if (pointer_type != null && !(pointer_type.base_type is VoidType)) {
5244 // manual memory management for non-void pointers
5245 // treat void* special to not leak memory with void* method parameters
5246 } else if (requires_destroy (expression_type)) {
5247 var decl = get_temp_variable (expression_type, true, expression_type, false);
5248 emit_temp_var (decl);
5249 temp_ref_vars.insert (0, decl);
5250 ccode.add_assignment (get_variable_cexpression (decl.name), cexpr);
5251 cexpr = get_variable_cexpression (decl.name);
5253 if (expression_type is ArrayType && expr != null) {
5254 var array_type = (ArrayType) expression_type;
5255 for (int dim = 1; dim <= array_type.rank; dim++) {
5256 var len_decl = new LocalVariable (int_type.copy (), get_array_length_cname (decl.name, dim));
5257 emit_temp_var (len_decl);
5258 ccode.add_assignment (get_variable_cexpression (len_decl.name), get_array_length_cexpression (expr, dim));
5260 } else if (expression_type is DelegateType && expr != null) {
5261 var target_decl = new LocalVariable (new PointerType (new VoidType ()), get_delegate_target_cname (decl.name));
5262 emit_temp_var (target_decl);
5263 var target_destroy_notify_decl = new LocalVariable (gdestroynotify_type, get_delegate_target_destroy_notify_cname (decl.name));
5264 emit_temp_var (target_destroy_notify_decl);
5265 CCodeExpression target_destroy_notify;
5266 ccode.add_assignment (get_variable_cexpression (target_decl.name), get_delegate_target_cexpression (expr, out target_destroy_notify));
5267 ccode.add_assignment (get_variable_cexpression (target_destroy_notify_decl.name), target_destroy_notify);
5273 if (target_type == null) {
5274 // value will be destroyed, no need for implicit casts
5275 return cexpr;
5278 if (gvalue_boxing) {
5279 // implicit conversion to GValue
5280 var decl = get_temp_variable (target_type, true, target_type);
5281 emit_temp_var (decl);
5283 if (!target_type.value_owned) {
5284 // boxed GValue leaked, destroy it
5285 temp_ref_vars.insert (0, decl);
5288 if (target_type.nullable) {
5289 var newcall = new CCodeFunctionCall (new CCodeIdentifier ("g_new0"));
5290 newcall.add_argument (new CCodeConstant ("GValue"));
5291 newcall.add_argument (new CCodeConstant ("1"));
5292 var newassignment = new CCodeAssignment (get_variable_cexpression (decl.name), newcall);
5293 ccode.add_expression (newassignment);
5296 var ccall = new CCodeFunctionCall (new CCodeIdentifier ("g_value_init"));
5297 if (target_type.nullable) {
5298 ccall.add_argument (get_variable_cexpression (decl.name));
5299 } else {
5300 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression (decl.name)));
5302 ccall.add_argument (new CCodeIdentifier (expression_type.get_type_id ()));
5303 ccode.add_expression (ccall);
5305 if (requires_destroy (expression_type)) {
5306 ccall = new CCodeFunctionCall (get_value_taker_function (expression_type));
5307 } else {
5308 ccall = new CCodeFunctionCall (get_value_setter_function (expression_type));
5310 if (target_type.nullable) {
5311 ccall.add_argument (get_variable_cexpression (decl.name));
5312 } else {
5313 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression (decl.name)));
5315 if (expression_type.is_real_non_null_struct_type ()) {
5316 ccall.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cexpr));
5317 } else {
5318 ccall.add_argument (cexpr);
5321 ccode.add_expression (ccall);
5323 cexpr = get_variable_cexpression (decl.name);
5325 return cexpr;
5326 } else if (gvariant_boxing) {
5327 // implicit conversion to GVariant
5328 string variant_func = "_variant_new%d".printf (++next_variant_function_id);
5330 var ccall = new CCodeFunctionCall (new CCodeIdentifier (variant_func));
5331 ccall.add_argument (cexpr);
5333 var cfunc = new CCodeFunction (variant_func, "GVariant*");
5334 cfunc.modifiers = CCodeModifiers.STATIC;
5335 cfunc.add_parameter (new CCodeParameter ("value", expression_type.get_cname ()));
5337 if (expression_type is ArrayType) {
5338 // return array length if appropriate
5339 var array_type = (ArrayType) expression_type;
5341 for (int dim = 1; dim <= array_type.rank; dim++) {
5342 ccall.add_argument (get_array_length_cexpression (expr, dim));
5343 cfunc.add_parameter (new CCodeParameter (get_array_length_cname ("value", dim), "gint"));
5347 push_function (cfunc);
5349 var result = serialize_expression (expression_type, new CCodeIdentifier ("value"));
5351 // sink floating reference
5352 var sink = new CCodeFunctionCall (new CCodeIdentifier ("g_variant_ref_sink"));
5353 sink.add_argument (result);
5354 ccode.add_return (sink);
5356 pop_function ();
5358 cfile.add_function_declaration (cfunc);
5359 cfile.add_function (cfunc);
5361 return ccall;
5362 } else if (boxing) {
5363 // value needs to be boxed
5365 var unary = cexpr as CCodeUnaryExpression;
5366 if (unary != null && unary.operator == CCodeUnaryOperator.POINTER_INDIRECTION) {
5367 // *expr => expr
5368 cexpr = unary.inner;
5369 } else if (cexpr is CCodeIdentifier || cexpr is CCodeMemberAccess) {
5370 cexpr = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cexpr);
5371 } else {
5372 var decl = get_temp_variable (expression_type, expression_type.value_owned, expression_type, false);
5373 emit_temp_var (decl);
5375 ccode.add_assignment (get_variable_cexpression (decl.name), cexpr);
5376 cexpr = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression (decl.name));
5378 } else if (unboxing) {
5379 // unbox value
5381 cexpr = new CCodeUnaryExpression (CCodeUnaryOperator.POINTER_INDIRECTION, cexpr);
5382 } else {
5383 cexpr = get_implicit_cast_expression (cexpr, expression_type, target_type, expr);
5386 if (target_type.value_owned && (!expression_type.value_owned || boxing || unboxing)) {
5387 // need to copy value
5388 if (requires_copy (target_type) && !(expression_type is NullType)) {
5389 CodeNode node = expr;
5390 if (node == null) {
5391 node = expression_type;
5394 var decl = get_temp_variable (target_type, true, node, false);
5395 emit_temp_var (decl);
5396 ccode.add_assignment (get_variable_cexpression (decl.name), get_ref_cexpression (target_type, cexpr, expr, node));
5397 cexpr = get_variable_cexpression (decl.name);
5401 return cexpr;
5404 public virtual CCodeExpression get_implicit_cast_expression (CCodeExpression source_cexpr, DataType? expression_type, DataType? target_type, Expression? expr = null) {
5405 var cexpr = source_cexpr;
5407 if (expression_type.data_type != null && expression_type.data_type == target_type.data_type) {
5408 // same type, no cast required
5409 return cexpr;
5412 if (expression_type is NullType) {
5413 // null literal, no cast required when not converting to generic type pointer
5414 return cexpr;
5417 generate_type_declaration (target_type, cfile);
5419 var cl = target_type.data_type as Class;
5420 var iface = target_type.data_type as Interface;
5421 if (context.checking && (iface != null || (cl != null && !cl.is_compact))) {
5422 // checked cast for strict subtypes of GTypeInstance
5423 return generate_instance_cast (cexpr, target_type.data_type);
5424 } else if (target_type.data_type != null && expression_type.get_cname () != target_type.get_cname ()) {
5425 var st = target_type.data_type as Struct;
5426 if (target_type.data_type.is_reference_type () || (st != null && st.is_simple_type ())) {
5427 // don't cast non-simple structs
5428 return new CCodeCastExpression (cexpr, target_type.get_cname ());
5429 } else {
5430 return cexpr;
5432 } else {
5433 return cexpr;
5437 public void store_property (Property prop, Expression? instance, TargetValue value) {
5438 if (instance is BaseAccess) {
5439 if (prop.base_property != null) {
5440 var base_class = (Class) prop.base_property.parent_symbol;
5441 var vcast = new CCodeFunctionCall (new CCodeIdentifier ("%s_CLASS".printf (base_class.get_upper_case_cname (null))));
5442 vcast.add_argument (new CCodeIdentifier ("%s_parent_class".printf (current_class.get_lower_case_cname (null))));
5444 var ccall = new CCodeFunctionCall (new CCodeMemberAccess.pointer (vcast, "set_%s".printf (prop.name)));
5445 ccall.add_argument ((CCodeExpression) get_ccodenode (instance));
5446 ccall.add_argument (get_cvalue_ (value));
5448 ccode.add_expression (ccall);
5449 } else if (prop.base_interface_property != null) {
5450 var base_iface = (Interface) prop.base_interface_property.parent_symbol;
5451 string parent_iface_var = "%s_%s_parent_iface".printf (current_class.get_lower_case_cname (null), base_iface.get_lower_case_cname (null));
5453 var ccall = new CCodeFunctionCall (new CCodeMemberAccess.pointer (new CCodeIdentifier (parent_iface_var), "set_%s".printf (prop.name)));
5454 ccall.add_argument ((CCodeExpression) get_ccodenode (instance));
5455 ccall.add_argument (get_cvalue_ (value));
5457 ccode.add_expression (ccall);
5459 return;
5462 var set_func = "g_object_set";
5464 var base_property = prop;
5465 if (!prop.no_accessor_method) {
5466 if (prop.base_property != null) {
5467 base_property = prop.base_property;
5468 } else if (prop.base_interface_property != null) {
5469 base_property = prop.base_interface_property;
5472 if (prop is DynamicProperty) {
5473 set_func = get_dynamic_property_setter_cname ((DynamicProperty) prop);
5474 } else {
5475 generate_property_accessor_declaration (base_property.set_accessor, cfile);
5476 set_func = base_property.set_accessor.get_cname ();
5478 if (!prop.external && prop.external_package) {
5479 // internal VAPI properties
5480 // only add them once per source file
5481 if (add_generated_external_symbol (prop)) {
5482 visit_property (prop);
5488 var ccall = new CCodeFunctionCall (new CCodeIdentifier (set_func));
5490 if (prop.binding == MemberBinding.INSTANCE) {
5491 /* target instance is first argument */
5492 var cinstance = (CCodeExpression) get_ccodenode (instance);
5494 if (prop.parent_symbol is Struct) {
5495 // we need to pass struct instance by reference
5496 var unary = cinstance as CCodeUnaryExpression;
5497 if (unary != null && unary.operator == CCodeUnaryOperator.POINTER_INDIRECTION) {
5498 // *expr => expr
5499 cinstance = unary.inner;
5500 } else if (cinstance is CCodeIdentifier || cinstance is CCodeMemberAccess) {
5501 cinstance = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cinstance);
5502 } else {
5503 // if instance is e.g. a function call, we can't take the address of the expression
5504 // (tmp = expr, &tmp)
5506 var temp_var = get_temp_variable (instance.target_type, true, null, false);
5507 emit_temp_var (temp_var);
5508 ccode.add_assignment (get_variable_cexpression (temp_var.name), cinstance);
5510 cinstance = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, get_variable_cexpression (temp_var.name));
5514 ccall.add_argument (cinstance);
5517 if (prop.no_accessor_method) {
5518 /* property name is second argument of g_object_set */
5519 ccall.add_argument (prop.get_canonical_cconstant ());
5522 var cexpr = get_cvalue_ (value);
5524 if (prop.property_type.is_real_non_null_struct_type ()) {
5525 cexpr = new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, cexpr);
5528 var array_type = prop.property_type as ArrayType;
5530 if (array_type != null && !prop.no_array_length) {
5531 var temp_var = get_temp_variable (prop.property_type, true, null, false);
5532 emit_temp_var (temp_var);
5533 ccode.add_assignment (get_variable_cexpression (temp_var.name), cexpr);
5534 ccall.add_argument (get_variable_cexpression (temp_var.name));
5535 } else {
5536 ccall.add_argument (cexpr);
5539 if (array_type != null && !prop.no_array_length) {
5540 for (int dim = 1; dim <= array_type.rank; dim++) {
5541 ccall.add_argument (get_array_length_cvalue (value, dim));
5543 } else if (prop.property_type is DelegateType) {
5544 var delegate_type = (DelegateType) prop.property_type;
5545 if (delegate_type.delegate_symbol.has_target) {
5546 ccall.add_argument (get_delegate_target_cvalue (value));
5550 if (prop.no_accessor_method) {
5551 ccall.add_argument (new CCodeConstant ("NULL"));
5554 ccode.add_expression (ccall);
5557 public bool add_wrapper (string wrapper_name) {
5558 return wrappers.add (wrapper_name);
5561 public bool add_generated_external_symbol (Symbol external_symbol) {
5562 return generated_external_symbols.add (external_symbol);
5565 public static DataType get_data_type_for_symbol (TypeSymbol sym) {
5566 DataType type = null;
5568 if (sym is Class) {
5569 type = new ObjectType ((Class) sym);
5570 } else if (sym is Interface) {
5571 type = new ObjectType ((Interface) sym);
5572 } else if (sym is Struct) {
5573 var st = (Struct) sym;
5574 if (st.is_boolean_type ()) {
5575 type = new BooleanType (st);
5576 } else if (st.is_integer_type ()) {
5577 type = new IntegerType (st);
5578 } else if (st.is_floating_type ()) {
5579 type = new FloatingType (st);
5580 } else {
5581 type = new StructValueType (st);
5583 } else if (sym is Enum) {
5584 type = new EnumValueType ((Enum) sym);
5585 } else if (sym is ErrorDomain) {
5586 type = new ErrorType ((ErrorDomain) sym, null);
5587 } else if (sym is ErrorCode) {
5588 type = new ErrorType ((ErrorDomain) sym.parent_symbol, (ErrorCode) sym);
5589 } else {
5590 Report.error (null, "internal error: `%s' is not a supported type".printf (sym.get_full_name ()));
5591 return new InvalidType ();
5594 return type;
5597 public CCodeExpression? default_value_for_type (DataType type, bool initializer_expression) {
5598 var st = type.data_type as Struct;
5599 var array_type = type as ArrayType;
5600 if (initializer_expression && !type.nullable &&
5601 ((st != null && !st.is_simple_type ()) ||
5602 (array_type != null && array_type.fixed_length))) {
5603 // 0-initialize struct with struct initializer { 0 }
5604 // only allowed as initializer expression in C
5605 var clist = new CCodeInitializerList ();
5606 clist.append (new CCodeConstant ("0"));
5607 return clist;
5608 } else if ((type.data_type != null && type.data_type.is_reference_type ())
5609 || type.nullable
5610 || type is PointerType || type is DelegateType
5611 || (array_type != null && !array_type.fixed_length)) {
5612 return new CCodeConstant ("NULL");
5613 } else if (type.data_type != null && type.data_type.get_default_value () != null) {
5614 return new CCodeConstant (type.data_type.get_default_value ());
5615 } else if (type.type_parameter != null) {
5616 return new CCodeConstant ("NULL");
5617 } else if (type is ErrorType) {
5618 return new CCodeConstant ("NULL");
5620 return null;
5623 private void create_property_type_check_statement (Property prop, bool check_return_type, TypeSymbol t, bool non_null, string var_name) {
5624 if (check_return_type) {
5625 create_type_check_statement (prop, prop.property_type, t, non_null, var_name);
5626 } else {
5627 create_type_check_statement (prop, new VoidType (), t, non_null, var_name);
5631 public void create_type_check_statement (CodeNode method_node, DataType ret_type, TypeSymbol t, bool non_null, string var_name) {
5632 var ccheck = new CCodeFunctionCall ();
5634 if (!context.assert) {
5635 return;
5636 } else if (context.checking && ((t is Class && !((Class) t).is_compact) || t is Interface)) {
5637 var ctype_check = new CCodeFunctionCall (new CCodeIdentifier (get_type_check_function (t)));
5638 ctype_check.add_argument (new CCodeIdentifier (var_name));
5640 CCodeExpression cexpr = ctype_check;
5641 if (!non_null) {
5642 var cnull = new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, new CCodeIdentifier (var_name), new CCodeConstant ("NULL"));
5644 cexpr = new CCodeBinaryExpression (CCodeBinaryOperator.OR, cnull, ctype_check);
5646 ccheck.add_argument (cexpr);
5647 } else if (!non_null) {
5648 return;
5649 } else if (t == glist_type || t == gslist_type) {
5650 // NULL is empty list
5651 return;
5652 } else {
5653 var cnonnull = new CCodeBinaryExpression (CCodeBinaryOperator.INEQUALITY, new CCodeIdentifier (var_name), new CCodeConstant ("NULL"));
5654 ccheck.add_argument (cnonnull);
5657 var cm = method_node as CreationMethod;
5658 if (cm != null && cm.parent_symbol is ObjectTypeSymbol) {
5659 ccheck.call = new CCodeIdentifier ("g_return_val_if_fail");
5660 ccheck.add_argument (new CCodeConstant ("NULL"));
5661 } else if (ret_type is VoidType) {
5662 /* void function */
5663 ccheck.call = new CCodeIdentifier ("g_return_if_fail");
5664 } else {
5665 ccheck.call = new CCodeIdentifier ("g_return_val_if_fail");
5667 var cdefault = default_value_for_type (ret_type, false);
5668 if (cdefault != null) {
5669 ccheck.add_argument (cdefault);
5670 } else {
5671 return;
5675 ccode.add_expression (ccheck);
5678 public int get_param_pos (double param_pos, bool ellipsis = false) {
5679 if (!ellipsis) {
5680 if (param_pos >= 0) {
5681 return (int) (param_pos * 1000);
5682 } else {
5683 return (int) ((100 + param_pos) * 1000);
5685 } else {
5686 if (param_pos >= 0) {
5687 return (int) ((100 + param_pos) * 1000);
5688 } else {
5689 return (int) ((200 + param_pos) * 1000);
5694 public CCodeExpression? get_ccodenode (Expression node) {
5695 if (get_cvalue (node) == null) {
5696 node.emit (this);
5698 return get_cvalue (node);
5701 public override void visit_class (Class cl) {
5704 public void create_postcondition_statement (Expression postcondition) {
5705 var cassert = new CCodeFunctionCall (new CCodeIdentifier ("g_warn_if_fail"));
5707 postcondition.emit (this);
5709 cassert.add_argument (get_cvalue (postcondition));
5711 ccode.add_expression (cassert);
5714 public virtual bool is_gobject_property (Property prop) {
5715 return false;
5718 public DataType? get_this_type () {
5719 if (current_method != null && current_method.binding == MemberBinding.INSTANCE) {
5720 return current_method.this_parameter.variable_type;
5721 } else if (current_property_accessor != null && current_property_accessor.prop.binding == MemberBinding.INSTANCE) {
5722 return current_property_accessor.prop.this_parameter.variable_type;
5724 return null;
5727 public CCodeFunctionCall generate_instance_cast (CCodeExpression expr, TypeSymbol type) {
5728 var result = new CCodeFunctionCall (new CCodeIdentifier (type.get_upper_case_cname (null)));
5729 result.add_argument (expr);
5730 return result;
5733 void generate_struct_destroy_function (Struct st) {
5734 if (cfile.add_declaration (st.get_destroy_function ())) {
5735 // only generate function once per source file
5736 return;
5739 var function = new CCodeFunction (st.get_destroy_function (), "void");
5740 function.modifiers = CCodeModifiers.STATIC;
5741 function.add_parameter (new CCodeParameter ("self", st.get_cname () + "*"));
5743 push_context (new EmitContext ());
5744 push_function (function);
5746 var this_value = load_this_parameter (st);
5747 foreach (Field f in st.get_fields ()) {
5748 if (f.binding == MemberBinding.INSTANCE) {
5749 if (requires_destroy (f.variable_type)) {
5750 ccode.add_expression (destroy_field (f, this_value));
5755 pop_function ();
5756 pop_context ();
5758 cfile.add_function_declaration (function);
5759 cfile.add_function (function);
5762 void generate_struct_copy_function (Struct st) {
5763 if (cfile.add_declaration (st.get_copy_function ())) {
5764 // only generate function once per source file
5765 return;
5768 var function = new CCodeFunction (st.get_copy_function (), "void");
5769 function.modifiers = CCodeModifiers.STATIC;
5770 function.add_parameter (new CCodeParameter ("self", "const " + st.get_cname () + "*"));
5771 function.add_parameter (new CCodeParameter ("dest", st.get_cname () + "*"));
5773 push_context (new EmitContext ());
5774 push_function (function);
5776 foreach (Field f in st.get_fields ()) {
5777 if (f.binding == MemberBinding.INSTANCE) {
5778 CCodeExpression copy = new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), f.name);
5779 if (requires_copy (f.variable_type)) {
5780 var this_access = new MemberAccess.simple ("this");
5781 this_access.value_type = get_data_type_for_symbol ((TypeSymbol) f.parent_symbol);
5782 set_cvalue (this_access, new CCodeIdentifier ("(*self)"));
5783 var ma = new MemberAccess (this_access, f.name);
5784 ma.symbol_reference = f;
5785 ma.value_type = f.variable_type.copy ();
5786 visit_member_access (ma);
5787 copy = get_ref_cexpression (f.variable_type, copy, ma, f);
5789 var dest = new CCodeMemberAccess.pointer (new CCodeIdentifier ("dest"), f.name);
5791 var array_type = f.variable_type as ArrayType;
5792 if (array_type != null && array_type.fixed_length) {
5793 // fixed-length (stack-allocated) arrays
5794 cfile.add_include ("string.h");
5796 var sizeof_call = new CCodeFunctionCall (new CCodeIdentifier ("sizeof"));
5797 sizeof_call.add_argument (new CCodeIdentifier (array_type.element_type.get_cname ()));
5798 var size = new CCodeBinaryExpression (CCodeBinaryOperator.MUL, new CCodeConstant ("%d".printf (array_type.length)), sizeof_call);
5800 var array_copy_call = new CCodeFunctionCall (new CCodeIdentifier ("memcpy"));
5801 array_copy_call.add_argument (dest);
5802 array_copy_call.add_argument (copy);
5803 array_copy_call.add_argument (size);
5804 ccode.add_expression (array_copy_call);
5805 } else {
5806 ccode.add_assignment (dest, copy);
5808 if (array_type != null && !f.no_array_length) {
5809 for (int dim = 1; dim <= array_type.rank; dim++) {
5810 var len_src = new CCodeMemberAccess.pointer (new CCodeIdentifier ("self"), get_array_length_cname (f.name, dim));
5811 var len_dest = new CCodeMemberAccess.pointer (new CCodeIdentifier ("dest"), get_array_length_cname (f.name, dim));
5812 ccode.add_assignment (len_dest, len_src);
5819 pop_function ();
5820 pop_context ();
5822 cfile.add_function_declaration (function);
5823 cfile.add_function (function);
5826 public void return_default_value (DataType return_type) {
5827 ccode.add_return (default_value_for_type (return_type, false));
5830 public virtual string? get_custom_creturn_type (Method m) {
5831 return null;
5834 public virtual void generate_dynamic_method_wrapper (DynamicMethod method) {
5837 public virtual bool method_has_wrapper (Method method) {
5838 return false;
5841 public virtual CCodeFunctionCall get_param_spec (Property prop) {
5842 return new CCodeFunctionCall (new CCodeIdentifier (""));
5845 public virtual CCodeFunctionCall get_signal_creation (Signal sig, TypeSymbol type) {
5846 return new CCodeFunctionCall (new CCodeIdentifier (""));
5849 public virtual void register_dbus_info (CCodeBlock block, ObjectTypeSymbol bindable) {
5852 public virtual string get_dynamic_property_getter_cname (DynamicProperty node) {
5853 Report.error (node.source_reference, "dynamic properties are not supported for %s".printf (node.dynamic_type.to_string ()));
5854 return "";
5857 public virtual string get_dynamic_property_setter_cname (DynamicProperty node) {
5858 Report.error (node.source_reference, "dynamic properties are not supported for %s".printf (node.dynamic_type.to_string ()));
5859 return "";
5862 public virtual string get_dynamic_signal_cname (DynamicSignal node) {
5863 return "";
5866 public virtual string get_dynamic_signal_connect_wrapper_name (DynamicSignal node) {
5867 return "";
5870 public virtual string get_dynamic_signal_connect_after_wrapper_name (DynamicSignal node) {
5871 return "";
5874 public virtual string get_dynamic_signal_disconnect_wrapper_name (DynamicSignal node) {
5875 return "";
5878 public virtual string get_array_length_cname (string array_cname, int dim) {
5879 return "";
5882 public virtual string get_parameter_array_length_cname (Parameter param, int dim) {
5883 return "";
5886 public virtual CCodeExpression get_array_length_cexpression (Expression array_expr, int dim = -1) {
5887 return new CCodeConstant ("");
5890 public virtual CCodeExpression get_array_length_cvalue (TargetValue value, int dim = -1) {
5891 return new CCodeInvalidExpression ();
5894 public virtual string get_array_size_cname (string array_cname) {
5895 return "";
5898 public virtual void add_simple_check (CodeNode node, bool always_fails = false) {
5901 public virtual string generate_ready_function (Method m) {
5902 return "";
5905 public CCodeExpression? get_cvalue (Expression expr) {
5906 if (expr.target_value == null) {
5907 return null;
5909 var glib_value = (GLibValue) expr.target_value;
5910 return glib_value.cvalue;
5913 public CCodeExpression? get_cvalue_ (TargetValue value) {
5914 var glib_value = (GLibValue) value;
5915 return glib_value.cvalue;
5918 public void set_cvalue (Expression expr, CCodeExpression? cvalue) {
5919 var glib_value = (GLibValue) expr.target_value;
5920 if (glib_value == null) {
5921 glib_value = new GLibValue (expr.value_type);
5922 expr.target_value = glib_value;
5924 glib_value.cvalue = cvalue;
5927 public CCodeExpression? get_array_size_cvalue (TargetValue value) {
5928 var glib_value = (GLibValue) value;
5929 return glib_value.array_size_cvalue;
5932 public void set_array_size_cvalue (TargetValue value, CCodeExpression? cvalue) {
5933 var glib_value = (GLibValue) value;
5934 glib_value.array_size_cvalue = cvalue;
5937 public CCodeExpression? get_delegate_target (Expression expr) {
5938 if (expr.target_value == null) {
5939 return null;
5941 var glib_value = (GLibValue) expr.target_value;
5942 return glib_value.delegate_target_cvalue;
5945 public void set_delegate_target (Expression expr, CCodeExpression? delegate_target) {
5946 var glib_value = (GLibValue) expr.target_value;
5947 if (glib_value == null) {
5948 glib_value = new GLibValue (expr.value_type);
5949 expr.target_value = glib_value;
5951 glib_value.delegate_target_cvalue = delegate_target;
5954 public CCodeExpression? get_delegate_target_destroy_notify (Expression expr) {
5955 if (expr.target_value == null) {
5956 return null;
5958 var glib_value = (GLibValue) expr.target_value;
5959 return glib_value.delegate_target_destroy_notify_cvalue;
5962 public void set_delegate_target_destroy_notify (Expression expr, CCodeExpression? destroy_notify) {
5963 var glib_value = (GLibValue) expr.target_value;
5964 if (glib_value == null) {
5965 glib_value = new GLibValue (expr.value_type);
5966 expr.target_value = glib_value;
5968 glib_value.delegate_target_destroy_notify_cvalue = destroy_notify;
5971 public void append_array_length (Expression expr, CCodeExpression size) {
5972 var glib_value = (GLibValue) expr.target_value;
5973 if (glib_value == null) {
5974 glib_value = new GLibValue (expr.value_type);
5975 expr.target_value = glib_value;
5977 glib_value.append_array_length_cvalue (size);
5980 public List<CCodeExpression>? get_array_lengths (Expression expr) {
5981 var glib_value = (GLibValue) expr.target_value;
5982 if (glib_value == null) {
5983 glib_value = new GLibValue (expr.value_type);
5984 expr.target_value = glib_value;
5986 return glib_value.array_length_cvalues;
5990 public class Vala.GLibValue : TargetValue {
5991 public CCodeExpression cvalue;
5993 public List<CCodeExpression> array_length_cvalues;
5994 public CCodeExpression? array_size_cvalue;
5996 public CCodeExpression? delegate_target_cvalue;
5997 public CCodeExpression? delegate_target_destroy_notify_cvalue;
5999 public GLibValue (DataType? value_type = null, CCodeExpression? cvalue = null) {
6000 base (value_type);
6001 this.cvalue = cvalue;
6004 public void append_array_length_cvalue (CCodeExpression length_cvalue) {
6005 if (array_length_cvalues == null) {
6006 array_length_cvalues = new ArrayList<CCodeExpression> ();
6008 array_length_cvalues.add (length_cvalue);
6011 public GLibValue copy () {
6012 var result = new GLibValue (value_type.copy (), cvalue);
6014 if (array_length_cvalues != null) {
6015 foreach (var cexpr in array_length_cvalues) {
6016 result.append_array_length_cvalue (cexpr);
6019 result.array_size_cvalue = array_size_cvalue;
6021 result.delegate_target_cvalue = delegate_target_cvalue;
6022 result.delegate_target_destroy_notify_cvalue = delegate_target_destroy_notify_cvalue;
6024 return result;