summaryrefslogtreecommitdiff
path: root/src/libaudcore/tuple-compiler.cc
blob: dc689209085656c367105f7a03b8fa5bef9a9a9b (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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/*
 * tuple_compiler.c
 * Copyright (c) 2007 Matti 'ccr' Hämäläinen
 * Copyright (c) 2011-2014 John Lindgren
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions, and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions, and the following disclaimer in the documentation
 *    provided with the distribution.
 *
 * This software is provided "as is" and without any warranty, express or
 * implied. In no event shall the authors be liable for any damages arising from
 * the use of this software.
 */

#include <stdlib.h>
#include <string.h>

#include <new>
#include <glib.h>

#include "audstrings.h"
#include "runtime.h"
#include "tuple-compiler.h"

struct Variable
{
    enum {
        Invalid = 0,
        Text,
        Integer,
        Field
    } type;

    String text;
    int integer;
    Tuple::Field field;

    bool set (const char * name, bool literal);
    bool exists (const Tuple & tuple) const;
    Tuple::ValueType get (const Tuple & tuple, String & tmps, int & tmpi) const;
};

enum class Op {
    Invalid = 0,
    Var,
    Exists,
    Equal,
    Unequal,
    Greater,
    GreaterEqual,
    Less,
    LessEqual,
    Empty
};

struct TupleCompiler::Node {
    Op op;
    Variable var1, var2;
    Index<Node> children;
};

typedef TupleCompiler::Node Node;

bool Variable::set (const char * name, bool literal)
{
    if (g_ascii_isdigit (name[0]))
    {
        type = Integer;
        integer = atoi (name);
    }
    else if (literal)
    {
        type = Text;
        text = String (name);
    }
    else
    {
        type = Field;
        field = Tuple::field_by_name (name);

        if (field < 0)
        {
            AUDWARN ("Invalid variable '%s'.\n", name);
            return false;
        }
    }

    return true;
}

bool Variable::exists (const Tuple & tuple) const
{
    g_return_val_if_fail (type == Field, false);
    return tuple.get_value_type (field) != Tuple::Empty;
}

Tuple::ValueType Variable::get (const Tuple & tuple, String & tmps, int & tmpi) const
{
    switch (type)
    {
    case Text:
        tmps = text;
        return Tuple::String;

    case Integer:
        tmpi = integer;
        return Tuple::Int;

    case Field:
        switch (tuple.get_value_type (field))
        {
        case Tuple::String:
            tmps = tuple.get_str (field);
            return Tuple::String;

        case Tuple::Int:
            tmpi = tuple.get_int (field);
            return Tuple::Int;

        default:
            return Tuple::Empty;
        }

    default:
        g_return_val_if_reached (Tuple::Empty);
    }
}

TupleCompiler::TupleCompiler () {}
TupleCompiler::~TupleCompiler () {}

static StringBuf get_item (const char * & str, char endch, bool & literal)
{
    const char * s = str;

    StringBuf buf (-1);
    char * set = buf;
    char * stop = buf + buf.len ();

    if (* s == '"')
    {
        if (! literal)
        {
            buf.steal (StringBuf ());
            AUDWARN ("Unexpected string literal at '%s'.\n", s);
            return StringBuf ();
        }

        s ++;
    }
    else
        literal = false;

    if (literal)
    {
        while (* s != '"')
        {
            if (* s == '\\')
                s ++;

            if (! * s)
            {
                buf.steal (StringBuf ());
                AUDWARN ("Unterminated string literal.\n");
                return StringBuf ();
            }

            if (set == stop)
                throw std::bad_alloc ();

            * set ++ = * s ++;
        }

        s ++;
    }
    else
    {
        while (g_ascii_isalnum (* s) || * s == '-')
        {
            if (set == stop)
                throw std::bad_alloc ();

            * set ++ = * s ++;
        }
    }

    if (* s != endch)
    {
        buf.steal (StringBuf ());
        AUDWARN ("Expected '%c' at '%s'.\n", endch, s);
        return StringBuf ();
    }

    str = s + 1;

    buf.resize (set - buf);
    return buf;
}

static bool compile_expression (Index<Node> & nodes, const char * & expression);

static bool parse_construct (Node & node, const char * & c)
{
    bool literal1 = true, literal2 = true;

    StringBuf tmps1 = get_item (c, ',', literal1);
    if (! tmps1)
        return false;

    StringBuf tmps2 = get_item (c, ':', literal2);
    if (! tmps2)
        return false;

    if (! node.var1.set (tmps1, literal1))
        return false;

    if (! node.var2.set (tmps2, literal2))
        return false;

    return compile_expression (node.children, c);
}

/* Compile format expression into Node tree. */
static bool compile_expression (Index<Node> & nodes, const char * & expression)
{
    const char * c = expression;

    while (* c && * c != '}')
    {
        Node & node = nodes.append ();

        if (* c == '$')
        {
            /* Expression? */
            if (c[1] != '{')
            {
                AUDWARN ("Expected '${' at '%s'.\n", c);
                return false;
            }

            c += 2;

            switch (* c)
            {
            case '?':
            case '(':
              {
                if (* c == '?')
                {
                    node.op = Op::Exists;
                    c ++;
                }
                else
                {
                    if (strncmp (c, "(empty)?", 8))
                    {
                        AUDWARN ("Expected '(empty)?' at '%s'.\n", c);
                        return false;
                    }

                    node.op = Op::Empty;
                    c += 8;
                }

                bool literal = false;
                StringBuf tmps = get_item (c, ':', literal);
                if (! tmps)
                    return false;

                if (! node.var1.set (tmps, false))
                    return false;

                if (! compile_expression (node.children, c))
                    return false;

                break;
              }

            case '=':
            case '!':
                node.op = (* c == '=') ? Op::Equal : Op::Unequal;

                if (c[1] != '=')
                {
                    AUDWARN ("Expected '%c=' at '%s'.\n", c[0], c);
                    return false;
                }

                c += 2;

                if (! parse_construct (node, c))
                    return false;

                break;

            case '<':
            case '>':
                if (c[1] == '=')
                {
                    node.op = (* c == '<') ? Op::LessEqual : Op::GreaterEqual;
                    c += 2;
                }
                else
                {
                    node.op = (* c == '<') ? Op::Less : Op::Greater;
                    c ++;
                }

                if (! parse_construct (node, c))
                    return false;

                break;

            default:
              {
                bool literal = false;
                StringBuf tmps = get_item (c, '}', literal);
                if (! tmps)
                    return false;

                c --;

                node.op = Op::Var;

                if (! node.var1.set (tmps, false))
                    return false;
              }
            }

            if (* c != '}')
            {
                AUDWARN ("Expected '}' at '%s'.\n", c);
                return false;
            }

            c ++;
        }
        else if (* c == '{')
        {
            AUDWARN ("Unexpected '%c' at '%s'.\n", * c, c);
            return false;
        }
        else
        {
            /* Parse raw/literal text */
            StringBuf buf (-1);
            char * set = buf;
            char * stop = buf + buf.len ();

            while (* c && * c != '$' && * c != '{' && * c != '}')
            {
                if (* c == '\\')
                {
                    c ++;

                    if (! * c)
                    {
                        buf.steal (StringBuf ());
                        AUDWARN ("Incomplete escaped character.\n");
                        return false;
                    }
                }

                if (set == stop)
                    throw std::bad_alloc ();

                * set ++ = * c ++;
            }

            buf.resize (set - buf);

            node.op = Op::Var;
            node.var1.type = Variable::Text;
            node.var1.text = String (buf);
        }
    }

    expression = c;
    return true;
}

bool TupleCompiler::compile (const char * expr)
{
    const char * c = expr;
    Index<Node> nodes;

    if (! compile_expression (nodes, c))
        return false;

    if (* c)
    {
        AUDWARN ("Unexpected '%c' at '%s'.\n", * c, c);
        return false;
    }

    root_nodes = std::move (nodes);
    return true;
}

/* Evaluate tuple in given TupleEval expression in given
 * context and return resulting string. */
static void eval_expression (const Index<Node> & nodes, const Tuple & tuple, StringBuf & out)
{
    for (const Node & node : nodes)
    {
        switch (node.op)
        {
        case Op::Var:
          {
            String tmps;
            int tmpi;

            switch (node.var1.get (tuple, tmps, tmpi))
            {
            case Tuple::String:
                out.insert (-1, tmps);
                break;

            case Tuple::Int:
                out.combine (int_to_str (tmpi));
                break;

            default:
                break;
            }

            break;
          }

        case Op::Equal:
        case Op::Unequal:
        case Op::Less:
        case Op::LessEqual:
        case Op::Greater:
        case Op::GreaterEqual:
          {
            bool result = false;
            String tmps1, tmps2;
            int tmpi1 = 0, tmpi2 = 0;

            Tuple::ValueType type1 = node.var1.get (tuple, tmps1, tmpi1);
            Tuple::ValueType type2 = node.var2.get (tuple, tmps2, tmpi2);

            if (type1 != Tuple::Empty && type2 != Tuple::Empty)
            {
                int resulti;

                if (type1 == type2)
                {
                    if (type1 == Tuple::String)
                        resulti = strcmp (tmps1, tmps2);
                    else
                        resulti = tmpi1 - tmpi2;
                }
                else
                {
                    if (type1 == Tuple::Int)
                        resulti = tmpi1 - atoi (tmps2);
                    else
                        resulti = atoi (tmps1) - tmpi2;
                }

                switch (node.op)
                {
                case Op::Equal:
                    result = (resulti == 0);
                    break;

                case Op::Unequal:
                    result = (resulti != 0);
                    break;

                case Op::Less:
                    result = (resulti < 0);
                    break;

                case Op::LessEqual:
                    result = (resulti <= 0);
                    break;

                case Op::Greater:
                    result = (resulti > 0);
                    break;

                case Op::GreaterEqual:
                    result = (resulti >= 0);
                    break;

                default:
                    g_warn_if_reached ();
                }
            }

            if (result)
                eval_expression (node.children, tuple, out);

            break;
          }

        case Op::Exists:
            if (node.var1.exists (tuple))
                eval_expression (node.children, tuple, out);

            break;

        case Op::Empty:
            if (! node.var1.exists (tuple))
                eval_expression (node.children, tuple, out);

            break;

        default:
            g_warn_if_reached ();
        }
    }
}

void TupleCompiler::format (Tuple & tuple) const
{
    tuple.unset (Tuple::FormattedTitle);  // prevent recursion

    StringBuf buf (0);
    eval_expression (root_nodes, tuple, buf);

    if (buf[0])
    {
        tuple.set_str (Tuple::FormattedTitle, buf);
        return;
    }

    /* formatting failed, try fallbacks */
    for (Tuple::Field fallback : {Tuple::Title, Tuple::Basename})
    {
        String title = tuple.get_str (fallback);
        if (title)
        {
            tuple.set_str (Tuple::FormattedTitle, title);
            return;
        }
    }

    tuple.set_str (Tuple::FormattedTitle, "");
}