summaryrefslogtreecommitdiff
path: root/gtk/gtkconstraintexpression.c
blob: 6c571ae14c20c90f0b54af2359824fc7a3b2eb77 (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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
/* gtkconstraintexpression.c: Constraint expressions and variables
 * Copyright 2019  GNOME Foundation
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Emmanuele Bassi
 */

#include "config.h"

#include "gtkconstraintexpressionprivate.h"
#include "gtkconstraintsolverprivate.h"

/* {{{ Variables */

typedef enum {
  GTK_CONSTRAINT_SYMBOL_DUMMY         = 'd',
  GTK_CONSTRAINT_SYMBOL_OBJECTIVE     = 'o',
  GTK_CONSTRAINT_SYMBOL_SLACK         = 'S',
  GTK_CONSTRAINT_SYMBOL_REGULAR       = 'v'
} GtkConstraintSymbolType;

struct _GtkConstraintVariable
{
  guint64 _id;

  GtkConstraintSymbolType _type;

  /* Interned strings */
  const char *name;
  const char *prefix;

  double value;

  guint is_external : 1;
  guint is_pivotable : 1;
  guint is_restricted : 1;
};

/* Variables are sorted by a monotonic id */
static guint64 gtk_constraint_variable_next_id;

static void
gtk_constraint_variable_init (GtkConstraintVariable *variable,
                              const char *prefix,
                              const char *name)
{
  variable->_id = gtk_constraint_variable_next_id++;

  variable->prefix = g_intern_string (prefix);
  variable->name = g_intern_string (name);
  variable->prefix = NULL;
  variable->value = 0.0;
}

/*< private >
 * gtk_constraint_variable_new_dummy:
 * @name: the name of the variable
 *
 * Allocates and initializes a new `GtkConstraintVariable` for a "dummy"
 * symbol. Dummy symbols are typically used as markers inside a solver,
 * and will not be factored in the solution when pivoting the tableau
 * of the constraint equations.
 *
 * Only `GtkConstraintSolver` should use this function.
 *
 * Returns: a newly allocated `GtkConstraintVariable`
 */
GtkConstraintVariable *
gtk_constraint_variable_new_dummy (const char *name)
{
  GtkConstraintVariable *res = g_rc_box_new (GtkConstraintVariable);

  gtk_constraint_variable_init (res, NULL, name);

  res->_type = GTK_CONSTRAINT_SYMBOL_DUMMY;
  res->is_external = FALSE;
  res->is_pivotable = FALSE;
  res->is_restricted = TRUE;

  return res;
}

/*< private >
 * gtk_constraint_variable_new_objective:
 * @name: the name of the variable
 *
 * Allocates and initializes a new `GtkConstraintVariable` for an objective
 * symbol. This is the constant value we wish to find as the result of the
 * simplex optimization.
 *
 * Only `GtkConstraintSolver` should use this function.
 *
 * Returns: a newly allocated `GtkConstraintVariable`
 */
GtkConstraintVariable *
gtk_constraint_variable_new_objective (const char *name)
{
  GtkConstraintVariable *res = g_rc_box_new (GtkConstraintVariable);

  gtk_constraint_variable_init (res, NULL, name);

  res->_type = GTK_CONSTRAINT_SYMBOL_OBJECTIVE;
  res->is_external = FALSE;
  res->is_pivotable = FALSE;
  res->is_restricted = FALSE;

  return res;
}

/*< private >
 * gtk_constraint_variable_new_slack:
 * @name: the name of the variable
 *
 * Allocates and initializes a new `GtkConstraintVariable` for a "slack"
 * symbol. Slack variables are introduced inside the tableau to turn
 * inequalities, like:
 *
 * |[
 *   expr ≥ 0
 * ]|
 *
 * Into equalities, like:
 *
 * |[
 *   expr - slack = 0
 * ]|
 *
 * Only `GtkConstraintSolver` should use this function.
 *
 * Returns: a newly allocated `GtkConstraintVariable`
 */
GtkConstraintVariable *
gtk_constraint_variable_new_slack (const char *name)
{
  GtkConstraintVariable *res = g_rc_box_new (GtkConstraintVariable);

  gtk_constraint_variable_init (res, NULL, name);

  res->_type = GTK_CONSTRAINT_SYMBOL_SLACK;
  res->is_external = FALSE;
  res->is_pivotable = TRUE;
  res->is_restricted = TRUE;

  return res;
}

/*< private >
 * gtk_constraint_variable_new:
 * @prefix: (nullable): an optional prefix string for @name
 * @name: (nullable): an optional name for the variable
 *
 * Allocates and initializes a new `GtkConstraintVariable` for a regular
 * symbol. All variables introduced by constraints are regular variables.
 *
 * Only `GtkConstraintSolver` should use this function; a constraint layout
 * manager should ask the `GtkConstraintSolver` to create a variable, using
 * gtk_constraint_solver_create_variable(), which will insert the variable
 * in the solver's tableau.
 *
 * Returns: a newly allocated `GtkConstraintVariable`
 */
GtkConstraintVariable *
gtk_constraint_variable_new (const char *prefix,
                             const char *name)
{
  GtkConstraintVariable *res = g_rc_box_new (GtkConstraintVariable);

  gtk_constraint_variable_init (res, prefix, name);

  res->_type = GTK_CONSTRAINT_SYMBOL_REGULAR;
  res->is_external = TRUE;
  res->is_pivotable = FALSE;
  res->is_restricted = FALSE;

  return res;
}

/*< private >
 * gtk_constraint_variable_ref:
 * @variable: a `GtkConstraintVariable`
 *
 * Acquires a reference to @variable.
 *
 * Returns: (transfer full): the given `GtkConstraintVariable`, with its reference
 *   count increased
 */
GtkConstraintVariable *
gtk_constraint_variable_ref (GtkConstraintVariable *variable)
{
  g_return_val_if_fail (variable != NULL, NULL);

  return g_rc_box_acquire (variable);
}

/*< private >
 * gtk_constraint_variable_unref:
 * @variable: (transfer full): a `GtkConstraintVariable`
 *
 * Releases a reference to @variable.
 */
void
gtk_constraint_variable_unref (GtkConstraintVariable *variable)
{
  g_return_if_fail (variable != NULL);

  g_rc_box_release (variable);
}

/*< private >
 * gtk_constraint_variable_set_value:
 * @variable: a `GtkConstraintVariable`
 *
 * Sets the current value of a `GtkConstraintVariable`.
 */
void
gtk_constraint_variable_set_value (GtkConstraintVariable *variable,
                                   double value)
{
  variable->value = value;
}

/*< private >
 * gtk_constraint_variable_get_value:
 * @variable: a `GtkConstraintVariable`
 *
 * Retrieves the current value of a `GtkConstraintVariable`
 *
 * Returns: the value of the variable
 */
double
gtk_constraint_variable_get_value (const GtkConstraintVariable *variable)
{
  return variable->value;
}

/*< private >
 * gtk_constraint_variable_to_string:
 * @variable: a `GtkConstraintVariable`
 *
 * Turns @variable into a string, for debugging purposes.
 *
 * Returns: (transfer full): a string with the contents of @variable
 */
char *
gtk_constraint_variable_to_string (const GtkConstraintVariable *variable)
{
  GString *buf = g_string_new (NULL);

  if (variable == NULL)
    g_string_append (buf, "<null>");
  else
    {
      switch (variable->_type)
        {
        case GTK_CONSTRAINT_SYMBOL_DUMMY:
          g_string_append (buf, "(d)");
          break;
        case GTK_CONSTRAINT_SYMBOL_OBJECTIVE:
          g_string_append (buf, "(O)");
          break;
        case GTK_CONSTRAINT_SYMBOL_SLACK:
          g_string_append (buf, "(S)");
          break;
        case GTK_CONSTRAINT_SYMBOL_REGULAR:
          break;

        default:
          g_assert_not_reached ();
        }

      g_string_append_c (buf, '[');

      if (variable->prefix != NULL)
        {
          g_string_append (buf, variable->prefix);
          g_string_append_c (buf, '.');
        }

      if (variable->name != NULL)
        g_string_append (buf, variable->name);

      if (variable->_type == GTK_CONSTRAINT_SYMBOL_REGULAR)
        {
          char dbl_buf[G_ASCII_DTOSTR_BUF_SIZE];

          g_ascii_dtostr (dbl_buf, G_ASCII_DTOSTR_BUF_SIZE, variable->value);

          g_string_append_c (buf, ':');
          g_string_append (buf, dbl_buf);
        }

      g_string_append_c (buf, ']');
    }

  return g_string_free (buf, FALSE);
}

/*< private >
 * gtk_constraint_variable_is_external:
 * @variable: a `GtkConstraintVariable`
 *
 * Checks whether the @variable was introduced from outside the solver.
 *
 * Returns: %TRUE if the variable is external
 */
gboolean
gtk_constraint_variable_is_external (const GtkConstraintVariable *variable)
{
  return variable->is_external;
}

/*< private >
 * gtk_constraint_variable_is_pivotable:
 * @variable: a `GtkConstraintVariable`
 *
 * Checks whether the @variable can be used as a pivot.
 *
 * Returns: %TRUE if the variable is pivotable
 */
gboolean
gtk_constraint_variable_is_pivotable (const GtkConstraintVariable *variable)
{
  return variable->is_pivotable;
}

/*< private >
 * gtk_constraint_variable_is_restricted:
 * @variable: a `GtkConstraintVariable`
 *
 * Checks whether the @variable's use is restricted.
 *
 * Returns: %TRUE if the variable is restricted
 */
gboolean
gtk_constraint_variable_is_restricted (const GtkConstraintVariable *variable)
{
  return variable->is_restricted;
}

/*< private >
 * gtk_constraint_variable_is_dummy:
 * @variable: a `GtkConstraintVariable`
 *
 * Checks whether the @variable is a dummy symbol.
 *
 * Returns: %TRUE if the variable is a dummy symbol
 */
gboolean
gtk_constraint_variable_is_dummy (const GtkConstraintVariable *variable)
{
  return variable->_type == GTK_CONSTRAINT_SYMBOL_DUMMY;
}

/*< private >
 * GtkConstraintVariableSet:
 *
 * A set of variables.
 */
struct _GtkConstraintVariableSet {
  /* List<Variable>, owns a reference */
  GSequence *set;

  /* Age of the set, to guard against mutations while iterating */
  gint64 age;
};

/*< private >
 * gtk_constraint_variable_set_free:
 * @set: a `GtkConstraintVariable`Set
 *
 * Frees the resources associated to a `GtkConstraintVariable`Set/
 */
void
gtk_constraint_variable_set_free (GtkConstraintVariableSet *set)
{
  g_return_if_fail (set != NULL);

  g_sequence_free (set->set);

  g_free (set);
}

/*< private >
 * gtk_constraint_variable_set_new:
 *
 * Creates a new `GtkConstraintVariable`Set.
 *
 * Returns: the newly created variable set
 */
GtkConstraintVariableSet *
gtk_constraint_variable_set_new (void)
{
  GtkConstraintVariableSet *res = g_new (GtkConstraintVariableSet, 1);

  res->set = g_sequence_new ((GDestroyNotify) gtk_constraint_variable_unref);

  res->age = 0;

  return res;
}

static int
sort_by_variable_id (gconstpointer a,
                     gconstpointer b,
                     gpointer      data)
{
  const GtkConstraintVariable *va = a, *vb = b;

  if (va == vb)
    return 0;

  return va->_id - vb->_id;
}

/*< private >
 * gtk_constraint_variable_set_add:
 * @set: a `GtkConstraintVariable`Set
 * @variable: a `GtkConstraintVariable`
 *
 * Adds @variable to the given @set, if the @variable is not already
 * in it.
 *
 * The @set will acquire a reference on the @variable, and will release
 * it after calling gtk_constraint_variable_set_remove(), or when the @set
 * is freed.
 *
 * Returns: %TRUE if the variable was added to the set, and %FALSE otherwise
 */
gboolean
gtk_constraint_variable_set_add (GtkConstraintVariableSet *set,
                                 GtkConstraintVariable *variable)
{
  GSequenceIter *iter;

  iter = g_sequence_search (set->set, variable, sort_by_variable_id, NULL);
  if (!g_sequence_iter_is_end (iter))
    {
      GtkConstraintVariable *v = g_sequence_get (iter);
      if (v->_id == variable->_id)
        return FALSE;
    }

  g_sequence_insert_before (iter, gtk_constraint_variable_ref (variable));

  set->age += 1;

  return TRUE;
}

/*< private >
 * gtk_constraint_variable_set_remove:
 * @set: a `GtkConstraintVariable`Set
 * @variable: a `GtkConstraintVariable`
 *
 * Removes @variable from the @set.
 *
 * This function will release the reference on @variable held by the @set.
 *
 * Returns: %TRUE if the variable was removed from the set, and %FALSE
 *   otherwise
 */
gboolean
gtk_constraint_variable_set_remove (GtkConstraintVariableSet *set,
                                    GtkConstraintVariable *variable)
{
  GSequenceIter *iter;

  iter = g_sequence_lookup (set->set, variable, sort_by_variable_id, NULL);
  if (iter != NULL)
    {
      g_sequence_remove (iter);
      set->age += 1;

      return TRUE;
    }

  return FALSE;
}

/*< private >
 * gtk_constraint_variable_set_size:
 * @set: a `GtkConstraintVariable`Set
 *
 * Retrieves the size of the @set.
 *
 * Returns: the number of variables in the set
 */
int
gtk_constraint_variable_set_size (GtkConstraintVariableSet *set)
{
  return g_sequence_get_length (set->set);
}

gboolean
gtk_constraint_variable_set_is_empty (GtkConstraintVariableSet *set)
{
  return g_sequence_is_empty (set->set);
}

gboolean
gtk_constraint_variable_set_is_singleton (GtkConstraintVariableSet *set)
{
  return g_sequence_iter_next (g_sequence_get_begin_iter (set->set)) == g_sequence_get_end_iter (set->set);
}

/*< private >
 * GtkConstraintVariableSetIter:
 *
 * An iterator type for `GtkConstraintVariable`Set.
 */
/* Keep in sync with GtkConstraintVariableSetIter */
typedef struct {
  GtkConstraintVariableSet *set;
  GSequenceIter *iter;
  gint64 age;
} RealVariableSetIter;

#define REAL_VARIABLE_SET_ITER(i)       ((RealVariableSetIter *) (i))

/*< private >
 * gtk_constraint_variable_set_iter_init:
 * @iter: a `GtkConstraintVariable`SetIter
 * @set: the `GtkConstraintVariable`Set to iterate
 *
 * Initializes @iter for iterating over @set.
 */
void
gtk_constraint_variable_set_iter_init (GtkConstraintVariableSetIter *iter,
                                       GtkConstraintVariableSet *set)
{
  RealVariableSetIter *riter = REAL_VARIABLE_SET_ITER (iter);

  g_return_if_fail (iter != NULL);
  g_return_if_fail (set != NULL);

  riter->set = set;
  riter->iter = g_sequence_get_begin_iter (set->set);
  riter->age = set->age;
}

/*< private >
 * gtk_constraint_variable_set_iter_next:
 * @iter: a `GtkConstraintVariable`SetIter
 * @variable_p: (out): the next variable in the set
 *
 * Advances the @iter to the next variable in the `GtkConstraintVariable`Set.
 *
 * Returns: %TRUE if the iterator was advanced, and %FALSE otherwise
 */
gboolean
gtk_constraint_variable_set_iter_next (GtkConstraintVariableSetIter *iter,
                                       GtkConstraintVariable **variable_p)
{
  RealVariableSetIter *riter = REAL_VARIABLE_SET_ITER (iter);

  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (variable_p != NULL, FALSE);

  g_assert (riter->age == riter->set->age);

  if (g_sequence_iter_is_end (riter->iter))
    return FALSE;

  *variable_p = g_sequence_get (riter->iter);
  riter->iter = g_sequence_iter_next (riter->iter);

  return TRUE;
}

/*< private >
 * gtk_constraint_variable_pair_new:
 * @first: a `GtkConstraintVariable`
 * @second: a `GtkConstraintVariable`
 *
 * Creates a new `GtkConstraintVariable`Pair, containing @first and @second.
 *
 * The `GtkConstraintVariable`Pair acquires a reference over the two
 * given `GtkConstraintVariable`s.
 *
 * Returns: a new `GtkConstraintVariable`Pair
 */
GtkConstraintVariablePair *
gtk_constraint_variable_pair_new (GtkConstraintVariable *first,
                                  GtkConstraintVariable *second)
{
  GtkConstraintVariablePair *res = g_new (GtkConstraintVariablePair, 1);

  res->first = gtk_constraint_variable_ref (first);
  res->second = gtk_constraint_variable_ref (second);

  return res;
}

/*< private >
 * gtk_constraint_variable_pair_free:
 * @pair: a `GtkConstraintVariable`Pair
 *
 * Frees the resources associated by @pair.
 */
void
gtk_constraint_variable_pair_free (GtkConstraintVariablePair *pair)
{
  g_clear_pointer (&pair->first, gtk_constraint_variable_unref);
  g_clear_pointer (&pair->second, gtk_constraint_variable_unref);

  g_free (pair);
}

/* }}} */

/* {{{ Expressions */

/*< private >
 * Term:
 * @variable: a `GtkConstraintVariable`
 * @coefficient: the coefficient applied to the @variable
 * @next: the next term in the expression
 * @prev: the previous term in the expression;
 *
 * A tuple of (@variable, @coefficient) in an equation.
 *
 * The term acquires a reference on the variable.
 */
typedef struct _Term Term;

struct _Term {
  GtkConstraintVariable *variable;
  double coefficient;

  Term *next;
  Term *prev;
};

static Term *
term_new (GtkConstraintVariable *variable,
          double coefficient)
{
  Term *res = g_new (Term, 1);

  res->variable = gtk_constraint_variable_ref (variable);
  res->coefficient = coefficient;
  res->next = res->prev = NULL;

  return res;
}

static void
term_free (gpointer data)
{
  Term *term = data;

  if (term == NULL)
    return;

  gtk_constraint_variable_unref (term->variable);

  g_free (term);
}

struct _GtkConstraintExpression
{
  double constant;

  /* HashTable<Variable, Term>; the key is the term's variable,
   * and the value is owned by the hash table
   */
  GHashTable *terms;

  /* List of terms, in insertion order */
  Term *first_term;
  Term *last_term;

  /* Used by GtkConstraintExpressionIter to guard against changes
   * in the expression while iterating
   */
  gint64 age;
};

/*< private >
 * gtk_constraint_expression_add_term:
 * @self: a `GtkConstraintExpression`
 * @variable: a `GtkConstraintVariable`
 * @coefficient: a coefficient for @variable
 *
 * Adds a new term formed by (@variable, @coefficient) into a
 * `GtkConstraintExpression`.
 *
 * The @expression acquires a reference on @variable.
 */
static void
gtk_constraint_expression_add_term (GtkConstraintExpression *self,
                                    GtkConstraintVariable *variable,
                                    double coefficient)
{
  Term *term;

  if (self->terms == NULL)
    {
      g_assert (self->first_term == NULL && self->last_term == NULL);
      self->terms = g_hash_table_new_full (NULL, NULL,
                                           NULL,
                                           term_free);
    }

  term = term_new (variable, coefficient);

  g_hash_table_insert (self->terms, term->variable, term);

  if (self->first_term == NULL)
    self->first_term = term;

  term->prev = self->last_term;

  if (self->last_term != NULL)
    self->last_term->next = term;

  self->last_term = term;

  /* Increase the age of the expression, so that we can catch
   * mutations from within an iteration over the terms
   */
  self->age += 1;
}

static void
gtk_constraint_expression_remove_term (GtkConstraintExpression *self,
                                       GtkConstraintVariable *variable)
{
  Term *term, *iter;

  if (self->terms == NULL)
    return;

  term = g_hash_table_lookup (self->terms, variable);
  if (term == NULL)
    return;

  /* Keep the variable alive for the duration of the function */
  gtk_constraint_variable_ref (variable);

  iter = self->first_term;
  while (iter != NULL)
    {
      Term *next = iter->next;
      Term *prev = iter->prev;

      if (iter == term)
        {
          if (prev != NULL)
            prev->next = next;
          if (next != NULL)
            next->prev = prev;

          if (iter == self->first_term)
            self->first_term = next;
          if (iter == self->last_term)
            self->last_term = prev;

          iter->next = NULL;
          iter->prev = NULL;

          break;
        }

      iter = next;
    }

  g_hash_table_remove (self->terms, variable);

  gtk_constraint_variable_unref (variable);

  self->age += 1;
}

/*< private >
 * gtk_constraint_expression_new:
 * @constant: a constant for the expression
 *
 * Creates a new `GtkConstraintExpression` with the given @constant.
 *
 * Returns: (transfer full): the newly created expression
 */
GtkConstraintExpression *
gtk_constraint_expression_new (double constant)
{
  GtkConstraintExpression *res = g_rc_box_new (GtkConstraintExpression);

  res->age = 0;
  res->terms = NULL;
  res->first_term = NULL;
  res->last_term = NULL;
  res->constant = constant;

  return res;
}

/*< private >
 * gtk_constraint_expression_new_from_variable:
 * @variable: a `GtkConstraintVariable`
 *
 * Creates a new `GtkConstraintExpression` with the given @variable.
 *
 * Returns: (transfer full): the newly created expression
 */
GtkConstraintExpression *
gtk_constraint_expression_new_from_variable (GtkConstraintVariable *variable)
{
  GtkConstraintExpression *res = gtk_constraint_expression_new (0.0);

  gtk_constraint_expression_add_term (res, variable, 1.0);

  return res;
}

/*< private >
 * gtk_constraint_expression_ref:
 * @expression: a `GtkConstraintExpression`
 *
 * Acquires a reference on @expression.
 *
 * Returns: (transfer full): the @expression, with its reference
 *   count increased
 */
GtkConstraintExpression *
gtk_constraint_expression_ref (GtkConstraintExpression *expression)
{
  g_return_val_if_fail (expression != NULL, NULL);

  return g_rc_box_acquire (expression);
}

static void
gtk_constraint_expression_clear (gpointer data)
{
  GtkConstraintExpression *self = data;

  g_clear_pointer (&self->terms, g_hash_table_unref);

  self->age = 0;
  self->constant = 0.0;
  self->first_term = NULL;
  self->last_term = NULL;
}

/*< private >
 * gtk_constraint_expression_unref:
 * @expression: (transfer full): a `GtkConstraintExpression`
 *
 * Releases a reference on @expression.
 */
void
gtk_constraint_expression_unref (GtkConstraintExpression *expression)
{
  g_rc_box_release_full (expression, gtk_constraint_expression_clear);
}

/*< private >
 * gtk_constraint_expression_is_constant:
 * @expression: a `GtkConstraintExpression`
 *
 * Checks whether @expression is a constant value, with no variable terms.
 *
 * Returns: %TRUE if the @expression is a constant
 */
gboolean
gtk_constraint_expression_is_constant (const GtkConstraintExpression *expression)
{
  return expression->terms == NULL;
}

/*< private >
 * gtk_constraint_expression_set_constant:
 * @expression: a `GtkConstraintExpression`
 * @constant: the value of the constant
 *
 * Sets the value of the constant part of @expression.
 */
void
gtk_constraint_expression_set_constant (GtkConstraintExpression *expression,
                                        double constant)
{
  g_return_if_fail (expression != NULL);

  expression->constant = constant;
}

/*< private >
 * gtk_constraint_expression_get_constant:
 * @expression: a `GtkConstraintExpression`
 *
 * Retrieves the constant value of @expression.
 *
 * Returns: the constant of @expression
 */
double
gtk_constraint_expression_get_constant (const GtkConstraintExpression *expression)
{
  g_return_val_if_fail (expression != NULL, 0.0);

  return expression->constant;
}

GtkConstraintExpression *
gtk_constraint_expression_clone (GtkConstraintExpression *expression)
{
  GtkConstraintExpression *res;
  Term *iter;

  res = gtk_constraint_expression_new (expression->constant);

  iter = expression->first_term;
  while (iter != NULL)
    {
      gtk_constraint_expression_add_term (res, iter->variable, iter->coefficient);

      iter = iter->next;
    }

  return res;
}

/*< private >
 * gtk_constraint_expression_add_variable:
 * @expression: a `GtkConstraintExpression`
 * @variable: a `GtkConstraintVariable` to add to @expression
 * @coefficient: the coefficient of @variable
 * @subject: (nullable): a `GtkConstraintVariable`
 * @solver: (nullable): a `GtkConstraintSolver`
 *
 * Adds a `(@coefficient × @variable)` term to @expression.
 *
 * If @expression already contains a term for @variable, this function will
 * update its coefficient.
 *
 * If @coefficient is 0 and @expression already contains a term for @variable,
 * the term for @variable will be removed.
 *
 * This function will notify @solver if @variable is added or removed from
 * the @expression.
 */
void
gtk_constraint_expression_add_variable (GtkConstraintExpression *expression,
                                        GtkConstraintVariable *variable,
                                        double coefficient,
                                        GtkConstraintVariable *subject,
                                        GtkConstraintSolver *solver)
{
  /* If the expression already contains the variable, update the coefficient */
  if (expression->terms != NULL)
    {
      Term *t = g_hash_table_lookup (expression->terms, variable);

      if (t != NULL)
        {
          double new_coefficient = t->coefficient + coefficient;

          /* Setting the coefficient to 0 will remove the variable */
          if (G_APPROX_VALUE (new_coefficient, 0.0, 0.001))
            {
              /* Update the tableau if needed */
              if (solver != NULL)
                gtk_constraint_solver_note_removed_variable (solver, variable, subject);

              gtk_constraint_expression_remove_term (expression, variable);
            }
          else
            {
              t->coefficient = new_coefficient;
            }

          return;
        }
    }

  /* Otherwise, add the variable if the coefficient is non-zero */
  if (!G_APPROX_VALUE (coefficient, 0.0, 0.001))
    {
      gtk_constraint_expression_add_term (expression, variable, coefficient);

      if (solver != NULL)
        gtk_constraint_solver_note_added_variable (solver, variable, subject);
    }
}

/*< private >
 * gtk_constraint_expression_remove_variable:
 * @expression: a `GtkConstraintExpression`
 * @variable: a `GtkConstraintVariable`
 *
 * Removes @variable from @expression.
 */
void
gtk_constraint_expression_remove_variable (GtkConstraintExpression *expression,
                                           GtkConstraintVariable *variable)
{
  g_return_if_fail (expression != NULL);
  g_return_if_fail (variable != NULL);

  gtk_constraint_expression_remove_term (expression, variable);
}

/*< private >
 * gtk_constraint_expression_set_variable:
 * @expression: a `GtkConstraintExpression`
 * @variable: a `GtkConstraintVariable`
 * @coefficient: a coefficient for @variable
 *
 * Sets the @coefficient for @variable inside an @expression.
 *
 * If the @expression does not contain a term for @variable, a new
 * one will be added.
 */
void
gtk_constraint_expression_set_variable (GtkConstraintExpression *expression,
                                        GtkConstraintVariable *variable,
                                        double coefficient)
{
  if (expression->terms != NULL)
    {
      Term *t = g_hash_table_lookup (expression->terms, variable);

      if (t != NULL)
        {
          t->coefficient = coefficient;
          return;
        }
    }

  gtk_constraint_expression_add_term (expression, variable, coefficient);
}

/*< private >
 * gtk_constraint_expression_add_expression:
 * @a_expr: first operand
 * @b_expr: second operand
 * @n: the multiplication factor for @b_expr
 * @subject: (nullable): a `GtkConstraintVariable`
 * @solver: (nullable): a `GtkConstraintSolver`
 *
 * Adds `(@n × @b_expr)` to @a_expr.
 *
 * Typically, this function is used to turn two expressions in the
 * form:
 *
 * |[
 *   a.x + a.width = b.x + b.width
 * ]|
 *
 * into a single expression:
 *
 * |[
 *   a.x + a.width - b.x - b.width = 0
 * ]|
 *
 * If @solver is not %NULL, this function will notify a `GtkConstraintSolver`
 * of every variable that was added or removed from @a_expr.
 */
void
gtk_constraint_expression_add_expression (GtkConstraintExpression *a_expr,
                                          GtkConstraintExpression *b_expr,
                                          double n,
                                          GtkConstraintVariable *subject,
                                          GtkConstraintSolver *solver)
{
  Term *iter;

  a_expr->constant += (n * b_expr->constant);

  iter = b_expr->last_term;
  while (iter != NULL)
    {
      Term *next = iter->prev;

      gtk_constraint_expression_add_variable (a_expr,
                                              iter->variable, n * iter->coefficient,
                                              subject,
                                              solver);

      iter = next;
    }
}

/*< private >
 * gtk_constraint_expression_plus_constant:
 * @expression: a `GtkConstraintExpression`
 * @constant: a constant value
 *
 * Adds a @constant value to the @expression.
 *
 * This is the equivalent of creating a new `GtkConstraintExpression` for
 * the @constant and calling gtk_constraint_expression_add_expression().
 *
 * Returns: the @expression
 */
GtkConstraintExpression *
gtk_constraint_expression_plus_constant (GtkConstraintExpression *expression,
                                         double constant)
{
  GtkConstraintExpression *e;

  e = gtk_constraint_expression_new (constant);
  gtk_constraint_expression_add_expression (expression, e, 1.0, NULL, NULL);
  gtk_constraint_expression_unref (e);

  return expression;
}

/*< private >
 * gtk_constraint_expression_minus_constant:
 * @expression: a `GtkConstraintExpression`
 * @constant: a constant value
 *
 * Removes a @constant value from the @expression.
 *
 * This is the equivalent of creating a new `GtkConstraintExpression` for
 * the inverse of @constant and calling gtk_constraint_expression_add_expression().
 *
 * Returns: the @expression
 */
GtkConstraintExpression *
gtk_constraint_expression_minus_constant (GtkConstraintExpression *expression,
                                          double constant)
{
  return gtk_constraint_expression_plus_constant (expression, constant * -1.0);
}

/*< private >
 * gtk_constraint_expression_plus_variable:
 * @expression: a `GtkConstraintExpression`
 * @variable: a `GtkConstraintVariable`
 *
 * Adds a @variable to the @expression.
 *
 * Returns: the @expression
 */
GtkConstraintExpression *
gtk_constraint_expression_plus_variable (GtkConstraintExpression *expression,
                                         GtkConstraintVariable *variable)
{
  GtkConstraintExpression *e;

  e = gtk_constraint_expression_new_from_variable (variable);
  gtk_constraint_expression_add_expression (expression, e, 1.0, NULL, NULL);
  gtk_constraint_expression_unref (e);

  return expression;
}

/*< private >
 * gtk_constraint_expression_minus_variable:
 * @expression: a `GtkConstraintExpression`
 * @variable: a `GtkConstraintVariable`
 *
 * Subtracts a @variable from the @expression.
 *
 * Returns: the @expression
 */
GtkConstraintExpression *
gtk_constraint_expression_minus_variable (GtkConstraintExpression *expression,
                                          GtkConstraintVariable *variable)
{
  GtkConstraintExpression *e;

  e = gtk_constraint_expression_new_from_variable (variable);
  gtk_constraint_expression_add_expression (expression, e, -1.0, NULL, NULL);
  gtk_constraint_expression_unref (e);

  return expression;
}

/*< private >
 * gtk_constraint_expression_multiply_by:
 * @expression: a `GtkConstraintExpression`
 * @factor: the multiplication factor
 *
 * Multiplies the constant part and the coefficient of all terms
 * in @expression with the given @factor.
 *
 * Returns: the @expression
 */
GtkConstraintExpression *
gtk_constraint_expression_multiply_by (GtkConstraintExpression *expression,
                                       double factor)
{
  GHashTableIter iter;
  gpointer value_p;

  expression->constant *= factor;

  if (expression->terms == NULL)
    return expression;

  g_hash_table_iter_init (&iter, expression->terms);
  while (g_hash_table_iter_next (&iter, NULL, &value_p))
    {
      Term *t = value_p;

      t->coefficient *= factor;
    }

  return expression;
}

/*< private >
 * gtk_constraint_expression_divide_by:
 * @expression: a `GtkConstraintExpression`
 * @factor: the division factor
 *
 * Divides the constant part and the coefficient of all terms
 * in @expression by the given @factor.
 *
 * Returns: the @expression
 */
GtkConstraintExpression *
gtk_constraint_expression_divide_by (GtkConstraintExpression *expression,
                                     double factor)
{
  if (G_APPROX_VALUE (factor, 0.0, 0.001))
    return expression;

  return gtk_constraint_expression_multiply_by (expression, 1.0 / factor);
}

/*< private >
 * gtk_constraint_expression_new_subject:
 * @expression: a `GtkConstraintExpression`
 * @subject: a `GtkConstraintVariable` part of @expression
 *
 * Modifies @expression to have a new @subject.
 *
 * A `GtkConstraintExpression` is a linear expression in the form of
 * `@expression = 0`. If @expression contains @subject, for instance:
 *
 * |[
 *   c + (a × @subject) + (a1 × v1) + … + (an × vn) = 0
 * ]|
 *
 * this function will make @subject the new subject of the expression:
 *
 * |[
 *   subject = - (c / a) - ((a1 / a) × v1) - … - ((an / a) × vn) = 0
 * ]|
 *
 * The term @subject is removed from the @expression.
 *
 * Returns: the reciprocal of the coefficient of @subject, so we
 *   can use this function in gtk_constraint_expression_change_subject()
 */
double
gtk_constraint_expression_new_subject (GtkConstraintExpression *expression,
                                       GtkConstraintVariable *subject)
{
  double reciprocal = 1.0;
  Term *term;

  g_assert (!gtk_constraint_expression_is_constant (expression));

  term = g_hash_table_lookup (expression->terms, subject);
  g_assert (term != NULL);
  g_assert (!G_APPROX_VALUE (term->coefficient, 0.0, 0.001));

  reciprocal = 1.0 / term->coefficient;

  gtk_constraint_expression_remove_term (expression, subject);
  gtk_constraint_expression_multiply_by (expression, -reciprocal);

  return reciprocal;
}

/*< private >
 * gtk_constraint_expression_change_subject:
 * @expression: a `GtkConstraintExpression`
 * @old_subject: the old subject `GtkConstraintVariable` of @expression
 * @new_subject: the new subject `GtkConstraintVariable` of @expression
 *
 * Turns an @expression in the form of:
 *
 * |[
 *   old_subject = c + (a × new_subject) + (a1 × v1) + … + (an × vn)
 * ]|
 *
 * into the form of:
 *
 * |[
 *   new_subject = -c / a + old_subject / a - ((a1 / a) × v1) - … - ((an / a) × vn)
 * ]|
 *
 * Which means resolving @expression for @new_subject.
 */
void
gtk_constraint_expression_change_subject (GtkConstraintExpression *expression,
                                          GtkConstraintVariable *old_subject,
                                          GtkConstraintVariable *new_subject)
{
  double reciprocal;

  g_return_if_fail (expression != NULL);
  g_return_if_fail (old_subject != NULL);
  g_return_if_fail (new_subject != NULL);

  reciprocal = gtk_constraint_expression_new_subject (expression, new_subject);
  gtk_constraint_expression_set_variable (expression, old_subject, reciprocal);
}

/*< private >
 * gtk_constraint_expression_get_coefficient:
 * @expression: a `GtkConstraintExpression`
 * @variable: a `GtkConstraintVariable`
 *
 * Retrieves the coefficient of the term for @variable inside @expression.
 *
 * Returns: the coefficient of @variable
 */
double
gtk_constraint_expression_get_coefficient (GtkConstraintExpression *expression,
                                           GtkConstraintVariable *variable)
{
  const Term *term;

  g_return_val_if_fail (expression != NULL, 0.0);
  g_return_val_if_fail (variable != NULL, 0.0);

  if (expression->terms == NULL)
    return 0.0;

  term = g_hash_table_lookup (expression->terms, variable);
  if (term == NULL)
    return 0.0;

  return term->coefficient;
}

/*< private >
 * gtk_constraint_expression_substitute_out:
 * @expression: a `GtkConstraintExpression`
 * @out_var: the variable to replace
 * @expr: the expression used to replace @out_var
 * @subject: (nullable): a `GtkConstraintVariable`
 * @solver: (nullable): a `GtkConstraintSolver`
 *
 * Replaces every term containing @out_var inside @expression with @expr.
 *
 * If @solver is not %NULL, this function will notify the `GtkConstraintSolver`
 * for every variable added to or removed from @expression.
 */
void
gtk_constraint_expression_substitute_out (GtkConstraintExpression *expression,
                                          GtkConstraintVariable *out_var,
                                          GtkConstraintExpression *expr,
                                          GtkConstraintVariable *subject,
                                          GtkConstraintSolver *solver)
{
  double multiplier;
  Term *iter;

  if (expression->terms == NULL)
    return;

  multiplier = gtk_constraint_expression_get_coefficient (expression, out_var);
  gtk_constraint_expression_remove_term (expression, out_var);

  expression->constant = expression->constant + multiplier * expr->constant;

  iter = expr->first_term;
  while (iter != NULL)
    {
      GtkConstraintVariable *clv = iter->variable;
      double coeff = iter->coefficient;
      Term *next = iter->next;

      if (expression->terms != NULL &&
          g_hash_table_contains (expression->terms, clv))
        {
          double old_coefficient = gtk_constraint_expression_get_coefficient (expression, clv);
          double new_coefficient = old_coefficient + multiplier * coeff;

          if (G_APPROX_VALUE (new_coefficient, 0.0, 0.001))
            {
              if (solver != NULL)
                gtk_constraint_solver_note_removed_variable (solver, clv, subject);

              gtk_constraint_expression_remove_term (expression, clv);
            }
          else
            gtk_constraint_expression_set_variable (expression, clv, new_coefficient);
        }
      else
        {
          gtk_constraint_expression_set_variable (expression, clv, multiplier * coeff);

          if (solver != NULL)
            gtk_constraint_solver_note_added_variable (solver, clv, subject);
        }

      iter = next;
    }
}

/*< private >
 * gtk_constraint_expression_get_pivotable_variable:
 * @expression: a `GtkConstraintExpression`
 *
 * Retrieves the first `GtkConstraintVariable` in @expression that
 * is marked as pivotable.
 *
 * Returns: (transfer none) (nullable): a `GtkConstraintVariable`
 */
GtkConstraintVariable *
gtk_constraint_expression_get_pivotable_variable (GtkConstraintExpression *expression)
{
  Term *iter;

  if (expression->terms == NULL)
    {
      g_critical ("Expression %p is a constant", expression);
      return NULL;
    }

  iter = expression->first_term;
  while (iter != NULL)
    {
      Term *next = iter->next;

      if (gtk_constraint_variable_is_pivotable (iter->variable))
        return iter->variable;

      iter = next;
    }

  return NULL;
}

/*< private >
 * gtk_constraint_expression_to_string:
 * @expression: a `GtkConstraintExpression`
 *
 * Creates a string containing @expression.
 *
 * This function is only useful for debugging.
 *
 * Returns: (transfer full): a string containing the given expression
 */
char *
gtk_constraint_expression_to_string (const GtkConstraintExpression *expression)
{
  gboolean needs_plus = FALSE;
  GString *buf;
  Term *iter;

  if (expression == NULL)
    return g_strdup ("<null>");

  buf = g_string_new (NULL);

  if (!G_APPROX_VALUE (expression->constant, 0.0, 0.001))
    {
      g_string_append_printf (buf, "%g", expression->constant);

      if (expression->terms != NULL)
        needs_plus = TRUE;
    }

  if (expression->terms == NULL)
    return g_string_free (buf, FALSE);

  iter = expression->first_term;
  while (iter != NULL)
    {
      char *str = gtk_constraint_variable_to_string (iter->variable);
      Term *next = iter->next;

      if (needs_plus)
        g_string_append (buf, " + ");

      if (G_APPROX_VALUE (iter->coefficient, 1.0, 0.001))
        g_string_append_printf (buf, "%s", str);
      else
        g_string_append_printf (buf, "(%g * %s)", iter->coefficient, str);

      g_free (str);

      if (!needs_plus)
        needs_plus = TRUE;

      iter = next;
    }

  return g_string_free (buf, FALSE);
}

/* Keep in sync with GtkConstraintExpressionIter */
typedef struct {
  GtkConstraintExpression *expression;
  Term *current;
  gint64 age;
} RealExpressionIter;

#define REAL_EXPRESSION_ITER(i) ((RealExpressionIter *) (i))

/*< private >
 * gtk_constraint_expression_iter_init:
 * @iter: a `GtkConstraintExpression`Iter
 * @expression: a `GtkConstraintExpression`
 *
 * Initializes an iterator over @expression.
 */
void
gtk_constraint_expression_iter_init (GtkConstraintExpressionIter *iter,
                                     GtkConstraintExpression *expression)
{
  RealExpressionIter *riter = REAL_EXPRESSION_ITER (iter);

  riter->expression = expression;
  riter->current = NULL;
  riter->age = expression->age;
}

/*< private >
 * gtk_constraint_expression_iter_next:
 * @iter: a valid `GtkConstraintExpression`Iter
 * @variable: (out): the variable of the next term
 * @coefficient: (out): the coefficient of the next term
 *
 * Moves the given `GtkConstraintExpression`Iter forwards to the next
 * term in the expression, starting from the first term.
 *
 * Returns: %TRUE if the iterator was moved, and %FALSE if the iterator
 *   has reached the end of the terms of the expression
 */
gboolean
gtk_constraint_expression_iter_next (GtkConstraintExpressionIter *iter,
                                     GtkConstraintVariable **variable,
                                     double *coefficient)
{
  RealExpressionIter *riter = REAL_EXPRESSION_ITER (iter);

  g_assert (riter->age == riter->expression->age);

  if (riter->current == NULL)
    riter->current = riter->expression->first_term;
  else
    riter->current = riter->current->next;

  if (riter->current != NULL)
    {
      *coefficient = riter->current->coefficient;
      *variable = riter->current->variable;
    }

  return riter->current != NULL;
}

/*< private >
 * gtk_constraint_expression_iter_prev:
 * @iter: a valid `GtkConstraintExpression`Iter
 * @variable: (out): the variable of the previous term
 * @coefficient: (out): the coefficient of the previous term
 *
 * Moves the given `GtkConstraintExpression`Iter backwards to the previous
 * term in the expression, starting from the last term.
 *
 * Returns: %TRUE if the iterator was moved, and %FALSE if the iterator
 *   has reached the beginning of the terms of the expression
 */
gboolean
gtk_constraint_expression_iter_prev (GtkConstraintExpressionIter *iter,
                                     GtkConstraintVariable **variable,
                                     double *coefficient)
{
  RealExpressionIter *riter = REAL_EXPRESSION_ITER (iter);

  g_assert (riter->age == riter->expression->age);

  if (riter->current == NULL)
    riter->current = riter->expression->last_term;
  else
    riter->current = riter->current->prev;

  if (riter->current != NULL)
    {
      *coefficient = riter->current->coefficient;
      *variable = riter->current->variable;
    }

  return riter->current != NULL;
}

typedef enum {
  BUILDER_OP_NONE,
  BUILDER_OP_PLUS,
  BUILDER_OP_MINUS,
  BUILDER_OP_MULTIPLY,
  BUILDER_OP_DIVIDE
} BuilderOpType;

typedef struct
{
  GtkConstraintExpression *expression;
  GtkConstraintSolver *solver;
  int op;
} RealExpressionBuilder;

#define REAL_EXPRESSION_BUILDER(b) ((RealExpressionBuilder *) (b))

/*< private >
 * gtk_constraint_expression_builder_init:
 * @builder: a `GtkConstraintExpression`Builder
 * @solver: a `GtkConstraintSolver`
 *
 * Initializes the given `GtkConstraintExpression`Builder for the
 * given `GtkConstraintSolver`.
 *
 * You can use the @builder to construct expressions to be added to the
 * @solver, in the form of constraints.
 *
 * A typical use is:
 *
 * |[<!-- language="C" -->
 *   GtkConstraintExpressionBuilder builder;
 *
 *   // "solver" is set in another part of the code
 *   gtk_constraint_expression_builder_init (&builder, solver);
 *
 *   // "width" is set in another part of the code
 *   gtk_constraint_expression_builder_term (&builder, width);
 *   gtk_constraint_expression_builder_divide_by (&builder);
 *   gtk_constraint_expression_builder_constant (&builder, 2.0);
 *
 *   // "left" is set in another part of the code
 *   gtk_constraint_expression_builder_plus (&builder);
 *   gtk_constraint_expression_builder_term (&builder, left);
 *
 *   // "expr" now contains the following expression:
 *   //     width / 2.0 + left
 *   GtkConstraintExpression *expr =
 *     gtk_constraint_expression_builder_finish (&builder);
 *
 *   // The builder is inert, and can be re-used by calling
 *   // gtk_constraint_expression_builder_init() again.
 * ]|
 */
void
gtk_constraint_expression_builder_init (GtkConstraintExpressionBuilder *builder,
                                        GtkConstraintSolver *solver)
{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);

  rbuilder->solver = solver;
  rbuilder->expression = gtk_constraint_expression_new (0);
  rbuilder->op = BUILDER_OP_NONE;
}

/*< private >
 * gtk_constraint_expression_builder_term:
 * @builder: a `GtkConstraintExpression`Builder
 * @term: a `GtkConstraintVariable`
 *
 * Adds a variable @term to the @builder.
 */
void
gtk_constraint_expression_builder_term (GtkConstraintExpressionBuilder *builder,
                                        GtkConstraintVariable *term)
{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);
  GtkConstraintExpression *expr;

  expr = gtk_constraint_expression_new_from_variable (term);

  switch (rbuilder->op)
    {
    case BUILDER_OP_NONE:
      g_clear_pointer (&rbuilder->expression, gtk_constraint_expression_unref);
      rbuilder->expression = g_steal_pointer (&expr);
      break;

    case BUILDER_OP_PLUS:
      gtk_constraint_expression_add_expression (rbuilder->expression,
                                                expr, 1.0,
                                                NULL,
                                                NULL);
      gtk_constraint_expression_unref (expr);
      break;

    case BUILDER_OP_MINUS:
      gtk_constraint_expression_add_expression (rbuilder->expression,
                                                expr, -1.0,
                                                NULL,
                                                NULL);
      gtk_constraint_expression_unref (expr);
      break;

    default:
      break;
    }

  rbuilder->op = BUILDER_OP_NONE;
}

/*< private >
 * gtk_constraint_expression_builder_plus:
 * @builder: a `GtkConstraintExpression`Builder
 *
 * Adds a plus operator to the @builder.
 */
void
gtk_constraint_expression_builder_plus (GtkConstraintExpressionBuilder *builder)
{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);

  rbuilder->op = BUILDER_OP_PLUS;
}

/*< private >
 * gtk_constraint_expression_builder_minus:
 * @builder: a `GtkConstraintExpression`Builder
 *
 * Adds a minus operator to the @builder.
 */
void
gtk_constraint_expression_builder_minus (GtkConstraintExpressionBuilder *builder)
{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);

  rbuilder->op = BUILDER_OP_MINUS;
}

/*< private >
 * gtk_constraint_expression_builder_divide_by:
 * @builder: a `GtkConstraintExpression`Builder
 *
 * Adds a division operator to the @builder.
 */
void
gtk_constraint_expression_builder_divide_by (GtkConstraintExpressionBuilder *builder)
{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);

  rbuilder->op = BUILDER_OP_DIVIDE;
}

/*< private >
 * gtk_constraint_expression_builder_multiply_by:
 * @builder: a `GtkConstraintExpression`Builder
 *
 * Adds a multiplication operator to the @builder.
 */
void
gtk_constraint_expression_builder_multiply_by (GtkConstraintExpressionBuilder *builder)

{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);

  rbuilder->op = BUILDER_OP_MULTIPLY;
}

/*< private >
 * gtk_constraint_expression_builder_constant:
 * @builder: a `GtkConstraintExpression`Builder
 * @value: a constant value
 *
 * Adds a constant value to the @builder.
 */
void
gtk_constraint_expression_builder_constant (GtkConstraintExpressionBuilder *builder,
                                            double value)
{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);

  switch (rbuilder->op)
    {
    case BUILDER_OP_NONE:
      gtk_constraint_expression_set_constant (rbuilder->expression, value);
      break;

    case BUILDER_OP_PLUS:
      gtk_constraint_expression_plus_constant (rbuilder->expression, value);
      break;

    case BUILDER_OP_MINUS:
      gtk_constraint_expression_minus_constant (rbuilder->expression, value);
      break;

    case BUILDER_OP_MULTIPLY:
      gtk_constraint_expression_multiply_by (rbuilder->expression, value);
      break;

    case BUILDER_OP_DIVIDE:
      gtk_constraint_expression_divide_by (rbuilder->expression, value);
      break;

    default:
      break;
    }

  rbuilder->op = BUILDER_OP_NONE;
}

/*< private >
 * gtk_constraint_expression_builder_finish:
 * @builder: a `GtkConstraintExpression`Builder
 *
 * Closes the given expression builder, and returns the expression.
 *
 * You can only call this function once.
 *
 * Returns: (transfer full): the built expression
 */
GtkConstraintExpression *
gtk_constraint_expression_builder_finish (GtkConstraintExpressionBuilder *builder)
{
  RealExpressionBuilder *rbuilder = REAL_EXPRESSION_BUILDER (builder);

  rbuilder->solver = NULL;
  rbuilder->op = BUILDER_OP_NONE;

  return g_steal_pointer (&rbuilder->expression);
}

/* }}} */