1/* valaregexliteral.vala
2 *
3 * Copyright (C) 2010  Jukka-Pekka Iivonen
4 * Copyright (C) 2010  Jürg Billeter
5 *
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.
10
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.
15
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
19 *
20 * Author:
21 * 	Jukka-Pekka Iivonen <jp0409@jippii.fi>
22 */
23
24using GLib;
25
26/**
27 * Represents a regular expression literal in the source code.
28 */
29public class Vala.RegexLiteral : Literal {
30	/**
31	 * The literal value.
32	 */
33	public string value { get; set; }
34
35	/**
36	 * Creates a new regular expression literal.
37	 *
38	 * @param value             the literal value
39	 * @param source_reference  reference to source code
40	 * @return                  newly created string literal
41	 */
42	public RegexLiteral (string value, SourceReference? source_reference = null) {
43		this.value = value;
44		this.source_reference = source_reference;
45	}
46
47	public override void accept (CodeVisitor visitor) {
48		visitor.visit_regex_literal (this);
49
50		visitor.visit_expression (this);
51	}
52
53	public override bool is_pure () {
54		return true;
55	}
56
57	public override bool is_non_null () {
58		return true;
59	}
60
61	public override string to_string () {
62		return value;
63	}
64
65	public override bool check (CodeContext context) {
66		if (checked) {
67			return !error;
68		}
69
70		checked = true;
71
72		try {
73			var regex = new GLib.Regex (value);
74			if (regex != null) { /* Regex is valid. */ }
75		} catch (RegexError err) {
76			error = true;
77			Report.error (source_reference, "Invalid regular expression `%s'.".printf (value));
78			return false;
79		}
80
81		value_type = context.analyzer.regex_type.copy ();
82
83		return !error;
84	}
85
86	public override void emit (CodeGenerator codegen) {
87		codegen.visit_regex_literal (this);
88
89		codegen.visit_expression (this);
90	}
91}
92
93