summaryrefslogtreecommitdiffstats
path: root/src/libixion/formula.cpp
blob: 21e990aea79217189ba52a2ce67502e9571007f3 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <ixion/formula.hpp>
#include <ixion/formula_name_resolver.hpp>
#include <ixion/formula_function_opcode.hpp>
#include <ixion/cell.hpp>
#include <ixion/dirty_cell_tracker.hpp>
#include <ixion/types.hpp>
#include <ixion/model_context.hpp>

#include "formula_lexer.hpp"
#include "formula_parser.hpp"
#include "formula_functions.hpp"
#include "debug.hpp"

#include <sstream>
#include <algorithm>

namespace ixion {

namespace {

#if IXION_LOGGING

[[maybe_unused]] std::string debug_print_formula_tokens(const formula_tokens_t& tokens)
{
    std::ostringstream os;

    for (const formula_token& t : tokens)
    {
        os << std::endl << "  * " << t;
    }

    return os.str();
}

#endif

void print_token(
    const print_config& config, const model_context& cxt, const abs_address_t& pos,
    const formula_name_resolver& resolver, const formula_token& token, std::ostream& os)
{
    auto sheet_to_print = [&config, &pos](const address_t& ref_addr) -> bool
    {
        switch (config.display_sheet)
        {
            case display_sheet_t::always:
                return true;
            case display_sheet_t::never:
                return false;
            case display_sheet_t::only_if_different:
                return ref_addr.to_abs(pos).sheet != pos.sheet;
            case display_sheet_t::unspecified:
                break;
        }
        return false;
    };

    switch (token.opcode)
    {
        case fop_array_open:
            os << '{';
            break;
        case fop_array_close:
            os << '}';
            break;
        case fop_close:
            os << ')';
            break;
        case fop_divide:
            os << '/';
            break;
        case fop_minus:
            os << '-';
            break;
        case fop_multiply:
            os << '*';
            break;
        case fop_exponent:
            os << '^';
            break;
        case fop_concat:
            os << '&';
            break;
        case fop_open:
            os << '(';
            break;
        case fop_plus:
            os << '+';
            break;
        case fop_value:
            os << std::get<double>(token.value);
            break;
        case fop_sep:
            os << cxt.get_config().sep_function_arg;
            break;
        case fop_array_row_sep:
            os << cxt.get_config().sep_matrix_row;
            break;
        case fop_function:
        {
            auto fop = std::get<formula_function_t>(token.value);
            os << formula_functions::get_function_name(fop);
            break;
        }
        case fop_single_ref:
        {
            const address_t& addr = std::get<address_t>(token.value);
            bool sheet_name = sheet_to_print(addr);
            os << resolver.get_name(addr, pos, sheet_name);
            break;
        }
        case fop_range_ref:
        {
            const range_t& range = std::get<range_t>(token.value);
            bool sheet_name = sheet_to_print(range.first);
            os << resolver.get_name(range, pos, sheet_name);
            break;
        }
        case fop_table_ref:
        {
            const table_t& tbl = std::get<table_t>(token.value);
            os << resolver.get_name(tbl);
            break;
        }
        case fop_string:
        {
            auto sid = std::get<string_id_t>(token.value);
            const std::string* p = cxt.get_string(sid);
            if (p)
                os << "\"" << *p << "\"";
            else
                IXION_DEBUG("failed to get a string value for the identifier value of " << sid);

            break;
        }
        case fop_equal:
            os << "=";
            break;
        case fop_not_equal:
            os << "<>";
            break;
        case fop_less:
            os << "<";
            break;
        case fop_greater:
            os << ">";
            break;
        case fop_less_equal:
            os << "<=";
            break;
        case fop_greater_equal:
            os << ">=";
            break;
        case fop_named_expression:
            os << std::get<std::string>(token.value);
            break;
        case fop_unknown:
        default:
        {
            std::ostringstream repr;
            repr << token;
            IXION_DEBUG(
                "token not printed (repr='" << repr.str()
                << "'; name='" << get_opcode_name(token.opcode)
                << "'; opcode='" << get_formula_opcode_string(token.opcode)
                << "')");
        }
    }
}

}

formula_tokens_t parse_formula_string(
    model_context& cxt, const abs_address_t& pos,
    const formula_name_resolver& resolver, std::string_view formula)
{
    IXION_TRACE("pos=" << pos.get_name() << "; formula='" << formula << "'");
    lexer_tokens_t lxr_tokens;
    formula_lexer lexer(cxt.get_config(), formula.data(), formula.size());
    lexer.tokenize();
    lexer.swap_tokens(lxr_tokens);

    IXION_TRACE("lexer tokens: " << print_tokens(lxr_tokens, true));

    formula_tokens_t tokens;
    formula_parser parser(lxr_tokens, cxt, resolver);
    parser.set_origin(pos);
    parser.parse();
    parser.get_tokens().swap(tokens);

    IXION_TRACE("formula tokens (string): " << print_formula_tokens(cxt, pos, resolver, tokens));
    IXION_TRACE("formula tokens (individual): " << debug_print_formula_tokens(tokens));

    return tokens;
}

formula_tokens_t create_formula_error_tokens(
    model_context& cxt, std::string_view src_formula,
    std::string_view error)
{
    formula_tokens_t tokens;
    tokens.emplace_back(fop_error);
    tokens.back().value = 2u;

    string_id_t sid_src_formula = cxt.add_string(src_formula);
    tokens.emplace_back(sid_src_formula);

    string_id_t sid_error = cxt.add_string(error);
    tokens.emplace_back(sid_error);

    return tokens;
}

std::string print_formula_tokens(
    const model_context& cxt, const abs_address_t& pos,
    const formula_name_resolver& resolver, const formula_tokens_t& tokens)
{
    print_config config;
    config.display_sheet = display_sheet_t::only_if_different;
    return print_formula_tokens(config, cxt, pos, resolver, tokens);
}

std::string print_formula_tokens(
    const print_config& config, const model_context& cxt, const abs_address_t& pos,
    const formula_name_resolver& resolver, const formula_tokens_t& tokens)
{
    std::ostringstream os;

    if (!tokens.empty() && tokens[0].opcode == fop_error)
        // Let's not print anything on error tokens.
        return std::string();

    for (const formula_token& token : tokens)
        print_token(config, cxt, pos, resolver, token, os);

    return os.str();
}

std::string print_formula_token(
    const model_context& cxt, const abs_address_t& pos,
    const formula_name_resolver& resolver, const formula_token& token)
{
    print_config config;
    config.display_sheet = display_sheet_t::only_if_different;
    return print_formula_token(config, cxt, pos, resolver, token);
}

std::string print_formula_token(
    const print_config& config, const model_context& cxt, const abs_address_t& pos,
    const formula_name_resolver& resolver, const formula_token& token)
{
    std::ostringstream os;
    print_token(config, cxt, pos, resolver, token, os);
    return os.str();
}

namespace {

bool is_volatile(formula_function_t func)
{
    switch (func)
    {
        case formula_function_t::func_now:
            return true;
        default:
            ;
    }
    return false;
}

bool has_volatile(const formula_tokens_t& tokens)
{
    for (const auto& t : tokens)
    {
        if (t.opcode != fop_function)
            continue;

        auto func = std::get<formula_function_t>(t.value);
        if (is_volatile(func))
            return true;
    }
    return false;
}

void check_sheet_or_throw(const char* func_name, sheet_t sheet, const model_context& cxt, const abs_address_t& pos, const formula_cell& cell)
{
    if (is_valid_sheet(sheet))
        return;

    IXION_DEBUG("invalid range reference: func=" << func_name
        << "; pos=" << pos.get_name()
        << "; formula='" << detail::print_formula_expression(cxt, pos, cell)
        << "'");

    std::ostringstream os;
    os << func_name << ": invalid sheet index in " << pos.get_name()
        << ": formula='" << detail::print_formula_expression(cxt, pos, cell) << "'";
    throw ixion::formula_registration_error(os.str());
}

}

void register_formula_cell(
    model_context& cxt, const abs_address_t& pos, const formula_cell* cell)
{
#ifdef IXION_DEBUG_UTILS
    if (cell)
    {
        const formula_cell* check = cxt.get_formula_cell(pos);
        if (cell != check)
        {
            throw std::runtime_error(
                "The cell instance passed to this call does not match the cell instance found at the specified position.");
        }
    }
#endif

    if (!cell)
    {
        cell = cxt.get_formula_cell(pos);
        if (!cell)
            // Not a formula cell. Bail out.
            return;
    }

    formula_group_t fg_props = cell->get_group_properties();
    dirty_cell_tracker& tracker = cxt.get_cell_tracker();

    abs_range_t src_pos = pos;
    if (fg_props.grouped)
    {
        // Expand the source range for grouped formula cells.
        src_pos.last.column += fg_props.size.column - 1;
        src_pos.last.row += fg_props.size.row - 1;
    }

    IXION_TRACE("pos=" << pos.get_name()
        << "; formula='" << detail::print_formula_expression(cxt, pos, *cell)
        << "'");

    std::vector<const formula_token*> ref_tokens = cell->get_ref_tokens(cxt, pos);

    for (const formula_token* p : ref_tokens)
    {
        IXION_TRACE("ref token: " << detail::print_formula_token_repr(*p));

        switch (p->opcode)
        {
            case fop_single_ref:
            {
                abs_address_t addr = std::get<address_t>(p->value).to_abs(pos);
                check_sheet_or_throw("register_formula_cell", addr.sheet, cxt, pos, *cell);
                tracker.add(src_pos, addr);
                break;
            }
            case fop_range_ref:
            {
                abs_range_t range = std::get<range_t>(p->value).to_abs(pos);
                check_sheet_or_throw("register_formula_cell", range.first.sheet, cxt, pos, *cell);
                rc_size_t sheet_size = cxt.get_sheet_size();
                if (range.all_columns())
                {
                    range.first.column = 0;
                    range.last.column = sheet_size.column - 1;
                }
                if (range.all_rows())
                {
                    range.first.row = 0;
                    range.last.row = sheet_size.row - 1;
                }
                range.reorder();
                tracker.add(src_pos, range);
                break;
            }
            default:
                ; // ignore the rest.
        }
    }

    // Check if the cell is volatile.
    const formula_tokens_store_ptr_t& ts = cell->get_tokens();
    if (ts && has_volatile(ts->get()))
        tracker.add_volatile(pos);
}

void unregister_formula_cell(model_context& cxt, const abs_address_t& pos)
{
    // When there is a formula cell at this position, unregister it from
    // the dependency tree.
    formula_cell* fcell = cxt.get_formula_cell(pos);
    if (!fcell)
        // Not a formula cell. Bail out.
        return;

    dirty_cell_tracker& tracker = cxt.get_cell_tracker();
    tracker.remove_volatile(pos);

    // Go through all its existing references, and remove
    // itself as their listener.  This step is important
    // especially during partial re-calculation.
    std::vector<const formula_token*> ref_tokens = fcell->get_ref_tokens(cxt, pos);

    for (const formula_token* p : ref_tokens)
    {

        switch (p->opcode)
        {
            case fop_single_ref:
            {
                abs_address_t addr = std::get<address_t>(p->value).to_abs(pos);
                check_sheet_or_throw("unregister_formula_cell", addr.sheet, cxt, pos, *fcell);
                tracker.remove(pos, addr);
                break;
            }
            case fop_range_ref:
            {
                abs_range_t range = std::get<range_t>(p->value).to_abs(pos);
                check_sheet_or_throw("unregister_formula_cell", range.first.sheet, cxt, pos, *fcell);
                tracker.remove(pos, range);
                break;
            }
            default:
                ; // ignore the rest.
        }
    }
}

abs_address_set_t query_dirty_cells(model_context& cxt, const abs_address_set_t& modified_cells)
{
    abs_range_set_t modified_ranges;
    for (const abs_address_t& mc : modified_cells)
        modified_ranges.insert(mc);

    const dirty_cell_tracker& tracker = cxt.get_cell_tracker();
    abs_range_set_t dirty_ranges = tracker.query_dirty_cells(modified_ranges);

    // Convert a set of ranges to a set of addresses.
    abs_address_set_t dirty_cells;
    std::for_each(dirty_ranges.begin(), dirty_ranges.end(),
        [&dirty_cells](const abs_range_t& r)
        {
            dirty_cells.insert(r.first);
        }
    );
    return dirty_cells;
}

std::vector<abs_range_t> query_and_sort_dirty_cells(
    model_context& cxt, const abs_range_set_t& modified_cells,
    const abs_range_set_t* dirty_formula_cells)
{
    const dirty_cell_tracker& tracker = cxt.get_cell_tracker();
    return tracker.query_and_sort_dirty_cells(modified_cells, dirty_formula_cells);
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */