summaryrefslogtreecommitdiff
path: root/identify.c
blob: 1fd993ab934ae98838b74cc8bf9cd6bd7b03e195 (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
106
107
108
109
110
111
112
113
114
#include "identify.h"
#include "token.h"
#include <stddef.h>

static int
identify_dec(Token **list, unsigned int type)
{
	if (*list == NULL || (*list)->next == NULL)
		return 0;
	if ((*list)->type != type)
		return 0;
	for (Token *e = (*list)->next; e != NULL; e = e->next)
		if (e->type != TOK_WORD)
			return 0;

	// Delete redundant first element (always the type keyword).
	token_delete(list, *list);
	return 1;
}

static int
identify_control(Token **list, unsigned int type)
{
	if (token_len(*list) != 3)
		return 0;
	if ((*list)->type != type)
		return 0;
	// TODO: Add checks for condition type.
	if (!token_isgroup((*list)->next->next, GROUP_SCOPE))
		return 0;
	token_delete(list, *list);
	return 1;
}

void
identify(Token *list, int (*fun)(Token**), unsigned int type, int recurse)
{
	if (recurse)
		for (Token *e = list; e != NULL; e = e->next)
			if (e->type == TOK_GROUP)
				identify(e->group.tokens, fun, type, 1);

	for (Token *e = list; e != NULL; e = e->next)
		if (token_isgroup(e, GROUP_ATOM) && fun(&e->group.tokens))
			e->group.type = type;
}

int
identify_function(Token **list)
{
	for (Token *e = *list; e != NULL; e = e->next) {
		if (e->next == NULL && !token_isgroup(e, GROUP_SCOPE))
			return 0;
		if (e->next != NULL && e->type != TOK_WORD)
			return 0;
	}
	return 1;
}

int
identify_let(Token **list)
{
	return identify_dec(list, TOK_KW_LET);
}

int
identify_return(Token **list)
{
	if (token_len(*list) != 2)
		return 0;
	if ((*list)->type != TOK_KW_RETURN)
		return 1;
	// TODO: Add checks for value type.
	token_delete(list, *list);
	return 1;
}

int
identify_assign(Token **list)
{
	if (token_len(*list) != 3)
		return 0;
	if ((*list)->next->type != TOK_ASSIGN)
		return 0;
	// TODO: Add checks for LH and RH value types.
	token_delete(list, (*list)->next);
	return 1;
}

int
identify_if(Token **list)
{
	return identify_control(list, TOK_KW_IF);
}

int
identify_else(Token **list)
{
	return identify_control(list, TOK_KW_ELSE);
}

int
identify_while(Token **list)
{
	return identify_control(list, TOK_KW_WHILE);
}

int
identify_expression(Token **list)
{
	if (token_len(*list) != 1 || !token_isgroup(*list, GROUP_FUNCALL))
		return 0;
	return 1;
}