timedAutomatonBuilder.c 33.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/callback.h>
}

// activate asserts for this file
#undef NDEBUG

#include <cassert>
15
#include <fstream>
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
#include <sstream>

#include <utap/utap.h>

// TODO move the utility caml callbacks (such as list and pair manipulation) into a dedicated file

using namespace UTAP;

class TimedAutomatonBuilder : public UTAP::SystemVisitor
{
public:
    // WARNING  to live in harmony with the GC, the visitor cannot live longer than `pa`
    //          having it as a reference should make it clearer to C++ devs
    explicit TimedAutomatonBuilder(value & pa): _nb_process(0), _process_array(pa) {}
    virtual ~TimedAutomatonBuilder() {}

    void visitSystemBefore(TimedAutomataSystem *ta) { /* nothing to do before */ }
    void visitSystemAfter(TimedAutomataSystem *) { /* nothing to do after */ }

    // global variables are passed to this method
    void visitVariable(variable_t &);

    bool visitTemplateBefore(template_t &) { /* visit templates? */ return false; }
    void visitTemplateAfter(template_t &) { /* nothing to do */ }

    void visitState(state_t &) {}
    void visitEdge(edge_t &) {}

    void visitInstance(instance_t &) {}
    void visitProcess(instance_t &);

    void
    visitFunction(function_t &)
    {
        // not supported by tiamo
        caml_failwith("functions are not supported by TiAMo");
    }
    void visitTypeDef(symbol_t) {}

    void visitIODecl(iodecl_t&) {} // supported by tiamo?
    void visitProgressMeasure(progress_t &) {} // supported by tiamo?
    void visitGanttChart(gantt_t&) {} // supported by tiamo?
    void visitInstanceLine(instanceLine_t &) {} // supported by tiamo?
    void visitMessage(message_t &) {} // supported by tiamo?

    void visitCondition(condition_t &) {} // supported by tiamo?
    void visitUpdate(update_t &) {} // supported by tiamo?

private:
    value & _process_array;
    int _nb_process;
};

/** An expression is one of:
 *      Constant of int
 *      Variable of int
 *      Clock of int
 *      Sum of expression * expression
 *      Product of expression * expression
 *      Subtraction of expression * expression
 *      Division of expression * expression
77 78 79
 *
 * `process` is of OCaml type 'int option' (None for global scope, Some procId for scope in proc
 * this applies to all other functions make_* (make_guard, make_channel, make_update...)
80 81 82 83 84
 */
extern "C" CAMLprim value
make_expression(value process, const expression_t &expression)
{
    CAMLparam1(process);
85
    CAMLlocal4(result, lhs, rhs, indices);
86
    value * cb_pointer = NULL;
87

88 89 90 91 92 93
    switch (expression.getKind())
    {
        case Constants::CONSTANT:
            assert(expression.getSize() == 0);
            result = caml_callback(*caml_named_value("cb_expression_constant"), Val_int(expression.getValue()));
            break;
94 95 96
        case Constants::DOT:
            caml_failwith("dot expressions are not supported in queries");
            break;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        case Constants::IDENTIFIER:
            // it is a clock
            if (expression.getType().isClock())
            {
                result = caml_callback2(*caml_named_value("cb_expression_clock"),
                                        process,
                                        caml_copy_string(expression.getSymbol().getName().c_str()));

            }
            // it is a variable
            else if (expression.getType().isIntegral())
            {
                result = caml_callback2(*caml_named_value("cb_expression_variable"),
                                        process,
                                        caml_copy_string(expression.getSymbol().getName().c_str()));
            }
            else
            {
                // not a clock nor a variable, fail
116 117
                std::stringstream exc_txt("invalid identifier ");
                exc_txt << expression.toString();
118 119 120
                caml_failwith(exc_txt.str().c_str());
            }

Maximilien Colange's avatar
Maximilien Colange committed
121 122 123 124 125 126
            break;
        case Constants::UNARY_MINUS:
            assert(expression.getSize() == 1);
            lhs = caml_callback(*caml_named_value("cb_expression_constant"), Val_int(0));
            rhs = make_expression(process, expression[0]);
            result = caml_callback2(*caml_named_value("cb_expression_substraction"), lhs, rhs);
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
            break;
        case Constants::PLUS:
        case Constants::MULT:
        case Constants::MINUS:
        case Constants::DIV:
            switch (expression.getKind())
            {
                case Constants::PLUS:
                    cb_pointer = caml_named_value("cb_expression_sum");
                    break;
                case Constants::MULT:
                    cb_pointer = caml_named_value("cb_expression_product");
                    break;
                case Constants::MINUS:
                    cb_pointer = caml_named_value("cb_expression_substraction");
                    break;
                case Constants::DIV:
                    cb_pointer = caml_named_value("cb_expression_division");
                    break;
                default: // cannot happen
                    caml_failwith("this line of code is unreacheable");
            }
            assert(expression.getSize() > 1);
            lhs = make_expression(process, expression[0]);
            rhs = make_expression(process, expression[1]);
            result = caml_callback2(*cb_pointer, lhs, rhs);
            for (int i = 2; i < expression.getSize(); ++i)
            {
                lhs = make_expression(process, expression[i]);
                result = caml_callback2(*cb_pointer, lhs, result);
            }
            break;
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        case Constants::ARRAY:
            indices = callback(*caml_named_value("cb_empty_list"), Val_unit);
            {
                expression_t current = expression;
                while (current.getKind() == Constants::ARRAY)
                {
                    assert(current.getSize() == 2);
                    indices = caml_callback2(*caml_named_value("cb_build_list"),
                                             make_expression(process, current[1]),
                                             indices);
                    current = current[0];
                }
                result = caml_callback3(*caml_named_value("cb_expression_array"),
                                        process,
                                        caml_copy_string(current.toString().c_str()),
                                        indices);
            }
            break;
177 178 179 180 181

        case Constants::COST:
            printf("expr is a cost\n");
        case Constants::RATE:
            printf("expr is a rate\n");
182
        default:
183
            printf("expr is %s\n", expression.toString().c_str());
184 185
            caml_failwith("not a valid expression");
    }
186

187 188 189
    CAMLreturn(result);
}

190 191 192 193 194 195 196 197 198 199 200 201
/** A channel is:
 *      either a channel id
 *      or an access in an array of channels
 */
extern "C" CAMLprim value
make_channel(const expression_t &chanexp, value process)
{
    CAMLparam1(process);
    CAMLlocal2(result, indices);

    switch (chanexp.getKind())
    {
202
        case Constants::IDENTIFIER:
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
            result = caml_callback(*caml_named_value("cb_channel_simple"),
                                   caml_copy_string(chanexp.toString().c_str()));
            break;
        case Constants::ARRAY:
            indices = callback(*caml_named_value("cb_empty_list"), Val_unit);
        {
            expression_t current = chanexp;
            while (current.getKind() == Constants::ARRAY)
            {
                assert(current.getSize() == 2);
                indices = caml_callback2(*caml_named_value("cb_build_list"),
                                         make_expression(process, current[1]),
                                         indices);
                current = current[0];
            }
            result = caml_callback2(*caml_named_value("cb_channel_array"),
                                    caml_copy_string(current.toString().c_str()),
                                    indices);
        }
            break;
        default:
            printf("not a valid channel reference: %s\n", chanexp.toString().c_str());
            caml_failwith("invalid channel reference");
    }

    CAMLreturn(result);
}

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
/** An atomic guard is a comparison between two expressions */
extern "C" CAMLprim value
make_atomic_guard(value process, const expression_t &atom_guard)
{
    CAMLparam1(process);
    CAMLlocal3(result, sonleft, sonright);
    assert(atom_guard.getSize() == 2);
    sonleft = make_expression(process, atom_guard[0]);
    sonright = make_expression(process, atom_guard[1]);
    value * cb_pointer = NULL;
    switch (atom_guard.getKind())
    {
        case Constants::LT:
            cb_pointer = caml_named_value("cb_atomic_guard_LT");
            break;
        case Constants::LE:
            cb_pointer = caml_named_value("cb_atomic_guard_LE");
            break;
        case Constants::EQ:
            cb_pointer = caml_named_value("cb_atomic_guard_EQ");
            break;
        case Constants::NEQ:
253
            cb_pointer = caml_named_value("cb_atomic_guard_NEQ");
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
            break;
        case Constants::GE:
            cb_pointer = caml_named_value("cb_atomic_guard_GE");
            break;
        case Constants::GT:
            cb_pointer = caml_named_value("cb_atomic_guard_GT");
            break;
        default:
            caml_failwith("not a valid atomic guard");
    }
    assert(cb_pointer);
    result = caml_callback2(*cb_pointer, sonleft, sonright);
    CAMLreturn(result);
}

/** A guard is a conjunction (as a list) of atomic guards */
extern "C" CAMLprim value
make_guard(value process, const expression_t &guard)
{
    CAMLparam1(process);
    CAMLlocal1(result);
    result = caml_callback(*caml_named_value("cb_empty_list"), Val_unit);
    if (!guard.empty())
    {
        switch (guard.getKind())
        {
            case Constants::LT:
            case Constants::LE:
            case Constants::EQ:
            case Constants::NEQ:
            case Constants::GT:
            case Constants::GE:
                result = caml_callback2(*caml_named_value("cb_build_list"),
                                        make_atomic_guard(process, guard),
                                        result);
                break;
            case Constants::AND:
                for (int i = 0; i != guard.getSize(); ++i)
                {
                    result = caml_callback2(*caml_named_value("cb_concat_list"),
                                            make_guard(process, guard[i]),
                                            result);
                }
                break;
            case Constants::CONSTANT:
                assert(guard.getSize() == 0);
                assert(guard.isTrue());
                // nothing to do, empty guard
                break;
            default:
                caml_failwith("not a valid guard");
        }
    }
    CAMLreturn(result);
}

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
/** a query is a boolean combination of atomic queries */
/** an atomic query is either a regular atomic guard, or a location specification */
extern "C" CAMLprim value
make_query(const expression_t &query)
{
    CAMLparam0();
    CAMLlocal4(result, tmp, procId, locId);

    switch (query.getKind()) {
        case Constants::AND:
            result = make_query(query[0]);
            for (int i = 1; i != query.getSize(); ++i)
            {
                tmp = make_query(query[i]);
                result = caml_callback2(*caml_named_value("cb_qb_make_and"),
                                        result,
                                        tmp);
            }
            break;

        case Constants::OR:
            result = make_query(query[0]);
            for (int i = 1; i != query.getSize(); ++i)
            {
                tmp = make_query(query[i]);
                result = caml_callback2(*caml_named_value("cb_qb_make_or"),
                                        result,
                                        tmp);
            }
            break;

        // there are no global location
        case Constants::DOT:
            // NB: the string right of the dot is: query[0].getType().getRecordLabel(query.getIndex()).c_str()
            procId = caml_callback(*caml_named_value("cb_get_proc"),
                                   caml_copy_string(query.getSymbol().getName().c_str()));
            assert(Int_val(procId) >= 0);
            locId = caml_callback2(*caml_named_value("cb_get_loc"),
                                   procId,
                                   caml_copy_string(query.toString().c_str()));
            assert(Int_val(locId) >= 0);
            result = caml_callback2(*caml_named_value("cb_qb_location"), procId, locId);
            break;

        default:
            result = make_atomic_guard(Val_int(-1), query);
            break;
    }

    CAMLreturn(result);
}

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
// transforms an assignment 'e @= f' into 'e = e @ f'
// where @ is one of +,-,*,/
expression_t
normalize_assignment(const expression_t &update)
{
    switch (update.getKind())
    {
        case Constants::ASSPLUS:
        case Constants::ASSMINUS:
        case Constants::ASSMULT:
        case Constants::ASSDIV:
        {
            expression_t new_rhs;
            Constants::kind_t op;
            switch (update.getKind())
            {
                case Constants::ASSPLUS:
                    op = Constants::PLUS;
                    break;
                case Constants::ASSMINUS:
                    op = Constants::MINUS;
                    break;
                case Constants::ASSMULT:
                    op = Constants::MULT;
                    break;
                case Constants::ASSDIV:
                    op = Constants::DIV;
                    break;
                default: // cannot happen
                    assert(false);
                    throw "cannot happen";
            }
            new_rhs = expression_t::createBinary(op, update[0], update[1]);
            return expression_t::createBinary(Constants::ASSIGN, update[0], new_rhs);
        }
        default:
            return update;
    }
}

402
extern "C" CAMLprim value
403
make_update(value process, const expression_t &u)
404 405 406
{
    CAMLparam1(process);
    CAMLlocal4(result, lhs, rhs, tmp);
407 408
    // remove compound assignments (+=, -=, *=, /=)
    expression_t update = normalize_assignment(u);
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
    result = caml_callback(*caml_named_value("cb_empty_list"), Val_unit);
    switch (update.getKind())
    {
        case Constants::CONSTANT:
            // nothing to do, empty list
            break;
        case Constants::ASSIGN:
            assert(update.getSize() == 2);
            lhs = make_expression(process, update[0]);
            rhs = make_expression(process, update[1]);
            tmp = caml_callback2(*caml_named_value("cb_build_pair"), lhs, rhs);
            result = caml_callback2(*caml_named_value("cb_build_list"), tmp, result);
            break;
        case Constants::COMMA:
            for (int i = 0; i < update.getSize(); ++i)
            {
                result = caml_callback2(*caml_named_value("cb_concat_list"),
                                        make_update(process, update[i]), result);
            }
            break;
        default:
            caml_failwith("invalid kind of update");
    }
    CAMLreturn(result);
}

// a helper function to evaluate an initial value
int
438
eval_expr(const expression_t &expr, value proc)
439
{
440
    CAMLparam1(proc);
441
    CAMLlocal1(tmp);
442
    tmp = make_expression(proc, expr);
443 444 445 446
    int res = Int_val(caml_callback(*caml_named_value("cb_evaluate_expr"), tmp));
    CAMLreturnT(int, res);
}

447 448 449 450 451 452 453 454 455 456 457 458
// a helper function to remove parameters from an expression
expression_t
subst_params(const expression_t &expr, const std::map<symbol_t, expression_t> &mapping)
{
    expression_t res = expr;
    for (auto &varval : mapping)
    {
        res = res.subst(varval.first, varval.second);
    }
    return res;
}

459
void
460
handle_declaration(variable_t &var, value proc, const std::map<symbol_t, expression_t> &mapping)
461
{
462 463
    CAMLparam1(proc);
    CAMLlocal3(cb_array, cb_cell, indices);
464 465 466 467 468

    type_t varType = var.uid.getType();
    // a clock
    if (varType.isClock())
    {
469 470 471
        caml_callback2(*caml_named_value("cb_register_clock"),
                       proc,
                       caml_copy_string(var.uid.getName().c_str()));
472 473 474 475 476 477 478 479
    }
    // a variable
    else if (varType.isIntegral())
    {
        int init_value = 0;
        // evaluate the initializing expression in the caml world
        if (!var.expr.empty())
        {
480
            init_value = eval_expr(subst_params(var.expr, mapping), proc);
481
        }
482 483 484

        value * cb_pointer = NULL;
        // for a const variable
485 486
        if (varType.isConstant())
        {
487
            cb_pointer = caml_named_value("cb_register_constant");
488 489 490
        }
        else
        {
491
            cb_pointer = caml_named_value("cb_register_variable");
492
        }
493 494 495 496 497 498
        assert(cb_pointer);

        caml_callback3(*cb_pointer,
                       proc,
                       caml_copy_string(var.uid.getName().c_str()),
                       Val_int(init_value));
499 500 501 502
    }
    // a channel
    else if (varType.isChannel())
    {
503 504 505
        // raise a warning on urgent and broadcast channels, which are not supported by TiAMo
        if (varType.is(Constants::URGENT))
        {
506
            caml_failwith("Urgent channels are not supported by TiAMo");
507 508 509 510 511
        }
        else if (varType.is(Constants::BROADCAST))
        {
            caml_failwith("Broadcast channels are not supported by TiAMo");
        }
512 513 514 515
        // register channel
        caml_callback2(*caml_named_value("cb_register_channel"),
                       proc,
                       caml_copy_string(var.uid.getName().c_str()));
516 517 518 519 520 521 522
    }
    // an array
    else if (varType.isArray())
    {
        // recall: varType is an array, so it has two subtypes:
        //      the first one (varType.getSub()) is the element type
        //      the second one (varType.getArraySize()) is the array size
523

524 525
        // to differentiate with an array of clocks
        bool is_clock = varType.getSub().isClock();
526 527
        // to differentiate between an array of channels or of integers
        bool is_channel = varType.getSub().isChannel();
528 529
        // to differentiate between const and non-const arrays of integers
        bool is_const = varType.getSub().isConstant();
530

531 532
        if (is_channel)
        {
533 534 535 536 537 538 539
            cb_array = *caml_named_value("cb_register_channel_array_name");
            cb_cell = *caml_named_value("cb_register_channel_array_cell");
        }
        else if (is_clock)
        {
            cb_array = *caml_named_value("cb_register_clock_array_name");
            cb_cell = *caml_named_value("cb_register_clock_array_cell");
540
        }
541 542
        else if (is_const)
        {
543 544
            cb_array = *caml_named_value("cb_register_const_array_name");
            cb_cell = *caml_named_value("cb_register_const_array_cell");
545
        }
546 547
        else
        {
548 549
            cb_array = *caml_named_value("cb_register_array_name");
            cb_cell = *caml_named_value("cb_register_array_cell");
550
        }
551 552 553 554
        // partially apply with `proc` (1st argument common to all invocations)
        cb_array = caml_callback(cb_array, proc);
        cb_cell = caml_callback(cb_cell, proc);

555 556 557 558 559 560 561 562 563 564 565 566 567
        // if varType.getSub() is itself an array type, this makes arrays of arrays
        // to handle the general case, we need to retrieve all dimensions, say in a vector
        //      BEWARE of the order: top-most in the type = right-most in the declaration
        // then use this vector to iterate over the cells of the array and declare them as
        // regular variables with (possible several pairs of) square brackets []
        std::vector<int> multiSize;
        type_t currentType = varType;
        while (currentType.isArray())
        {
            // after looking at type_t::toDeclarationString (file type.cpp),
            // i discovered that the expression of the size of the array is as follows
            expression_t arraySizeExpr = currentType.getArraySize().getRange().second.get(0);
            // evaluate the size expression
568
            int arraySize = eval_expr(subst_params(arraySizeExpr, mapping), proc);
569 570 571 572 573 574
            // push this size in the vector
            multiSize.push_back(arraySize);
            // recursively descend in the type
            currentType = currentType.getSub();
        }

575 576 577 578 579 580 581 582 583 584 585 586
        indices = caml_callback(*caml_named_value("cb_empty_list"), Val_unit);
        for (auto it = multiSize.rbegin(); it != multiSize.rend(); ++it)
        {
            indices = caml_callback2(*caml_named_value("cb_build_list"),
                                     Val_int(*it),
                                     indices);
        }
        // first, register array name with its full dimension
        caml_callback2(cb_array,
                       caml_copy_string(var.uid.getName().c_str()),
                       indices);

587 588 589 590
        std::vector<int> index(multiSize.size(), 0);
        bool index_is_zero = true;
        do
        {
591 592
            indices = caml_callback(*caml_named_value("cb_empty_list"), Val_unit);
            for (auto it = index.rbegin(); it != index.rend(); ++it)
593
            {
594 595 596
                indices = caml_callback2(*caml_named_value("cb_build_list"),
                                         Val_int(*it),
                                         indices);
597 598
            }

599
            if (is_channel || is_clock) // no initial value, register cells directly
600
            {
601
                caml_callback2(cb_cell,
602 603
                               caml_copy_string(var.uid.getName().c_str()),
                               indices);
604
            }
605
            else // integer array, need to compute initial values
606 607 608 609 610 611 612 613 614 615 616
            {
                // retrieve the right initial value
                expression_t initExpr = var.expr;
                for (int i = 0; i != index.size(); ++i)
                {
                    // TODO what if the initExpr is a reference to a previously declared array?
                    //      we should register (in C) the declared arrays, and substitute
                    assert(multiSize[i] == initExpr.getSize());
                    assert(index[i] < initExpr.getSize());
                    initExpr = initExpr[index[i]];
                }
617 618 619 620 621 622
                int cellValue = eval_expr(subst_params(initExpr, mapping), proc);
                // declare current cell
                caml_callback3(cb_cell,
                               caml_copy_string(var.uid.getName().c_str()),
                               indices,
                               Val_int(cellValue));
623
            }
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

            // update index
            index_is_zero = true;
            for (int i = 0; i != index.size() ; ++i)
            {
                if (index[i] == multiSize[i]-1)
                {
                    index[i] = 0;
                }
                else
                {
                    index[i]++;
                    index_is_zero = false;
                    break;
                }
            }
        } while (!index_is_zero);


643 644 645
    }
    else
    {
646
        printf("invalid global declaration %s\n", var.toString().c_str());
647 648
        caml_failwith("invalid global declaration");
    }
649 650

    // return nothing
651 652 653
    CAMLreturn0;
}

654 655 656
// called when visiting global declarations
void
TimedAutomatonBuilder::visitVariable(variable_t &var)
657
{
658 659 660
    CAMLparam0();
    handle_declaration(var, caml_callback(*caml_named_value("cb_make_None"), Val_unit), std::map<symbol_t, expression_t>());
    CAMLreturn0;
661 662
}

663 664 665 666
void
TimedAutomatonBuilder::visitProcess(instance_t &process)
{
    CAMLparam0();
667 668
    CAMLlocal4(guard, edge_list, update, tmpedge);
    CAMLlocal2(proc_id, procref);
669
    CAMLlocalN(args, 8);
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    CAMLlocal1(loc_array);
    CAMLlocal1(tmpproc);
    loc_array = caml_callback(*caml_named_value("cb_build_location_array"), Val_int(process.templ->states.size()));

    // ensure that the argument is an instance
    assert(&process == process.uid.getData());
    // ensure that process has no unbound parameters
    assert(process.parameters.getSize() == process.arguments);
    assert(process.unbound == 0);
    // ensure that the parent template is a real template
    assert(process.templ->arguments == 0);
    assert(process.templ->parameters.getSize() == process.parameters.getSize());
    // ensure that the parent template is its own parent
    assert(process.templ->templ == process.templ);


    proc_id = Val_int(_nb_process++);
687 688
    procref = caml_callback(*caml_named_value("cb_make_Some"), proc_id);

689 690 691 692 693

    // walk the parent template, replacing arguments with the mapping, to build the process
    // register process variables
    for (auto &var : process.templ->variables)
    {
694
        handle_declaration(var, procref, process.mapping);
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    }

    // ensure that there are no branchpoints
    if (process.templ->branchpoints.size() != 0)
    {
        caml_failwith("branchpoints are not supported in TiAMo");
    }

    // visit all locations once, to associate them a unique ID
    std::map<state_t *, int> location_ids;
    int locid = 0;
    for (auto & location : process.templ->states)
    {
        location_ids[&location] = locid++;
    }

    // revisit the locations to actually build them in OCaml
    for (auto & location : process.templ->states)
    {
        edge_list = caml_callback(*caml_named_value("cb_empty_list"), Val_unit);
        for (auto & edge : process.templ->edges)
        {
            assert(edge.srcb == NULL && edge.dstb == NULL);
            if (edge.src == &location)
            {
720 721 722 723 724 725 726
                // TODO currently support at most one non-deterministic select
                assert(edge.select.getSize() < 2);
                symbol_t selectVar;
                std::vector<int32_t> selectValues;
                if (edge.select.getSize() != 0)
                {
                    selectVar = edge.select[0];
727 728
                    int valInf = eval_expr(selectVar.getType().getRange().first, procref);
                    int valSup = eval_expr(selectVar.getType().getRange().second, procref);
729 730 731 732 733 734 735 736 737 738
                    for (int32_t i = valInf; i <= valSup; ++i)
                    {
                        selectValues.push_back(i);
                    }
                }
                else
                {
                    selectValues.push_back(0);
                }

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753

                int srcid = location_ids[edge.src];
                int dstid = location_ids[edge.dst];
                // the source
                args[0] = Val_int(srcid);
                // the destination
                args[1] = Val_int(dstid);
                // the synchronization (if any)
                if (edge.sync.empty())
                {
                    args[4] = caml_callback(*caml_named_value("cb_make_None"), Val_unit);
                }
                else
                {
                    // if not empty, edge.sync must be a synchronization
754
                    // TODO channels are currently resolved WITHOUT the select variable, if any
755 756 757 758 759 760 761
                    assert(edge.sync.getKind() == Constants::SYNC);
                    switch (edge.sync.getSync())
                    {
                        assert(edge.sync.getSize() == 1);
                        // receiving channel
                        case Constants::SYNC_QUE:
                            args[4] = caml_callback(*caml_named_value("cb_recv_channel"),
762
                                                    make_channel(subst_params(edge.sync[0], process.mapping), procref));
763 764 765 766
                            break;
                        // sending channel
                        case Constants::SYNC_BANG:
                            args[4] = caml_callback(*caml_named_value("cb_send_channel"),
767
                                                    make_channel(subst_params(edge.sync[0], process.mapping), procref));
768 769 770 771 772 773 774 775 776 777 778 779
                            break;
                        // TODO what is the semantics of this?
                        case Constants::SYNC_CSP:
                            caml_failwith("CSP synchronization is not supported by TiAMo");
                            break;
                    }
                }
                // the containing process id
                args[5] = proc_id;
                // whether the edge is controllable
                args[6] = Val_bool(edge.control);

780 781 782 783 784 785
                for (auto selval : selectValues)
                {
                    std::map<symbol_t, expression_t> local_mapping = process.mapping;
                    local_mapping[selectVar] = expression_t::createConstant(selval);

                    // the guard
786
                    args[2] = make_guard(procref, subst_params(edge.guard, local_mapping));
787
                    // the updates
788
                    args[3] = make_update(procref, subst_params(edge.assign, local_mapping));
789 790 791 792 793 794

                    // build the edge
                    tmpedge = caml_callbackN(*caml_named_value("cb_build_edge"), 7, args);
                    // add it to the edge list of the current location
                    edge_list = caml_callback2(*caml_named_value("cb_build_list"), tmpedge, edge_list);
                }
795 796 797 798 799 800 801 802 803 804 805
            }
        }
        // the location id
        args[0] = Val_int(location_ids[&location]);
        // the location name
        args[1] = caml_copy_string(location.uid.getName().c_str());
        // TODO is that correct?
        args[2] = Val_bool(location.uid.getType().is(Constants::COMMITTED));
        // TODO is that correct?
        args[3] = Val_bool(location.uid.getType().is(Constants::URGENT));
        // the invariant
806
        args[4] = make_guard(procref, subst_params(location.invariant, process.mapping));
807 808 809 810
        // the list of edges (built above)
        args[5] = edge_list;
        // the containing process id
        args[6] = proc_id;
811 812 813
        // the rate of the location
        args[7] = location.costRate.empty() ?
            caml_callback(*caml_named_value("cb_make_None"), Val_unit) :
814
            caml_callback(*caml_named_value("cb_make_Some"), make_expression(procref, subst_params(location.costRate, process.mapping)));
815 816
        // GC-friendly version of: loc_array[loc_id] = build_location()
        caml_modify(&Field(loc_array, location_ids[&location]),
817
                    caml_callbackN(*caml_named_value("cb_build_location"), 8, args));
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
    }
    // we now build the process
    // the process name
    args[0] = caml_copy_string(process.uid.getName().c_str());
    // the process id
    args[1] = proc_id;
    // the array of locations (built above)
    args[2] = loc_array;
    // the id of the initial location
    args[3] = Val_int(location_ids[static_cast<state_t*>(process.templ->init.getData())]);

    // build the process
    tmpproc = caml_callbackN(*caml_named_value("cb_build_process"), 4, args);

    // GC-friendly version of: _process_array[proc_id] = build_process()
    caml_modify(&Field(_process_array, Int_val(proc_id)),
                tmpproc);

    CAMLreturn0;
}

839 840
#include "querybuilder.c"

841 842
#include "utap/typechecker.h"

843
extern "C" CAMLprim value
844
xta_from_xmlfile(value filename, value qfilename, value enable_cora)
845
{
846
    CAMLparam3(filename, qfilename, enable_cora);
847
    CAMLlocal3(process_array, queryguard, result);
848 849

    // parse the input with the library utap
850
    UTAP::TimedAutomataSystem * ta = new UTAP::TimedAutomataSystem(Bool_val(enable_cora));
851 852 853
    int parse_res = parseXMLFile(String_val(filename), ta, true);
    assert(parse_res == 0);

854
    // running the type checker is mandatory to appropriately set costs (for CORA)
855
    UTAP::TypeChecker type_checker(ta);
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    // TODO I do not understand how the type_checker works
    // building it correctly sets costs (CORA)
    // accepting it detects more errors but deletes the costs...
//    ta->accept(type_checker);

    // the type checker stores errors in the ta
    if (ta->hasErrors())
    {
        for (auto &e : ta->getErrors())
        {
            std::cerr << e << "\n";
        }
        std::cerr << "the input model has errors, aborting\n";
        exit(1);
    }

    // also report warnings
    if (ta->hasWarnings())
    {
        for (auto &w : ta->getWarnings())
        {
            std::cerr << w << "\n";
        }
        std::cerr << "the input model has warnings (see above)\n"
        << "computation goes on, but may be incorrect.\n";
    }
882

883 884 885 886 887 888 889 890 891 892 893 894 895 896
    // currently, we handle only one query
    assert(ta->getQueries().size() < 2);
    std::string squery;
    if (ta->getQueries().size() != 0)
    {
        squery = ta->getQueries()[0].formula;
    }
    else
    {
        // look into the .q file
        std::ifstream inqfile(String_val(qfilename));
        std::getline(inqfile, squery);
    }
    assert(squery != "");
897 898 899 900 901 902 903 904 905 906

    // build the array of process, to be populated by the TA visitor
    process_array = caml_callback(*caml_named_value("cb_build_process_array"),
                                  Val_int(ta->getProcesses().size()));

    // WARNING  to live in harmony with the GC, the visitor cannot live longer than the
    //          value (caml array) `process_array`
    TimedAutomatonBuilder v(process_array);
    ta->accept(v);

907 908 909
    // build the caml TA (before parsing the query)
    result = caml_callback(*caml_named_value("cb_build_ta"), process_array);

910 911 912
    // parse the query
    QueryBuilder qb(ta);
    parseProperty(squery.c_str(), &qb);
913 914 915
    const expression_t & query = qb.getResult();
    assert(query.getKind() == Constants::EF);
    queryguard = make_query(query[0]);
916

917 918
    // set the query
    result = caml_callback2(*caml_named_value("cb_set_query"), result, queryguard);
919 920 921

    CAMLreturn(result);
}