summaryrefslogtreecommitdiff
path: root/vala/valaintegertype.vala
blob: a5b189639495d28af2d57849f2247d453120ad21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* valaintegertype.vala
 *
 * Copyright (C) 2008-2009  Jürg Billeter
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

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

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

using GLib;

/**
 * An integer type.
 */
public class Vala.IntegerType : ValueType {
	string? literal_value;
	string? literal_type_name;

	public IntegerType (Struct type_symbol, string? literal_value = null, string? literal_type_name = null, SourceReference? source_reference = null) {
		base (type_symbol, source_reference);
		this.literal_value = literal_value;
		this.literal_type_name = literal_type_name;
	}

	public override DataType copy () {
		var result = new IntegerType ((Struct) type_symbol, literal_value, literal_type_name, source_reference);
		result.value_owned = value_owned;
		result.nullable = nullable;
		return result;
	}

	public override bool compatible (DataType target_type) {
		if (target_type.type_symbol is Struct && literal_type_name == "int") {
			// int literals are implicitly convertible to integer types
			// of a lower rank if the value of the literal is within
			// the range of the target type
			var target_st = (Struct) target_type.type_symbol;
			if (target_st.is_integer_type ()) {
				var int_attr = target_st.get_attribute ("IntegerType");
				if (int_attr != null && int_attr.has_argument ("min") && int_attr.has_argument ("max")) {
					int val = int.parse (literal_value);
					return (val >= int_attr.get_integer ("min") && val <= int_attr.get_integer ("max"));
				} else {
					// assume to be compatible if the target type doesn't specify limits
					return true;
				}
			}
		} else if (target_type.type_symbol is Enum && (literal_type_name == "int" || literal_type_name == "uint")) {
			// allow implicit conversion from 0 to enum and flags types
			if (int.parse (literal_value) == 0) {
				return true;
			}
		}

		return base.compatible (target_type);
	}
}