1/* valatemplate.vala
2 *
3 * Copyright (C) 2009-2010  Jürg Billeter
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 * Lesser General Public License for more details.
14
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
18 *
19 * Author:
20 * 	Jürg Billeter <j@bitron.ch>
21 */
22
23
24public class Vala.Template : Expression {
25	private List<Expression> expression_list = new ArrayList<Expression> ();
26
27	public Template (SourceReference? source_reference = null) {
28		this.source_reference = source_reference;
29	}
30
31	public override void accept (CodeVisitor visitor) {
32		visitor.visit_template (this);
33	}
34
35	public override void accept_children (CodeVisitor visitor) {
36		foreach (var expr in expression_list) {
37			expr.accept (visitor);
38		}
39	}
40
41	public void add_expression (Expression expr) {
42		expression_list.add (expr);
43		expr.parent_node = this;
44	}
45
46	public unowned List<Expression> get_expressions () {
47		return expression_list;
48	}
49
50	public override bool is_pure () {
51		return false;
52	}
53
54	Expression stringify (Expression expr) {
55		if (expr is StringLiteral) {
56			return expr;
57		} else {
58			return new MethodCall (new MemberAccess (expr, "to_string", expr.source_reference), expr.source_reference);
59		}
60	}
61
62	public override void replace_expression (Expression old_node, Expression new_node) {
63		int index = expression_list.index_of (old_node);
64		if (index >= 0) {
65			expression_list[index] = new_node;
66			new_node.parent_node = this;
67		}
68	}
69
70	public override bool check (CodeContext context) {
71		if (checked) {
72			return !error;
73		}
74
75		checked = true;
76
77		Expression expr;
78
79		if (expression_list.size == 0) {
80			expr = new StringLiteral ("\"\"", source_reference);
81		} else {
82			expr = stringify (expression_list[0]);
83			if (expression_list.size > 1) {
84				var concat = new MethodCall (new MemberAccess (expr, "concat", source_reference), source_reference);
85				for (int i = 1; i < expression_list.size; i++) {
86					concat.add_argument (stringify (expression_list[i]));
87				}
88				expr = concat;
89			}
90		}
91		expr.target_type = target_type;
92
93		context.analyzer.replaced_nodes.add (this);
94		parent_node.replace_expression (this, expr);
95		return expr.check (context);
96	}
97}
98
99