summaryrefslogtreecommitdiff
path: root/init-check.c
blob: 2b8cb8f907ae9390a0c16112d27ca5ff5c96bfcd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* Oort
 * Copyright 2007, Soren Sandmann Pedersen
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/* Check that variables are initialized before they are used.
 */

#include "ast.h"

static void
compute_initialized (node_t *node, gpointer data)
{
    gboolean *changed = data;
    set_t *tmp;
    GList *list, *free_me;

    list = free_me = node_list_predecessors (node);
    if (!list)
	tmp = set_new();
    else
	tmp = set_new_full();
    while (list)
    {
	node_t *pred = list->data;

	if (pred->common.init_vars)
	    set_intersect (tmp, pred->common.init_vars);

	list = list->next;
    }
    g_list_free (free_me);

    if (node->common.type == NODE_STORE)
	set_add (tmp, node->store.definition);

    if (node->common.type == NODE_INIT)
	set_add (tmp, node->initialize.definition);

    if (!node->common.init_vars)
    {
	node->common.init_vars = tmp;
	*changed = TRUE;
    }
    else if (!set_equal (node->common.init_vars, tmp))
    {
	set_free (node->common.init_vars);
	node->common.init_vars = tmp;
	*changed = TRUE;
    }
    else
    {
	set_free (tmp);
    }
}

gboolean
init_check (ast_t *ast)
{
    gboolean changed;
    node_t **nodes;
    int i;

    do
    {
	changed = FALSE;
	node_breadth_first (ast->program.enter, compute_initialized, &changed);
    }
    while (changed);

    nodes = node_list_all (ast->program.enter);

    for (i = 0; nodes[i] != NULL; ++i)
    {
	node_t *node = nodes[i];
	if (node->common.type == NODE_LOAD)
	{
	    ast_variable_definition_t *definition = node->load.definition;

	    if (!set_contains (node->common.init_vars, definition) &&
		!definition->field)
	    {
		return report_error ("Uninitialized variable %s\n",
				     definition->name);
	    }
	}
    }

    g_free (nodes);

    return TRUE;
}