summaryrefslogtreecommitdiff
path: root/csrc/services/quick-answers/math-parser.c
blob: 17d976d4df605b8332c21e81319bc905ce477984 (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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#include "services/quick-answers/math.h"

//
// Parser:
//
// The parser context/state which is passed around.
//

typedef struct _Parser Parser;

struct _Parser
{
	FoobarMathToken const* tokens;
	gsize                  tokens_count;
	gsize                  position;
};

//
// InfixPrecedence:
//
// Value indicating how strongly infix operators should bind. The higher the value, the stronger they should bind.
//

typedef enum
{
	INFIX_PRECEDENCE_INVALID        = -1,
	INFIX_PRECEDENCE_NONE           = 0,
	INFIX_PRECEDENCE_ADDITIVE       = 1,
	INFIX_PRECEDENCE_MULTIPLICATIVE = 2,
	INFIX_PRECEDENCE_EXPONENTS      = 3,
} InfixPrecedence;

static FoobarMathExpression*  parser_process            ( Parser*                ctx,
                                                          FoobarMathExpression*  lhs,
                                                          InfixPrecedence        min_precedence );
static FoobarMathExpression*  parser_process_single     ( Parser*                ctx,
                                                          gboolean               allow_sign );
static FoobarMathExpression*  parser_process_identifier ( Parser*                ctx );
static FoobarMathExpression*  parser_process_number     ( Parser*                ctx );
static FoobarMathExpression*  parser_process_function   ( Parser*                ctx,
                                                          FoobarMathFunction     function );
static FoobarMathExpression*  parser_process_parens     ( Parser*                ctx );
static FoobarMathExpression*  parser_process_sign       ( Parser*                ctx );
static FoobarMathToken const* parser_peek               ( Parser const*          ctx );
static FoobarMathToken const* parser_pop                ( Parser*                ctx );
static gboolean               parser_match_identifier   ( FoobarMathToken const* token,
                                                          gchar const*           identifier );
static InfixPrecedence        parser_operator_precedence( FoobarMathToken const* token );
static FoobarMathOperation    parser_operator           ( FoobarMathToken const* token );

// ---------------------------------------------------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------------------------------------------------

//
// Transform a sequence of tokens into a mathematical expression.
//
// On success, this will return a newly allocated expression which should be freed using foobar_math_expression_free.
//
// On error, this will return NULL.
//
FoobarMathExpression* foobar_math_parse(
	FoobarMathToken const* tokens,
	gsize                  tokens_count )
{
	Parser ctx = { 0 };
	ctx.tokens = tokens;
	ctx.tokens_count = tokens_count;

	FoobarMathExpression* lhs = parser_process_single( &ctx, TRUE );
	if ( !lhs ) { return NULL; }

	FoobarMathExpression* expr = parser_process( &ctx, lhs, INFIX_PRECEDENCE_NONE );
	if ( !expr ) { return NULL; }

	if ( parser_peek( &ctx ) )
	{
		foobar_math_expression_free( expr );
		return NULL;
	}

	return expr;
}

//
// Process tokens until the end of the current precedence scope (indicated by min_precedence), starting at an operator.
//
FoobarMathExpression* parser_process(
	Parser*               ctx,
	FoobarMathExpression* lhs,
	InfixPrecedence       min_precedence )
{
	FoobarMathToken const* op = parser_peek( ctx );
	InfixPrecedence op_precedence = parser_operator_precedence( op );
	while ( op_precedence >= min_precedence )
	{
		parser_pop( ctx );

		FoobarMathExpression* rhs = parser_process_single( ctx, FALSE );
		if ( !rhs )
		{
			foobar_math_expression_free( lhs );
			return NULL;
		}

		FoobarMathToken const* next_op = parser_peek( ctx );
		while ( parser_operator_precedence( next_op ) > op_precedence )
		{
			rhs = parser_process( ctx, rhs, op_precedence + 1 );
			if ( !rhs )
			{
				foobar_math_expression_free( lhs );
				return NULL;
			}

			next_op = parser_peek( ctx );
		}

		lhs = foobar_math_expression_new_operation( parser_operator( op ), lhs, rhs );

		op = parser_peek( ctx );
		op_precedence = parser_operator_precedence( op );
	}

	return lhs;
}

//
// Process a single value which may be either a constant, function, number, expression enclosed in parenthesis or
// negation.
//
// If an unexpected token is encountered (i.e. an operator), this will return FALSE.
//
FoobarMathExpression* parser_process_single(
	Parser*  ctx,
	gboolean allow_sign )
{
	FoobarMathToken const* token = parser_peek( ctx );
	if ( !token ) { return NULL; }

	switch ( token->type )
	{
		case FOOBAR_MATH_TOKEN_IDENTIFIER:
			return parser_process_identifier( ctx );
		case FOOBAR_MATH_TOKEN_NUMBER:
			return parser_process_number( ctx );
		case FOOBAR_MATH_TOKEN_PAREN_OPEN:
			return parser_process_parens( ctx );
		case FOOBAR_MATH_TOKEN_MINUS:
		case FOOBAR_MATH_TOKEN_PLUS:
			if ( !allow_sign ) { return NULL; }
			return parser_process_sign( ctx );
		case FOOBAR_MATH_TOKEN_PAREN_CLOSE:
		case FOOBAR_MATH_TOKEN_MUL:
		case FOOBAR_MATH_TOKEN_DIV:
		case FOOBAR_MATH_TOKEN_POW:
			return NULL;
		default:
			g_warn_if_reached( );
			return NULL;
	}
}

//
// Parse an identifier.
//
// If the identifier is a function, this will expected parenthesis and an expression afterwards.
//
FoobarMathExpression* parser_process_identifier( Parser* ctx )
{
	FoobarMathToken const* token = parser_pop( ctx );
	if ( parser_match_identifier( token, "pi" ) )
	{
		return foobar_math_expression_new_constant( FOOBAR_MATH_CONSTANT_PI );
	}
	else if ( parser_match_identifier( token, "e" ) )
	{
		return foobar_math_expression_new_constant( FOOBAR_MATH_CONSTANT_E );
	}
	else if ( parser_match_identifier( token, "exp" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_EXP );
	}
	else if ( parser_match_identifier( token, "sqrt" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_SQRT );
	}
	else if ( parser_match_identifier( token, "sin" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_SIN );
	}
	else if ( parser_match_identifier( token, "cos" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_COS );
	}
	else if ( parser_match_identifier( token, "sec" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_SEC );
	}
	else if ( parser_match_identifier( token, "csc" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_CSC );
	}
	else if ( parser_match_identifier( token, "tan" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_TAN );
	}
	else if ( parser_match_identifier( token, "cot" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_COT );
	}
	else if ( parser_match_identifier( token, "arcsin" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_ARCSIN );
	}
	else if ( parser_match_identifier( token, "arccos" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_ARCCOS );
	}
	else if ( parser_match_identifier( token, "arcsec" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_ARCSEC );
	}
	else if ( parser_match_identifier( token, "arccsc" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_ARCCSC );
	}
	else if ( parser_match_identifier( token, "arctan" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_ARCTAN );
	}
	else if ( parser_match_identifier( token, "arccot" ) )
	{
		return parser_process_function( ctx, FOOBAR_MATH_FUNCTION_ARCCOT );
	}
	else
	{
		return NULL;
	}
}

//
// Process a numeric value.
//
FoobarMathExpression* parser_process_number( Parser* ctx )
{
	FoobarMathToken const* token = parser_pop( ctx );
	FoobarMathValue value = { 0 };
	if ( !foobar_math_value_from_string( token->data, token->length, &value ) )
	{
		return NULL;
	}

	return foobar_math_expression_new_value( value );
}

//
// Process a function's parameter which should be enclosed in parenthesis.
//
FoobarMathExpression* parser_process_function(
	Parser*            ctx,
	FoobarMathFunction function )
{
	FoobarMathToken const* opening_paren = parser_peek( ctx );
	if ( !opening_paren || opening_paren->type != FOOBAR_MATH_TOKEN_PAREN_OPEN )
	{
		return NULL;
	}

	FoobarMathExpression* arg = parser_process_parens( ctx );
	if ( !arg ) { return NULL; }

	return foobar_math_expression_new_function( function, arg );
}

//
// Process an expression enclosed in parenthesis.
//
FoobarMathExpression* parser_process_parens( Parser* ctx )
{
	parser_pop( ctx );
	FoobarMathExpression* lhs = parser_process_single( ctx, TRUE );
	if ( !lhs ) { return NULL; }
	FoobarMathExpression* result = parser_process( ctx, lhs, INFIX_PRECEDENCE_NONE );
	if ( !result ) { return NULL; }
	FoobarMathToken const* closing_paren = parser_pop( ctx );
	if ( !closing_paren || closing_paren->type != FOOBAR_MATH_TOKEN_PAREN_CLOSE )
	{
		foobar_math_expression_free( result );
		return NULL;
	}
	return result;
}

//
// Process a sign (- or +) which may be used for negation of an expression.
//
FoobarMathExpression* parser_process_sign( Parser* ctx )
{
	FoobarMathToken const* token = parser_pop( ctx );
	FoobarMathExpression* result = parser_process_single( ctx, FALSE );
	if ( !result ) { return NULL; }

	if ( token->type == FOOBAR_MATH_TOKEN_MINUS )
	{
		return foobar_math_expression_new_function( FOOBAR_MATH_FUNCTION_NEGATE, result );
	}
	else
	{
		return result;
	}
}

// ---------------------------------------------------------------------------------------------------------------------
// State Helpers
// ---------------------------------------------------------------------------------------------------------------------

//
// Peek at the current token without consuming it.
//
// If this is the end of the token list, return NULL.
//
FoobarMathToken const* parser_peek( Parser const* ctx )
{
	if ( ctx->position >= ctx->tokens_count ) { return NULL; }

	return &ctx->tokens[ctx->position];
}

//
// Consume the current token.
//
// If this is the end of the token list, return NULL.
//
FoobarMathToken const* parser_pop( Parser* ctx )
{
	if ( ctx->position >= ctx->tokens_count ) { return NULL; }

	return &ctx->tokens[ctx->position++];
}

// ---------------------------------------------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------------------------------------------------

//
// Match a token's string against the given identifier string.
//
// This is necessary because the token's content is not a null-terminated string.
//
gboolean parser_match_identifier(
	FoobarMathToken const* token,
	gchar const*           identifier )
{
	if ( strlen( identifier ) != token->length ) { return FALSE; }

	return !strncmp( token->data, identifier, token->length );
}

//
// Get the precedence of an infix operator token or INVALID.
//
InfixPrecedence parser_operator_precedence( FoobarMathToken const* token )
{
	if ( token )
	{
		switch ( token->type )
		{
			case FOOBAR_MATH_TOKEN_PLUS:
			case FOOBAR_MATH_TOKEN_MINUS:
				return INFIX_PRECEDENCE_ADDITIVE;
			case FOOBAR_MATH_TOKEN_MUL:
			case FOOBAR_MATH_TOKEN_DIV:
				return INFIX_PRECEDENCE_MULTIPLICATIVE;
			case FOOBAR_MATH_TOKEN_POW:
				return INFIX_PRECEDENCE_EXPONENTS;
			case FOOBAR_MATH_TOKEN_IDENTIFIER:
			case FOOBAR_MATH_TOKEN_NUMBER:
			case FOOBAR_MATH_TOKEN_PAREN_OPEN:
			case FOOBAR_MATH_TOKEN_PAREN_CLOSE:
			default:
				break;
		}
	}

	return INFIX_PRECEDENCE_INVALID;
}

//
// Get the operation for an infix operator token. This requires the token to be valid.
//
FoobarMathOperation parser_operator( FoobarMathToken const* token )
{
	switch ( token->type )
	{
		case FOOBAR_MATH_TOKEN_PLUS:
			return FOOBAR_MATH_OPERATION_ADD;
		case FOOBAR_MATH_TOKEN_MINUS:
			return FOOBAR_MATH_OPERATION_SUB;
		case FOOBAR_MATH_TOKEN_MUL:
			return FOOBAR_MATH_OPERATION_MUL;
		case FOOBAR_MATH_TOKEN_DIV:
			return FOOBAR_MATH_OPERATION_DIV;
		case FOOBAR_MATH_TOKEN_POW:
			return FOOBAR_MATH_OPERATION_POW;
		case FOOBAR_MATH_TOKEN_IDENTIFIER:
		case FOOBAR_MATH_TOKEN_NUMBER:
		case FOOBAR_MATH_TOKEN_PAREN_OPEN:
		case FOOBAR_MATH_TOKEN_PAREN_CLOSE:
		default:
			g_warn_if_reached( );
			return 0;
	}
}