i-slint-compiler 1.18.0

Internal Slint Compiler Library
Documentation
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
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

/*!
 This module contains the intermediate representation of the code in the form of an object tree
*/

// cSpell: ignore qualname

use crate::diagnostics::{BuildDiagnostics, SourceLocation, Spanned};
use crate::expression_tree::{
    self, BindingExpression, Callable, ConditionLocation, Expression, Unit,
};
use crate::langtype::{
    BuiltinElement, Enumeration, EnumerationValue, Function, NativeClass, Struct, StructName, Type,
};
use crate::langtype::{ElementType, PropertyLookupMode, PropertyLookupResult};
use crate::layout::{LayoutConstraints, Orientation};
use crate::namedreference::NamedReference;
use crate::parser::{SyntaxKind, SyntaxNode, syntax_nodes};
use crate::typeloader::{ImportKind, ImportedTypes, LibraryInfo};
use crate::typeregister::TypeRegister;
use crate::{parser, reject_experimental_feature};
use itertools::Either;
use smol_str::{SmolStr, ToSmolStr, format_smolstr};
use std::cell::{Cell, OnceCell, Ref, RefCell, RefMut};
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::Display;
use std::path::PathBuf;
use std::rc::{Rc, Weak};
use std::sync::Arc;

pub(crate) mod forward_inherited_expression;
mod interfaces;

macro_rules! unwrap_or_continue {
    ($e:expr ; $diag:expr) => {
        match $e {
            Some(x) => x,
            None => {
                debug_assert!($diag.has_errors()); // error should have been reported at parsing time
                continue;
            }
        }
    };
}

/// The full document (a complete file)
#[derive(Default)]
pub struct Document {
    pub node: Option<syntax_nodes::Document>,
    pub inner_components: Vec<Rc<Component>>,
    pub inner_types: Vec<Type>,
    pub local_registry: TypeRegister,
    /// A list of paths to .ttf/.ttc files that are supposed to be registered on
    /// startup for custom font use.
    pub custom_fonts: Vec<(SmolStr, crate::parser::SyntaxToken)>,
    pub exports: Exports,
    pub imports: Vec<ImportedTypes>,
    pub library_exports: HashMap<String, LibraryInfo>,

    /// Resources to embed in the generated code.
    ///
    /// The [`crate::embedded_resources::EmbeddedResourcesIdx`] is the identifier used by code generators.
    /// Each entry's `path` is the absolute path on disk, or `None` for in-memory data URI payloads.
    pub embedded_file_resources: RefCell<
        typed_index_collections::TiVec<
            crate::embedded_resources::EmbeddedResourcesIdx,
            crate::embedded_resources::EmbeddedResources,
        >,
    >,

    #[cfg(feature = "bundle-translations")]
    pub translation_builder: Option<crate::translations::TranslationsBuilder>,

    /// The list of used extra types used recursively.
    pub used_types: RefCell<UsedSubTypes>,

    /// The popup_menu_impl
    pub popup_menu_impl: Option<Rc<Component>>,
}

impl Document {
    pub fn from_node(
        node: syntax_nodes::Document,
        imports: Vec<ImportedTypes>,
        reexports: Exports,
        diag: &mut BuildDiagnostics,
        parent_registry: &Rc<RefCell<TypeRegister>>,
        ignore_missing_font_files: bool,
        symbol_counters: &Rc<crate::symbol_counters::SymbolCounters>,
    ) -> Self {
        debug_assert_eq!(node.kind(), SyntaxKind::Document);

        let mut local_registry = TypeRegister::new(parent_registry);
        let mut inner_components = Vec::new();
        let mut inner_types = Vec::new();

        // Named imports are part of the subset, the other two forms aren't.
        // The path rules are enforced in the type loader, which is where a
        // path is resolved.
        #[cfg(feature = "slint-sc")]
        for import in &imports {
            match import.import_kind {
                ImportKind::ImportList(_) => {}
                ImportKind::FileImport => {
                    diag.slint_sc_error("File imports are", &import.import_uri_token)
                }
                ImportKind::ModuleReexport(_) => {
                    diag.slint_sc_error("Re-exports are", &import.import_uri_token)
                }
            }
        }

        let mut process_component =
            |n: syntax_nodes::Component,
             diag: &mut BuildDiagnostics,
             local_registry: &mut TypeRegister| {
                let compo = Component::from_node(n, diag, local_registry);
                if !local_registry.add(compo.clone()) {
                    diag.push_warning(format!("Component '{}' is replacing a previously defined component with the same name", compo.id), &compo.node.clone().unwrap().DeclaredIdentifier());
                }
                inner_components.push(compo);
            };
        let process_struct = |n: syntax_nodes::StructDeclaration,
                              diag: &mut BuildDiagnostics,
                              local_registry: &mut TypeRegister,
                              inner_types: &mut Vec<Type>| {
            let ty = type_struct_from_node(
                n.ObjectType(),
                diag,
                local_registry,
                parser::identifier_text(&n.DeclaredIdentifier()),
                Some(symbol_counters),
            );
            assert!(matches!(ty, Type::Struct(_)));
            if !local_registry.insert_type(ty.clone()) {
                diag.push_warning(
                    format!(
                        "Struct '{ty}' is replacing a previously defined type with the same name"
                    ),
                    &n.DeclaredIdentifier(),
                );
            }
            inner_types.push(ty);
        };
        let process_enum = |n: syntax_nodes::EnumDeclaration,
                            diag: &mut BuildDiagnostics,
                            local_registry: &mut TypeRegister,
                            inner_types: &mut Vec<Type>| {
            let Some(name) = parser::identifier_text(&n.DeclaredIdentifier()) else {
                assert!(diag.has_errors());
                return;
            };
            let mut existing_names = HashSet::new();
            let values = n
                .EnumValue()
                .filter_map(|v| {
                    let value = parser::identifier_text(&v)?;
                    if value == name {
                        diag.push_error(
                            format!("Enum '{value}' can't have a value with the same name"),
                            &v,
                        );
                        None
                    } else if !existing_names.insert(crate::generator::to_pascal_case(&value)) {
                        diag.push_error(format!("Duplicated enum value '{value}'"), &v);
                        None
                    } else {
                        Some(value)
                    }
                })
                .collect();
            let en = Enumeration {
                name: name.clone(),
                values,
                default_value: 0,
                node: Some(n.to_source_location()),
                rust_attributes: n
                    .AtRustAttr()
                    .map(|a| SmolStr::from(a.text().to_string()))
                    .collect(),
            };
            if en.values.is_empty() {
                diag.push_error("Enums must have at least one value".into(), &n);
            }

            let ty = Type::Enumeration(Arc::new(en));
            if !local_registry.insert_type_with_name(ty.clone(), name.clone()) {
                diag.push_warning(
                    format!(
                        "Enum '{name}' is replacing a previously defined type with the same name"
                    ),
                    &n.DeclaredIdentifier(),
                );
            }
            inner_types.push(ty);
        };

        for n in node.children() {
            match n.kind() {
                SyntaxKind::Component => {
                    process_component(n.into(), diag, &mut local_registry);
                }
                SyntaxKind::StructDeclaration => {
                    process_struct(n.into(), diag, &mut local_registry, &mut inner_types)
                }
                SyntaxKind::EnumDeclaration => {
                    process_enum(n.into(), diag, &mut local_registry, &mut inner_types)
                }
                SyntaxKind::ExportsList => {
                    for n in n.children() {
                        match n.kind() {
                            SyntaxKind::Component => {
                                process_component(n.into(), diag, &mut local_registry)
                            }
                            SyntaxKind::StructDeclaration => process_struct(
                                n.into(),
                                diag,
                                &mut local_registry,
                                &mut inner_types,
                            ),
                            SyntaxKind::EnumDeclaration => {
                                process_enum(n.into(), diag, &mut local_registry, &mut inner_types)
                            }
                            _ => {}
                        }
                    }
                }
                _ => {}
            };
        }
        let mut exports = Exports::from_node(&node, &inner_components, &local_registry, diag);
        exports.add_reexports(reexports, diag);

        let custom_fonts = imports
            .iter()
            .filter(|import| matches!(import.import_kind, ImportKind::FileImport))
            .filter_map(|import| {
                if crate::pathutils::is_font_file(&import.file) {
                    let token_path = import.import_uri_token.source_file.path();
                    let import_file_path = PathBuf::from(import.file.clone());
                    let import_file_path = crate::pathutils::join(token_path, &import_file_path)
                        .unwrap_or(import_file_path);

                    // Assume remote urls are valid, we need to load them at run-time (which we currently don't). For
                    // local paths we should try to verify the existence and let the developer know ASAP.
                    // When the resource URL mapper is set (e.g. remote viewer), fonts are
                    // delivered out-of-band; skip the local existence check.
                    if ignore_missing_font_files
                        || crate::pathutils::is_url(&import_file_path)
                        || crate::fileaccess::load_file(std::path::Path::new(&import_file_path))
                            .is_some()
                    {
                        Some((import_file_path.to_string_lossy().into(), import.import_uri_token.clone()))
                    } else {
                        diag.push_error(
                            format!("File \"{}\" not found", import.file),
                            &import.import_uri_token,
                        );
                        None
                    }
                } else if import.file.ends_with(".slint") {
                    diag.push_error("Import names are missing. Please specify which types you would like to import".into(), &import.import_uri_token.parent());
                    None
                } else {
                    diag.push_error(
                        format!("Unsupported foreign import \"{}\"", import.file),
                        &import.import_uri_token,
                    );
                    None
                }
            })
            .collect();

        for local_compo in &inner_components {
            if exports
                .components_or_types
                .iter()
                .filter_map(|(_, exported_compo_or_type)| exported_compo_or_type.as_ref().left())
                .any(|exported_compo| Rc::ptr_eq(exported_compo, local_compo))
            {
                continue;
            }
            // Don't warn about these for now - detecting their use can only be done after the resolve_expressions
            // pass.
            if local_compo.is_global() {
                continue;
            }
            if !local_compo.used.get() {
                diag.push_warning(
                    "Component is neither used nor exported".into(),
                    &local_compo.node.as_ref().map(|n| n.to_source_location()),
                )
            }
        }

        Document {
            node: Some(node),
            inner_components,
            inner_types,
            local_registry,
            custom_fonts,
            imports,
            exports,
            library_exports: Default::default(),
            embedded_file_resources: Default::default(),
            #[cfg(feature = "bundle-translations")]
            translation_builder: None,
            used_types: Default::default(),
            popup_menu_impl: None,
        }
    }

    pub fn exported_roots(&self) -> impl DoubleEndedIterator<Item = Rc<Component>> + '_ {
        self.exports
            .iter()
            .filter_map(|e| e.1.as_ref().left())
            .filter(|c| !c.is_global() && !c.is_interface())
            .cloned()
    }

    /// This is the component that is going to be instantiated by the interpreter
    pub fn last_exported_component(&self) -> Option<Rc<Component>> {
        self.exports
            .iter()
            .filter_map(|e| Some((&e.0.name_ident, e.1.as_ref().left()?)))
            .filter(|(_, c)| !c.is_global())
            .max_by_key(|(n, _)| n.text_range().end())
            .map(|(_, c)| c.clone())
    }

    /// visit all root and used component (including globals)
    pub fn visit_all_used_components(&self, mut v: impl FnMut(&Rc<Component>)) {
        let used_types = self.used_types.borrow();
        for c in &used_types.sub_components {
            v(c);
        }
        for c in self.exported_roots() {
            v(&c);
        }
        for c in &used_types.globals {
            v(c);
        }
        if let Some(c) = &self.popup_menu_impl {
            v(c);
        }
    }
}

#[derive(Debug, Clone)]
pub struct PopupWindow {
    pub component: Rc<Component>,
    pub x: NamedReference,
    pub y: NamedReference,
    pub close_policy: EnumerationValue,
    pub parent_element: ElementRc,
    pub is_tooltip: bool,
    /// A reference to a synthesized property on the *parent* component that the runtime keeps in sync
    /// with the popup's visibility (`true` while shown, `false` once closed). This is `Some` only when
    /// the parent reads the PopupWindow's `is-open` property; see the `lower_popups` pass.
    pub is_open: Option<NamedReference>,
}

#[derive(Debug, Clone)]
pub struct Timer {
    pub interval: NamedReference,
    pub triggered: NamedReference,
    pub running: NamedReference,
    pub element: ElementWeak,
}

/// Key used for the default slot's insertion point and slot-target maps.
/// Not a valid Slint identifier, so it can never collide with a user-declared slot name.
pub const DEFAULT_SLOT_NAME: &str = "@children";

pub fn slot_error_subject(name: &str) -> String {
    if name == DEFAULT_SLOT_NAME {
        "The @children placeholder".into()
    } else {
        format!("The slot '{name}'")
    }
}

#[derive(Clone, Debug)]
pub enum ChildInsertionPointNode {
    DefaultChildrenPlaceHolder(SyntaxNode),
    ChildrenPlaceHolder(syntax_nodes::ChildrenPlaceholder),
    SlotPlaceholder(syntax_nodes::SubElement),
    SlotForwarding(syntax_nodes::Expression),
}

impl ChildInsertionPointNode {
    pub fn syntax_node(&self) -> &SyntaxNode {
        match self {
            Self::DefaultChildrenPlaceHolder(node) => node,
            Self::ChildrenPlaceHolder(node) => node,
            Self::SlotPlaceholder(node) => node,
            Self::SlotForwarding(node) => node,
        }
    }
}

impl Spanned for ChildInsertionPointNode {
    fn span(&self) -> crate::diagnostics::Span {
        self.syntax_node().span()
    }

    fn source_file(&self) -> Option<&crate::diagnostics::SourceFile> {
        self.syntax_node().source_file()
    }
}

#[derive(Clone, Debug)]
pub struct ChildrenInsertionPoint {
    pub parent: ElementRc,
    pub insertion_index: usize,
    pub node: ChildInsertionPointNode,
}

#[derive(Clone, Debug)]
pub struct DeclaredSlot {
    pub name: SmolStr,
    pub name_node: syntax_nodes::DeclaredIdentifier,
    has_rejected_placeholder: bool,
}

#[derive(Clone, Debug)]
pub struct SlotForwarding {
    pub target: SmolStr,
    pub source: SmolStr,
    pub expression_node: syntax_nodes::Expression,
}

/// Used sub types for a root component
#[derive(Debug, Default)]
pub struct UsedSubTypes {
    /// All the globals used by the component and its children.
    pub globals: Vec<Rc<Component>>,
    /// All the structs and enums used by the component and its children.
    pub structs_and_enums: Vec<Type>,
    /// All the sub components use by this components and its children,
    /// and the amount of time it is used
    pub sub_components: Vec<Rc<Component>>,
    /// All types, structs, enums, that originates from an
    /// external library
    pub library_types_imports: Vec<(SmolStr, LibraryInfo)>,
    /// All global components that originates from an
    /// external library
    pub library_global_imports: Vec<(SmolStr, LibraryInfo)>,
    /// `(old_name, new_name)` for types renamed to their export name. The generators emit a
    /// deprecated alias under `old_name` so code that used it keeps compiling.
    pub deprecated_type_aliases: Vec<(SmolStr, SmolStr)>,
    /// The fresh names given to types that collided with another declaration. These names were
    /// never part of the public API, so the generators must not re-export them (deprecated or not).
    pub collision_renamed_names: std::collections::BTreeSet<SmolStr>,
}

#[derive(Debug, Default, Clone)]
pub struct InitCode {
    // Code from init callbacks collected from elements
    pub constructor_code: Vec<Expression>,
    /// Code to set the initial focus via forward-focus on the Window
    pub focus_setting_code: Vec<Expression>,
    /// Code to register embedded fonts.
    pub font_registration_code: Vec<Expression>,

    /// Code inserted from inlined components, ordered by offset of the place where it was inlined from. This way
    /// we can preserve the order across multiple inlining passes.
    pub inlined_init_code: BTreeMap<usize, Expression>,
}

impl InitCode {
    pub fn iter(&self) -> impl Iterator<Item = &Expression> {
        self.font_registration_code.iter().chain(self.iter_without_font_registration())
    }
    /// The init code without the font registration, which has to run before the property init.
    pub fn iter_without_font_registration(&self) -> impl Iterator<Item = &Expression> {
        self.focus_setting_code
            .iter()
            .chain(self.constructor_code.iter())
            .chain(self.inlined_init_code.values())
    }
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Expression> {
        self.font_registration_code
            .iter_mut()
            .chain(self.focus_setting_code.iter_mut())
            .chain(self.constructor_code.iter_mut())
            .chain(self.inlined_init_code.values_mut())
    }
}

/// A component is a type in the language which can be instantiated,
/// Or is materialized for repeated expression.
#[derive(Default, Debug)]
pub struct Component {
    pub node: Option<syntax_nodes::Component>,
    pub id: SmolStr,
    pub root_element: ElementRc,

    /// The parent element within the parent component if this component represents a repeated element
    pub parent_element: RefCell<ElementWeak>,

    /// List of elements that are not attached to the root anymore because they have been
    /// optimized away, but their properties may still be in use
    pub optimized_elements: RefCell<Vec<ElementRc>>,

    /// The layout constraints of the root item
    pub root_constraints: RefCell<LayoutConstraints>,

    /// When creating this component and inserting "children", append them to the children of
    /// the element pointer to by this field.
    pub child_insertion_points: RefCell<BTreeMap<String, ChildrenInsertionPoint>>,

    /// Slots declared in this component, in source order.
    pub declared_slots: RefCell<Vec<DeclaredSlot>>,

    pub init_code: RefCell<InitCode>,

    pub popup_windows: RefCell<Vec<PopupWindow>>,
    pub timers: RefCell<Vec<Timer>>,
    pub menu_item_tree: RefCell<Vec<Rc<Component>>>,

    /// This component actually inherits PopupWindow (although that has been changed to a Window by the lower_popups pass)
    pub inherits_popup_window: Cell<bool>,

    /// The names under which this component should be accessible
    /// if it is a global singleton and exported.
    pub exported_global_names: RefCell<Vec<ExportedName>>,

    /// True if this component is used as a sub-component by at least one other component.
    pub used: Cell<bool>,

    /// The list of properties (name and type) declared as private in the component.
    /// This is used to issue better error in the generated code if the property is used.
    pub private_properties: RefCell<Vec<(SmolStr, Type)>>,

    /// True if this component is imported from an external library.
    pub from_library: Cell<bool>,
}

impl Component {
    pub fn from_node(
        node: syntax_nodes::Component,
        diag: &mut BuildDiagnostics,
        tr: &TypeRegister,
    ) -> Rc<Self> {
        let mut child_insertion_points = BTreeMap::new();
        let mut declared_slots = Vec::new();
        let is_legacy_syntax = node.child_token(SyntaxKind::ColonEqual).is_some();
        let c = Component {
            node: Some(node.clone()),
            id: parser::identifier_text(&node.DeclaredIdentifier()).unwrap_or_default(),
            root_element: Element::from_node(
                node.Element(),
                "root".into(),
                match node.child_text(SyntaxKind::Identifier) {
                    Some(t) if t == "global" => {
                        #[cfg(feature = "slint-sc")]
                        diag.slint_sc_error("Globals are", &node.DeclaredIdentifier());
                        ElementType::Global
                    }
                    Some(t) if t == "interface" => {
                        if reject_experimental_feature(diag, tr, "interface", &node) {
                            ElementType::Error
                        } else {
                            ElementType::Interface
                        }
                    }
                    _ => ElementType::Error,
                },
                &mut child_insertion_points,
                &mut declared_slots,
                is_legacy_syntax,
                diag,
                tr,
            ),
            child_insertion_points: RefCell::new(child_insertion_points),
            declared_slots: RefCell::new(declared_slots),
            ..Default::default()
        };
        c.check_slot_validity(diag);
        let c = Rc::new(c);
        // x and y on a Window are meaningless
        if c.root_element
            .borrow()
            .builtin_type()
            .is_some_and(|b| matches!(b.name.as_str(), "Window" | "Dialog"))
        {
            for prop in ["x", "y"] {
                if let Some(b) = c.root_element.borrow().binding_cell_including_synthetic(prop) {
                    #[cfg(feature = "slint-sc")]
                    if diag.slint_sc {
                        diag.slint_sc_error(&format!("The property '{prop}' is"), &*b.borrow());
                        continue;
                    }
                    diag.push_warning(
                        format!(
                            "Setting '{prop}' on a Window is deprecated, it doesn't affect the position of the window"
                        ),
                        &*b.borrow(),
                    );
                }
            }
            // The application gives the window its size, so the size is an
            // output of the component rather than something the file sets.
            #[cfg(feature = "slint-sc")]
            for prop in ["width", "height"] {
                if let Some(b) = c.root_element.borrow().binding_cell_including_synthetic(prop) {
                    diag.slint_sc_error(
                        &format!("Binding the '{prop}' of the root element is"),
                        &*b.borrow(),
                    );
                }
            }
        }
        let weak = Rc::downgrade(&c);
        recurse_elem(&c.root_element, &(), &mut |e, _| {
            e.borrow_mut().enclosing_component = weak.clone();
            if let Some(qualified_id) =
                e.borrow_mut().debug.first_mut().and_then(|x| x.qualified_id.as_mut())
            {
                *qualified_id = format_smolstr!("{}::{}", c.id, qualified_id);
            }
        });
        c
    }

    fn check_slot_validity(&self, diagnostics: &mut BuildDiagnostics) {
        if !diagnostics.enable_experimental {
            return;
        }
        if self.is_global() || self.is_interface() {
            return;
        }
        let mut declared_slot_nodes = BTreeMap::<SmolStr, syntax_nodes::DeclaredIdentifier>::new();
        for slot in self.declared_slots.borrow().iter() {
            if slot.name == "children" {
                diagnostics.push_error(
                    format!(
                        "The name '{}' is reserved for the default slot. Use @children instead",
                        slot.name
                    ),
                    &slot.name_node,
                );
                continue;
            }
            if declared_slot_nodes.insert(slot.name.clone(), slot.name_node.clone()).is_some() {
                diagnostics.push_error(
                    format!("Duplicate slot declaration '{}'", slot.name),
                    &slot.name_node,
                );
            }
        }
        for (name, cip) in self.child_insertion_points.borrow().iter() {
            if name == DEFAULT_SLOT_NAME {
                continue;
            }
            if !declared_slot_nodes.contains_key(name.as_str()) {
                diagnostics
                    .push_error(format!("The slot '{name}' is used but not declared"), &cip.node);
            }
        }
        for (name, node) in declared_slot_nodes.iter() {
            let has_rejected_placeholder = self
                .declared_slots
                .borrow()
                .iter()
                .any(|slot| slot.has_rejected_placeholder && &slot.name == name);
            if !self.child_insertion_points.borrow().contains_key(name.as_str())
                && !has_rejected_placeholder
            {
                diagnostics.push_error(format!("The slot '{name}' is declared but not used"), node);
            }
        }
    }

    /// This component is a global component introduced with the "global" keyword
    pub fn is_global(&self) -> bool {
        match &self.root_element.borrow().base_type {
            ElementType::Global => true,
            ElementType::Builtin(c) => c.is_global,
            _ => false,
        }
    }

    /// This is an interface introduced with the "interface" keyword
    pub fn is_interface(&self) -> bool {
        matches!(&self.root_element.borrow().base_type, ElementType::Interface)
    }

    /// True if this component's root resolves to the `SystemTrayIcon` native
    /// class. Uses `native_class()` rather than `builtin_type()` so the check
    /// still matches once the root has been resolved to `Native(SystemTrayIcon)`
    /// after `resolve_native_classes`.
    pub fn inherits_system_tray_icon(&self) -> bool {
        self.root_element
            .borrow()
            .native_class()
            .is_some_and(|n| n.class_name.as_str() == "SystemTrayIcon")
    }

    /// Returns the names of aliases to global singletons, exactly as
    /// specified in the .slint markup (not normalized).
    pub fn global_aliases(&self) -> Vec<SmolStr> {
        self.exported_global_names
            .borrow()
            .iter()
            .filter(|name| name.as_str() != self.root_element.borrow().id)
            .map(|name| name.original_name())
            .collect()
    }

    // Number of repeaters in this component, including sub-components
    pub fn repeater_count(&self) -> u32 {
        let mut count = 0;
        recurse_elem(&self.root_element, &(), &mut |element, _| {
            let element = element.borrow();
            if let Some(sub_component) = element.sub_component() {
                count += sub_component.repeater_count();
            } else if element.repeated.is_some() {
                count += 1;
            }
        });
        count
    }

    /// Convenience accessor to get the parent element if this component is a repeated component, or None otherwise.
    ///
    /// # Panics
    ///
    /// Panics if the Self::parent_element member is currently mutably borrowed
    pub fn parent_element(&self) -> Option<ElementRc> {
        self.parent_element.borrow().upgrade()
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
pub enum PropertyVisibility {
    #[default]
    Private,
    Input,
    Output,
    InOut,
    /// for builtin properties that must be known at compile time and cannot be changed at runtime
    Constexpr,
    /// For builtin properties that are meant to just be bindings but cannot be read or written
    /// (eg, Path's `commands`)
    Fake,
    /// For functions, not properties
    Public,
    Protected,
}

impl Display for PropertyVisibility {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PropertyVisibility::Private => f.write_str("private"),
            PropertyVisibility::Input => f.write_str("in"),
            PropertyVisibility::Output => f.write_str("out"),
            PropertyVisibility::InOut => f.write_str("in-out"),
            PropertyVisibility::Constexpr => f.write_str("constexpr"),
            PropertyVisibility::Public => f.write_str("public"),
            PropertyVisibility::Protected => f.write_str("protected"),
            PropertyVisibility::Fake => f.write_str("fake"),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct PropertyDeclaration {
    pub property_type: Type,
    pub node: Option<SyntaxNode>,
    /// Tells if getter and setter will be added to expose in the native language API
    pub expose_in_public_api: bool,
    /// Public API property exposed as an alias: it shouldn't be generated but instead forward to the alias.
    pub is_alias: Option<NamedReference>,
    pub visibility: PropertyVisibility,
    /// For function or callback: whether it is declared as `pure` (None for private function for which this has to be deduced)
    pub pure: Option<bool>,
    /// For a declaration that shadows an inherited member: the name as written in the source.
    /// The declaration itself is stored under a mangled name, see [`Element::shadowing_members`].
    pub shadowed_name: Option<SmolStr>,
    /// Declared `@shadowable`, so an inheriting component may shadow it.
    pub shadowable: bool,
    /// The name the declaration had on the element it was moved from, when the
    /// move_declarations pass hoisted it onto the root element from another
    /// element of the component, under a name of its own making. What the
    /// component itself declares, in the source or through the component it
    /// inherits from, keeps this `None`.
    pub moved_from: Option<SmolStr>,
    /// Some if the property was declared with `@deprecated`. The string is the hint shown after
    /// "The property 'xxx' has been deprecated." in the warning: either derived from the two-way
    /// binding target, or the custom message given as argument to `@deprecated("...")`.
    pub deprecated: Option<SmolStr>,
}

impl PropertyDeclaration {
    // For diagnostics: return a node pointing to the type
    pub fn type_node(&self) -> Option<SyntaxNode> {
        let node = self.node.as_ref()?;
        if let Some(x) = syntax_nodes::PropertyDeclaration::new(node.clone()) {
            Some(x.Type().map_or_else(|| x.into(), |x| x.into()))
        } else {
            node.clone().into()
        }
    }

    /// The name the member is declared under, un-mangled, given its internal key.
    pub fn declared_name<'a>(&'a self, internal_name: &'a SmolStr) -> &'a SmolStr {
        self.shadowed_name.as_ref().unwrap_or(internal_name)
    }

    /// A declaration that shadows an inherited member but is private: it is invisible outside its
    /// component, so from there the inherited member stays reachable instead.
    pub fn is_private_shadow(&self) -> bool {
        self.shadowed_name.is_some() && self.visibility == PropertyVisibility::Private
    }

    /// True when declared `@deprecated` without a custom message, so the hint in
    /// [`Self::deprecated`] is derived from the two-way binding target.
    pub fn has_derived_deprecation(&self) -> bool {
        self.deprecated.is_some()
            && self
                .node
                .as_ref()
                .and_then(|n| syntax_nodes::PropertyDeclaration::new(n.clone()))
                .and_then(|p| p.PropertyDeprecation())
                .is_some_and(|d| d.child_token(SyntaxKind::StringLiteral).is_none())
    }
}

/// Whether the declaration is marked `@shadowable` (an experimental feature).
fn shadowable_attribute(
    node: Option<syntax_nodes::ShadowableAttribute>,
    tr: &TypeRegister,
    diag: &mut BuildDiagnostics,
) -> bool {
    node.is_some_and(|node| !reject_experimental_feature(diag, tr, "@shadowable", &node))
}

/// How a `@deprecated` member without an explicit message derives its replacement hint.
enum DeprecationHint {
    /// A property or callback: derive it from the two-way binding target, if any.
    TwoWayBinding(Option<syntax_nodes::QualifiedName>),
    /// A function has no two-way binding, so an explicit message is required.
    MessageRequired,
}

/// The hint from a `@deprecated` attribute on a member: the explicit message, or one derived from
/// the two-way binding target when none is given. `None` when the member isn't deprecated.
fn member_deprecation(
    deprecation: Option<syntax_nodes::PropertyDeprecation>,
    hint: DeprecationHint,
    tr: &TypeRegister,
    diag: &mut BuildDiagnostics,
) -> Option<SmolStr> {
    let deprecation = deprecation?;
    if reject_experimental_feature(diag, tr, "@deprecated", &deprecation) {
        return None;
    }
    if let Some(message) = deprecation.child_token(SyntaxKind::StringLiteral) {
        return crate::literals::unescape_string(message.text());
    }
    let message = match hint {
        DeprecationHint::TwoWayBinding(target) => {
            // Derive the hint from the two-way binding target: keep the full path (e.g.
            // `a-struct.field`), dropping a leading `self`/`root`. The resolving pass checks the
            // target is actually reachable.
            if let Some(qn) = target {
                let mut segments = qn
                    .children_with_tokens()
                    .filter(|t| t.kind() == SyntaxKind::Identifier)
                    .map(|t| parser::normalize_identifier(t.as_token().unwrap().text()))
                    .peekable();
                if segments.peek().is_some_and(|s| matches!(s.as_str(), "self" | "root")) {
                    segments.next();
                }
                let path = segments.collect::<Vec<_>>().join(".");
                if !path.is_empty() {
                    return Some(format_smolstr!("Please use '{path}' instead"));
                }
            }
            "@deprecated without a message requires a two-way binding to derive the replacement from"
        }
        DeprecationHint::MessageRequired => "@deprecated on a function requires a message",
    };
    diag.push_error(message.into(), &deprecation);
    None
}

/// Shift the locality flags of a result that came from the element's base rather than itself.
fn from_base(mut r: PropertyLookupResult<'_>) -> PropertyLookupResult<'_> {
    r.is_in_direct_base = r.is_local_to_component;
    r.is_local_to_component = false;
    r
}

/// The error for a declaration that collides with a member it may not shadow.
/// `kind` is `None` for a function.
fn cannot_override_message(
    kind: Option<&str>,
    name: &SmolStr,
    declared_in: &Option<Rc<Component>>,
) -> String {
    let kind = kind.map_or_else(String::new, |kind| format!("{kind} "));
    match declared_in {
        Some(base) => format!("Cannot override {kind}'{name}' declared in '{}'", base.id),
        None => format!("Cannot override {kind}'{name}'"),
    }
}

/// How a declaration relates to a member of the same name already reachable from the element.
/// See [`Element::member_declaration`].
enum MemberDeclaration {
    /// No member of that name exists yet
    New,
    /// Shadows an inherited member: the declaration goes under `internal_name`, so the source
    /// name keeps resolving to the shadowed member for the code written against it.
    Shadow {
        internal_name: SmolStr,
        /// Shadowing a member that isn't visible here is silent
        warning: Option<String>,
    },
    /// A member of that name already exists and may not be shadowed
    Conflict {
        existing_type: Type,
        /// The base component declaring it, unless it is declared on this element itself
        declared_in: Option<Rc<Component>>,
    },
}

impl MemberDeclaration {
    /// Record the member on `elem`, warning if it shadows a member visible here.
    /// Returns the name to declare it under, which differs from `source_name` when it shadows.
    fn register(
        self,
        elem: &mut Element,
        source_name: &SmolStr,
        node: &dyn Spanned,
        diag: &mut BuildDiagnostics,
    ) -> SmolStr {
        let Self::Shadow { internal_name, warning } = self else {
            return source_name.clone();
        };
        elem.shadowing_members.insert(source_name.clone(), internal_name.clone());
        if let Some(warning) = warning {
            diag.push_warning(warning, node);
        }
        internal_name
    }
}

impl From<Type> for PropertyDeclaration {
    fn from(ty: Type) -> Self {
        PropertyDeclaration { property_type: ty, ..Self::default() }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TransitionDirection {
    In,
    Out,
    InOut,
}

#[derive(Debug, Clone)]
pub struct TransitionPropertyAnimation {
    /// The state id as computed in lower_state
    pub state_id: i32,
    /// The direction of the transition
    pub direction: TransitionDirection,
    /// The content of the `animation` object
    pub animation: ElementRc,
}

impl TransitionPropertyAnimation {
    /// Return an expression which returns a boolean which is true if the transition is active.
    /// The state argument is an expression referencing the state property of type StateInfo
    pub fn condition(&self, state: Expression) -> Expression {
        match self.direction {
            TransitionDirection::In => Expression::BinaryExpression {
                lhs: Box::new(Expression::StructFieldAccess {
                    base: Box::new(state),
                    name: "current-state".into(),
                }),
                rhs: Box::new(Expression::NumberLiteral(self.state_id as _, Unit::None)),
                op: '=',
                source_location: None,
            },
            TransitionDirection::Out => Expression::BinaryExpression {
                lhs: Box::new(Expression::StructFieldAccess {
                    base: Box::new(state),
                    name: "previous-state".into(),
                }),
                rhs: Box::new(Expression::NumberLiteral(self.state_id as _, Unit::None)),
                op: '=',
                source_location: None,
            },
            TransitionDirection::InOut => Expression::BinaryExpression {
                lhs: Box::new(Expression::BinaryExpression {
                    source_location: None,
                    lhs: Box::new(Expression::StructFieldAccess {
                        base: Box::new(state.clone()),
                        name: "current-state".into(),
                    }),
                    rhs: Box::new(Expression::NumberLiteral(self.state_id as _, Unit::None)),
                    op: '=',
                }),
                rhs: Box::new(Expression::BinaryExpression {
                    source_location: None,
                    lhs: Box::new(Expression::StructFieldAccess {
                        base: Box::new(state),
                        name: "previous-state".into(),
                    }),
                    rhs: Box::new(Expression::NumberLiteral(self.state_id as _, Unit::None)),
                    op: '=',
                }),
                op: '|',
                source_location: None,
            },
        }
    }
}

#[derive(Debug)]
pub enum PropertyAnimation {
    Static(ElementRc),
    Transition { state_ref: Expression, animations: Vec<TransitionPropertyAnimation> },
}

impl Clone for PropertyAnimation {
    fn clone(&self) -> Self {
        fn deep_clone(e: &ElementRc) -> ElementRc {
            let e = e.borrow();
            debug_assert!(e.children.is_empty());
            debug_assert!(e.property_declarations.is_empty());
            debug_assert!(e.states.is_empty() && e.transitions.is_empty());
            Rc::new(RefCell::new(Element {
                id: e.id.clone(),
                base_type: e.base_type.clone(),
                bindings: e.bindings.clone(),
                property_analysis: e.property_analysis.clone(),
                enclosing_component: e.enclosing_component.clone(),
                repeated: None,
                debug: e.debug.clone(),
                ..Default::default()
            }))
        }
        match self {
            PropertyAnimation::Static(e) => PropertyAnimation::Static(deep_clone(e)),
            PropertyAnimation::Transition { state_ref, animations } => {
                PropertyAnimation::Transition {
                    state_ref: state_ref.clone(),
                    animations: animations
                        .iter()
                        .map(|t| TransitionPropertyAnimation {
                            state_id: t.state_id,
                            direction: t.direction,
                            animation: deep_clone(&t.animation),
                        })
                        .collect(),
                }
            }
        }
    }
}

/// Map the accessibility property (eg "accessible-role", "accessible-label") to its named reference
#[derive(Default, Clone)]
pub struct AccessibilityProps(pub BTreeMap<String, NamedReference>);

#[derive(Clone, Debug)]
pub struct GeometryProps {
    pub x: NamedReference,
    pub y: NamedReference,
    pub width: NamedReference,
    pub height: NamedReference,
}

/// The z-order of a child element within a parent that has dynamic z-ordering.
#[derive(Clone, Debug)]
pub enum ZOrder {
    /// z is a compile-time constant (used for repeater/conditional children).
    Constant(f32),
    /// z is bound to a runtime expression (NamedReference to the child's z property).
    Dynamic(NamedReference),
    /// The child is a repeated element (`for` or `if`) whose instances each have
    /// their own z value: they are expanded and sorted individually among the
    /// parent's children. The NamedReference is the z property within the repeated
    /// component, evaluated per instance.
    PerInstance(NamedReference),
}

impl GeometryProps {
    pub fn new(element: &ElementRc) -> Self {
        Self {
            x: NamedReference::new(element, SmolStr::new_static("x")),
            y: NamedReference::new(element, SmolStr::new_static("y")),
            width: NamedReference::new(element, SmolStr::new_static("width")),
            height: NamedReference::new(element, SmolStr::new_static("height")),
        }
    }
}

pub type BindingsMap = BTreeMap<SmolStr, RefCell<BindingExpression>>;

/// A sealed wrapper around an element's binding map.
///
/// The inner map is private to the `object_tree` module, so other modules cannot read or mutate
/// it in a hook-unaware way (treating a synthetic debug hook as a real binding). All access from
/// outside goes through the hook-aware accessors on [`Element`]. The field itself can stay public
/// — `Element` struct literals keep compiling — because the seal is on this inner map.
#[derive(Clone, Default)]
pub struct Bindings(BindingsMap);

impl std::iter::FromIterator<(SmolStr, RefCell<BindingExpression>)> for Bindings {
    fn from_iter<T: IntoIterator<Item = (SmolStr, RefCell<BindingExpression>)>>(iter: T) -> Self {
        Bindings(iter.into_iter().collect())
    }
}

impl From<BindingsMap> for Bindings {
    fn from(map: BindingsMap) -> Self {
        Bindings(map)
    }
}

impl Bindings {
    /// The raw binding cell for `name`, including a synthetic debug hook.
    ///
    /// The counterpart of [`Element::binding_cell_including_synthetic`], for code that holds a
    /// `&Bindings` (e.g. an animation element's bindings) rather than a whole `Element`.
    pub fn binding_cell_including_synthetic(
        &self,
        name: &str,
    ) -> Option<&RefCell<BindingExpression>> {
        self.0.get(name)
    }
}

#[derive(Clone, Debug)]
pub struct ElementDebugInfo {
    // The id qualified with the enclosing component name. Given `foo := Bar {}` this is `EnclosingComponent::foo`
    pub qualified_id: Option<SmolStr>,
    pub type_name: String,
    // Hold an id for each element that is unique during this build, based on the source file and
    // the offset of the `LBrace` token.
    //
    // This helps to cross-reference the element in the different build stages the LSP has to deal with.
    pub element_hash: u64,
    pub node: syntax_nodes::Element,
    // Field to indicate whether this element was a layout that had
    // been lowered into a rectangle in the lower_layouts pass.
    pub layout: Option<crate::layout::Layout>,
    /// Set to true if the ElementDebugInfo following this one in the debug vector
    /// in Element::debug is the last one and the next entry belongs to an other element.
    /// This can happen as a result of rectangle optimization, for example.
    pub element_boundary: bool,
}

impl ElementDebugInfo {
    // Returns a comma separate string that encodes the element type name (`Rectangle`, `MyButton`, etc.),
    // the qualified id (`SurroundingComponent::my-id`), and optionally the layout kind
    // (`h-box`, `v-box`, `grid`, `flex-box`).
    fn encoded_element_info(&self) -> String {
        let mut info = self.type_name.clone();
        info.push(',');
        if let Some(id) = self.qualified_id.as_ref() {
            info.push_str(id);
        }
        info.push(',');
        if let Some(layout) = &self.layout {
            use crate::layout::{Layout, Orientation};
            match layout {
                Layout::BoxLayout(b) => match b.orientation {
                    Orientation::Horizontal => info.push_str("h-box"),
                    Orientation::Vertical => info.push_str("v-box"),
                },
                Layout::GridLayout(_) => info.push_str("grid"),
                Layout::FlexboxLayout(_) => info.push_str("flex-box"),
            }
        }
        info
    }
}

/// An Element is an instantiation of a Component
#[derive(Default)]
pub struct Element {
    /// The id as named in the original .slint file.
    ///
    /// Note that it can only be used for lookup before inlining.
    /// After inlining there can be duplicated id in the component.
    /// The id are then re-assigned unique id in the assign_id pass
    pub id: SmolStr,
    //pub base: QualifiedTypeName,
    pub base_type: ElementType,
    /// Currently contains also the callbacks. FIXME: should that be changed?
    pub bindings: Bindings,
    pub change_callbacks: BTreeMap<SmolStr, RefCell<Vec<Expression>>>,
    pub property_analysis: RefCell<BTreeMap<SmolStr, PropertyAnalysis>>,

    pub children: Vec<ElementRc>,
    /// The component which contains this element.
    pub enclosing_component: Weak<Component>,

    pub property_declarations: BTreeMap<SmolStr, PropertyDeclaration>,

    /// Members that shadow an inherited one, mapping the source name to the mangled key in
    /// `property_declarations`.
    pub shadowing_members: BTreeMap<SmolStr, SmolStr>,

    /// Main owner for a reference to a property.
    pub named_references: crate::namedreference::NamedReferenceContainer,

    /// This element is part of a `for <xxx> in <model>`:
    pub repeated: Option<RepeatedElementInfo>,
    /// This element is a placeholder to embed an Component at
    pub is_component_placeholder: bool,
    /// True when this element was injected by `lower_property_to_element` or the `visible` pass
    /// to wrap another element for a property like `opacity`/`transform-rotation`/`visible` (see
    /// `adjust_geometry_for_injected_parent`). Such wrappers take over the wrapped element's
    /// geometry, so consumers that need the wrapped element's source parent must walk past them.
    pub is_injected_wrapper_element: bool,

    /// Z-order of this element within a parent whose children are dynamically z-ordered.
    /// Stored on the child so it remains consistent when the children vector is reordered
    /// or moved to another parent.
    pub z_order: Option<ZOrder>,

    pub states: Vec<State>,
    pub transitions: Vec<Transition>,
    pub match_elements: Vec<MatchElementInfo>,
    /// true when this item's geometry is handled by a layout
    pub child_of_layout: bool,
    /// true when this item is a direct cell of a `FlexboxLayout`. Narrower
    /// than `child_of_layout`: only flexbox cells need the per-repeater
    /// `flexbox_layout_item_info` accessor.
    pub child_of_flexbox: bool,
    /// The orientation of the box layout this element is a repeated cell of.
    /// Only set when the cell also binds `cross-axis-self-alignment`; lets the
    /// generated `layout_item_info` return that value only for the cross axis,
    /// so the main-axis cache stays independent of it.
    pub parent_box_layout_orientation: Option<Orientation>,
    /// The property pointing to the layout info. `(horizontal, vertical)`
    ///
    /// Query it through `Element::effective_layout_info_prop`: the horizontal one
    /// it returns may be `layout_info_h_at_own_height`
    /// instead of `.0`. Use the field itself to copy, move, or write through it,
    /// where the element's own property is the one meant.
    pub layout_info_prop: Option<(NamedReference, NamedReference)>,
    /// `pure function layoutinfo-v-with-constraint(width: length) -> LayoutInfo`
    /// synthesized for elements whose vertical layout info depends on
    /// their width — lets the parent supply the width and avoid the
    /// recursion that would happen via the descendants' width property.
    pub layout_info_v_with_constraint: Option<NamedReference>,
    /// `layoutinfo-h-at-own-height`, the horizontal layout info of a column
    /// direction `FlexboxLayout` computed at its own height instead of an
    /// unbounded one, so a wrapping column counts the columns that fit. Only
    /// read where the height is settled by the source: see
    /// `Element::height_is_literal` and `Element::effective_layout_info_prop`.
    pub layout_info_h_at_own_height: Option<NamedReference>,
    /// Whether the effective `height` binding, on the element or a base, is a
    /// length literal that is not a percentage. Such a height can be read while
    /// computing the element's own horizontal layout info without closing a
    /// binding loop. `lower_layouts` computes it once with
    /// `Element::compute_height_is_literal`, which says why the rule is that
    /// narrow, while the bindings are still where the source put them.
    pub height_is_literal: bool,
    /// Whether we have `preferred-{width,height}: 100%`
    pub default_fill_parent: (bool, bool),

    pub accessibility_props: AccessibilityProps,

    /// Reference to the property.
    /// This is always initialized from the element constructor, but is Option because it references itself
    pub geometry_props: Option<GeometryProps>,

    /// true if this Element is the fake Flickable content element
    pub is_flickable_content: bool,

    /// true if this Element may have a popup as child meaning it cannot be optimized
    /// because the popup references it.
    pub has_popup_child: bool,

    /// True for compiler-generated tooltip `PopupWindow` instances (see `lower_tooltips`).
    pub is_tooltip: bool,

    /// This is the component-local index of this item in the item tree array.
    /// It is generated after the last pass and before the generators run.
    pub item_index: OnceCell<u32>,
    /// the index of the first children in the tree, set with item_index
    pub item_index_of_first_children: OnceCell<u32>,

    /// True when this element is in a component was declared with the `:=` symbol instead of the `component` keyword
    pub is_legacy_syntax: bool,

    /// How many times the element was inlined
    pub inline_depth: i32,

    /// If this element is assigned to a specific slot in its parent component (e.g., `name << ...`)
    pub slot_target: Option<SmolStr>,

    /// Slot forwarding mappings declared on this element: `target: source;`
    pub forwarded_slots: Vec<SlotForwarding>,

    /// Information about the grid cell containing this element, if applicable
    pub grid_layout_cell: Option<Rc<RefCell<crate::layout::GridLayoutCell>>>,

    /// Debug information about this element.
    ///
    /// There can be several in case of inlining or optimization (child merged into their parent).
    ///
    /// The order in the list is first the parent, and then the removed children.
    pub debug: Vec<ElementDebugInfo>,
}

impl Spanned for Element {
    fn span(&self) -> crate::diagnostics::Span {
        self.debug
            .first()
            .map(|n| {
                // If possible, only span the qualified name of the Element (i.e. the `MyElement`
                // part of `MyElement { ... }`, as otherwise the span can get very large, which
                // isn't useful for showing diagnostics.
                // Only use the full span as the fallback.
                n.node.QualifiedName().as_ref().map(Spanned::span).unwrap_or_else(|| n.node.span())
            })
            .unwrap_or_default()
    }

    fn source_file(&self) -> Option<&crate::diagnostics::SourceFile> {
        self.debug.first().map(|n| &n.node.source_file)
    }
}

impl core::fmt::Debug for Element {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        pretty_print(f, self, 0)
    }
}

pub fn pretty_print(
    f: &mut impl std::fmt::Write,
    e: &Element,
    indentation: usize,
) -> std::fmt::Result {
    if let Some(repeated) = &e.repeated {
        write!(f, "for {}[{}] in ", repeated.model_data_id, repeated.index_id)?;
        expression_tree::pretty_print(f, &repeated.model)?;
        write!(f, ":")?;
        if let ElementType::Component(base) = &e.base_type {
            write!(f, "(base) ")?;
            if base.parent_element().is_some() {
                pretty_print(f, &base.root_element.borrow(), indentation)?;
                return Ok(());
            }
        }
    }
    if e.is_component_placeholder {
        write!(f, "/* Component Placeholder */ ")?;
    }
    writeln!(f, "{} := {} {{  /* {} */", e.id, e.base_type, e.element_infos())?;
    let mut indentation = indentation + 1;
    macro_rules! indent {
        () => {
            for _ in 0..indentation {
                write!(f, "   ")?
            }
        };
    }
    for (name, ty) in &e.property_declarations {
        indent!();
        if let Some(alias) = &ty.is_alias {
            writeln!(f, "alias<{}> {} <=> {:?};", ty.property_type, name, alias)?
        } else {
            writeln!(f, "property<{}> {};", ty.property_type, name)?
        }
    }
    for (name, expr) in &e.bindings.0 {
        indent!();
        write!(f, "{name}: ")?;
        let Ok(expr) = expr.try_borrow() else {
            writeln!(f, "<borrowed>")?;
            continue;
        };
        expression_tree::pretty_print(f, &expr.expression)?;
        if expr.analysis.as_ref().is_some_and(|a| a.is_const) {
            write!(f, "/*const*/")?;
        }
        writeln!(f, ";")?;
        //writeln!(f, "; /*{}*/", expr.priority)?;
        if let Some(anim) = &expr.animation {
            indent!();
            writeln!(f, "animate {name} {anim:?}")?;
        }
        for nr in &expr.two_way_bindings {
            indent!();
            writeln!(f, "{name} <=> {nr:?};")?;
        }
    }
    for (name, ch) in &e.change_callbacks {
        for ex in &*ch.borrow() {
            indent!();
            write!(f, "changed {name} => ")?;
            expression_tree::pretty_print(f, ex)?;
            writeln!(f)?;
        }
    }
    if !e.states.is_empty() {
        indent!();
        writeln!(f, "states {:?}", e.states)?;
    }
    if !e.transitions.is_empty() {
        indent!();
        writeln!(f, "transitions {:?} ", e.transitions)?;
    }
    for c in &e.children {
        indent!();
        pretty_print(f, &c.borrow(), indentation)?
    }
    if let Some(g) = &e.geometry_props {
        indent!();
        writeln!(f, "geometry {g:?} ")?;
    }

    /*if let Type::Component(base) = &e.base_type {
        pretty_print(f, &c.borrow(), indentation)?
    }*/
    indentation -= 1;
    indent!();
    writeln!(f, "}}")
}

#[derive(Clone, Default, Debug)]
pub struct PropertyAnalysis {
    /// true if somewhere in the code, there is an expression that changes this property with an assignment
    pub is_set: bool,

    /// True if this property might be set from a different component.
    pub is_set_externally: bool,

    /// true if somewhere in the code, an expression is reading this property
    /// Note: currently this is only set in the binding analysis pass
    pub is_read: bool,

    /// true if this property is read from another component
    pub is_read_externally: bool,

    /// True if the property is linked to another property that is read only. That property becomes read-only
    pub is_linked_to_read_only: bool,

    /// True if this property is linked to another property
    pub is_linked: bool,
}

impl PropertyAnalysis {
    /// Merge analysis from base element for inlining
    ///
    /// Contrary to `merge`, we don't keep the external uses because
    /// they should come from us
    pub fn merge_with_base(&mut self, other: &PropertyAnalysis) {
        self.is_set |= other.is_set;
        self.is_read |= other.is_read;
    }

    /// Merge the analysis
    pub fn merge(&mut self, other: &PropertyAnalysis) {
        self.is_set |= other.is_set;
        self.is_read |= other.is_read;
        self.is_read_externally |= other.is_read_externally;
        self.is_set_externally |= other.is_set_externally;
    }

    /// Return true if it is read or set or used in any way
    pub fn is_used(&self) -> bool {
        self.is_read || self.is_read_externally || self.is_set || self.is_set_externally
    }
}

#[derive(Debug, Clone)]
pub struct ListViewInfo {
    pub content_y: NamedReference,
    /// `None` when the user explicitly sets `content-height` on the ListView;
    /// `Some` when the ListView computes it from the content.
    pub content_height: Option<NamedReference>,
    /// `None` when the user explicitly sets `content-width` on the ListView;
    /// `Some` when the ListView computes it from the content.
    pub content_width: Option<NamedReference>,
    /// The ListView's inner visible height (not counting eventual scrollbar)
    pub listview_height: NamedReference,
    /// The ListView's inner visible width (not counting eventual scrollbar)
    pub listview_width: NamedReference,
}

#[derive(Debug, Clone)]
/// If the parent element is a repeated element, this has information about the models
pub struct RepeatedElementInfo {
    pub model: Expression,
    pub model_data_id: SmolStr,
    pub index_id: SmolStr,
    /// A conditional element is just a for whose model is a boolean expression
    ///
    /// When this is true, the model is of type boolean instead of Model
    pub is_conditional_element: bool,
    /// When the for is the delegate of a ListView
    pub is_listview: Option<ListViewInfo>,
}

/// Struct for a match element that later is resolved into standard conditional elements
pub struct MatchElementInfo {
    /// The match element node, used for diagnostics related to the match element as a whole
    pub node: syntax_nodes::MatchElement,
    /// The value that is matched on
    pub subject: Expression,
    /// Each case and the corresponding element
    pub cases: Vec<MatchCaseInfo>,
    /// The `*` case of the match element, if any
    pub wildcard: WildcardMatchCaseInfo,
}

pub enum WildcardMatchCaseInfo {
    None,
    Empty,
    Element(ElementRc),
}

/// One case of a match element
pub struct MatchCaseInfo {
    /// The value the subject is compared against
    pub value: Expression,
    /// The syntax node
    pub node: syntax_nodes::Expression,
    /// The element to potentially show. None for the empty case
    pub element: Option<ElementRc>,
}

impl MatchElementInfo {
    /// The elements of all the cases, skipping the empty cases
    pub fn elements(&self) -> impl Iterator<Item = ElementRc> + '_ {
        self.cases.iter().filter_map(|case| case.element.clone()).chain(match &self.wildcard {
            WildcardMatchCaseInfo::Element(e) => Some(e.clone()),
            WildcardMatchCaseInfo::None | WildcardMatchCaseInfo::Empty => None,
        })
    }

    /// Make every case a conditional element
    pub fn lower_to_conditional_elements(&self) {
        let compare = |value: &Expression, op| Expression::BinaryExpression {
            lhs: Box::new(self.subject.clone()),
            rhs: Box::new(value.clone()),
            op,
            source_location: None,
        };
        let show_when = |element: &ElementRc, condition| {
            element.borrow_mut().repeated = Some(RepeatedElementInfo {
                model: condition,
                model_data_id: SmolStr::default(),
                index_id: SmolStr::default(),
                is_conditional_element: true,
                is_listview: None,
            });
        };

        for case in &self.cases {
            if let Some(element) = &case.element {
                show_when(element, compare(&case.value, '='));
            }
        }
        if let WildcardMatchCaseInfo::Element(wildcard) = &self.wildcard {
            let condition = self
                .cases
                .iter()
                .map(|case| compare(&case.value, '!'))
                .reduce(|lhs, rhs| Expression::BinaryExpression {
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                    op: '&',
                    source_location: None,
                })
                .unwrap_or(Expression::BoolLiteral(true));
            show_when(wildcard, condition);
        }
    }
}

pub type ElementRc = Rc<RefCell<Element>>;
pub type ElementWeak = Weak<RefCell<Element>>;

impl Element {
    pub fn make_rc(self) -> ElementRc {
        let r = ElementRc::new(RefCell::new(self));
        let g = GeometryProps::new(&r);
        r.borrow_mut().geometry_props = Some(g);
        r
    }

    pub fn from_node(
        node: syntax_nodes::Element,
        id: SmolStr,
        parent_type: ElementType,
        component_child_insertion_points: &mut BTreeMap<String, ChildrenInsertionPoint>,
        declared_slots: &mut Vec<DeclaredSlot>,
        is_legacy_syntax: bool,
        diag: &mut BuildDiagnostics,
        tr: &TypeRegister,
    ) -> ElementRc {
        // A child element's parent_type is the type of its parent; the root
        // gets a sentinel from Component::from_node
        #[cfg(feature = "slint-sc")]
        let is_component_root =
            !matches!(parent_type, ElementType::Builtin(_) | ElementType::Component(_));
        let base_type = if let Some(base_node) = node.QualifiedName() {
            let base = QualifiedTypeName::from_node(base_node.clone());
            let base_string = base.to_smolstr();
            match parent_type.lookup_type_for_child_element(&base_string, tr) {
                Ok(ElementType::Component(c)) if c.is_global() => {
                    diag.push_error(
                        "Cannot create an instance of a global component".into(),
                        &base_node,
                    );
                    ElementType::Error
                }
                Ok(ty) => {
                    // Window children, including through a component that
                    // inherits Window, error in warn_about_child_windows.
                    #[cfg(feature = "slint-sc")]
                    if let ElementType::Builtin(b) = &ty
                        && !b.slint_sc
                    {
                        diag.slint_sc_error(
                            &format!("The builtin element '{}' is", b.name),
                            &base_node,
                        );
                    }
                    ty
                }
                Err(err) => {
                    diag.push_error(err, &base_node);
                    ElementType::Error
                }
            }
        } else if parent_type == ElementType::Global || parent_type == ElementType::Interface {
            // This must be a global component or interface. It can only have properties and callbacks
            let mut error_on = |node: &dyn Spanned, what: &str| {
                let element_type = match parent_type {
                    ElementType::Global => "A global component",
                    ElementType::Interface => "An interface",
                    _ => "An unexpected type",
                };
                diag.push_error(format!("{element_type} cannot have {what}"), node);
            };
            node.SubElement().for_each(|n| error_on(&n, "sub elements"));
            node.RepeatedElement().for_each(|n| error_on(&n, "sub elements"));
            if let Some(n) = node.ChildrenPlaceholder() {
                error_on(&n, "sub elements");
            }
            node.PropertyAnimation().for_each(|n| error_on(&n, "animations"));
            node.States().for_each(|n| error_on(&n, "states"));
            node.Transitions().for_each(|n| error_on(&n, "transitions"));
            node.CallbackDeclaration().for_each(|cb| {
                if parser::identifier_text(&cb.DeclaredIdentifier()).is_some_and(|s| s == "init") {
                    error_on(&cb, "an 'init' callback")
                }
            });
            node.CallbackConnection().for_each(|cb| {
                if parser::identifier_text(&cb).is_some_and(|s| s == "init") {
                    error_on(&cb, "an 'init' callback")
                }
            });
            node.MatchElement().for_each(|n| error_on(&n, "match elements"));
            node.SlotDeclaration().for_each(|n| error_on(&n, "slots"));

            if parent_type == ElementType::Interface {
                node.Binding().for_each(|n| error_on(&n, "bindings"));
                node.TwoWayBinding().for_each(|n| error_on(&n, "two-way bindings"));

                node.ImplementStatement().for_each(|stmt| {
                    diag.push_error("Interfaces cannot implement another interface".into(), &stmt);
                });
            } else {
                node.ImplementStatement().for_each(|stmt| {
                    diag.push_error("Globals cannot implement an interface".into(), &stmt);
                });
            }

            parent_type
        } else if parent_type != ElementType::Error {
            // This should normally never happen because the parser does not allow for this
            assert!(diag.has_errors());
            return ElementRc::default();
        } else {
            tr.empty_type()
        };
        let is_interface = base_type == ElementType::Interface;
        // This isn't truly qualified yet, the enclosing component is added at the end of Component::from_node
        let qualified_id = (!id.is_empty()).then(|| id.clone());
        if let ElementType::Component(c) = &base_type {
            c.used.set(true);
        }
        let type_name = base_type
            .type_name()
            .filter(|_| base_type != tr.empty_type())
            .unwrap_or_default()
            .to_string();
        let mut r = Element {
            id,
            base_type: base_type.clone(),
            debug: vec![ElementDebugInfo {
                qualified_id,
                element_hash: 0,
                type_name,
                node: node.clone(),
                layout: None,
                element_boundary: false,
            }],
            is_legacy_syntax,
            ..Default::default()
        };

        let mut property_bindings: Vec<(
            SmolStr,
            syntax_nodes::BindingExpression,
            syntax_nodes::DeclaredIdentifier,
        )> = Vec::new();

        let mut two_way_bindings: Vec<(
            SmolStr,
            syntax_nodes::TwoWayBinding,
            syntax_nodes::DeclaredIdentifier,
        )> = Vec::new();

        for prop_decl in node.PropertyDeclaration() {
            // Only the root element's properties become part of the component's API
            #[cfg(feature = "slint-sc")]
            if !is_component_root {
                diag.slint_sc_error(
                    "Declaring a property on an element other than the root is",
                    &prop_decl,
                );
            }
            let prop_type = prop_decl
                .Type()
                .map(|type_node| type_from_node(type_node, diag, tr))
                // Type::Void is used for two way bindings without type specified
                .unwrap_or(Type::InferredProperty);

            let unresolved_prop_name =
                unwrap_or_continue!(parser::identifier_text(&prop_decl.DeclaredIdentifier()); diag);
            let declaration = r.member_declaration(&unresolved_prop_name);
            let name_token =
                prop_decl.DeclaredIdentifier().child_token(SyntaxKind::Identifier).unwrap();
            if let MemberDeclaration::Conflict { existing_type, declared_in } = &declaration {
                match existing_type {
                    Type::Callback { .. } => diag.push_error(
                        format!("Cannot declare property '{unresolved_prop_name}' when a callback with the same name exists"),
                        &name_token,
                    ),
                    Type::Function { .. } => diag.push_error(
                        format!("Cannot declare property '{unresolved_prop_name}' when a function with the same name exists"),
                        &name_token,
                    ),
                    _ => diag.push_error(
                        cannot_override_message(Some("property"), &unresolved_prop_name, declared_in),
                        &name_token,
                    ),
                }
                continue;
            }
            let prop_name = declaration.register(&mut r, &unresolved_prop_name, &name_token, diag);
            let shadowed_name =
                (prop_name != unresolved_prop_name).then(|| unresolved_prop_name.clone());

            let mut visibility = None;
            for token in prop_decl.children_with_tokens() {
                if token.kind() != SyntaxKind::Identifier {
                    continue;
                }
                match (token.as_token().unwrap().text(), visibility) {
                    ("in", None) => visibility = Some(PropertyVisibility::Input),
                    ("in", Some(_)) => diag.push_error("Extra 'in' keyword".into(), &token),
                    ("out", None) => visibility = Some(PropertyVisibility::Output),
                    ("out", Some(_)) => diag.push_error("Extra 'out' keyword".into(), &token),
                    ("in-out" | "in_out", None) => visibility = Some(PropertyVisibility::InOut),
                    ("in-out" | "in_out", Some(_)) => {
                        diag.push_error("Extra 'in-out' keyword".into(), &token)
                    }
                    ("private", None) => visibility = Some(PropertyVisibility::Private),
                    ("private", Some(_)) => {
                        diag.push_error("Extra 'private' keyword".into(), &token)
                    }
                    _ => (),
                }
            }
            let visibility = visibility.unwrap_or({
                if is_legacy_syntax {
                    PropertyVisibility::InOut
                } else {
                    PropertyVisibility::Private
                }
            });

            if is_interface {
                if let Some(binding_expression) = &prop_decl.BindingExpression() {
                    diag.push_error(
                        "Interface properties cannot have default values".into(),
                        binding_expression,
                    )
                }
                if let Some(two_way) = &prop_decl.TwoWayBinding() {
                    diag.push_error(
                        "Interface properties cannot have default bindings".into(),
                        two_way,
                    )
                }
                if visibility == PropertyVisibility::Private {
                    diag.push_error(
                        "'private' properties are inaccessible in an interface".into(),
                        &prop_decl,
                    );
                }
            }

            let deprecated = member_deprecation(
                prop_decl.PropertyDeprecation(),
                DeprecationHint::TwoWayBinding(
                    prop_decl.TwoWayBinding().and_then(|twb| twb.Expression().QualifiedName()),
                ),
                tr,
                diag,
            );

            r.property_declarations.insert(
                prop_name.clone(),
                PropertyDeclaration {
                    property_type: prop_type,
                    node: Some(prop_decl.clone().into()),
                    visibility,
                    shadowed_name,
                    shadowable: shadowable_attribute(prop_decl.ShadowableAttribute(), tr, diag),
                    deprecated,
                    ..Default::default()
                },
            );

            if let Some(csn) = prop_decl.BindingExpression() {
                property_bindings.push((prop_name.clone(), csn, prop_decl.DeclaredIdentifier()));
            }

            if let Some(csn) = prop_decl.TwoWayBinding() {
                #[cfg(feature = "slint-sc")]
                diag.slint_sc_error("Two-way bindings are", &csn);
                two_way_bindings.push((prop_name, csn, prop_decl.DeclaredIdentifier()));
            }
        }

        let (implemented_interfaces, child_implements) =
            if matches!(r.base_type, ElementType::Global | ElementType::Interface) {
                // Already rejected above with a more specific diagnostic.
                (Vec::new(), Vec::new())
            } else if r.id == "root" {
                interfaces::get_implemented_interfaces(&r, &node, tr, diag)
            } else {
                interfaces::disallow_implement_in_non_root(&node, tr, diag);
                (Vec::new(), Vec::new())
            };

        for (prop_name, csn, source) in property_bindings {
            match r.bindings.0.entry(prop_name.clone()) {
                Entry::Vacant(e) => {
                    e.insert(BindingExpression::new_uncompiled(csn.into()).into());
                }
                Entry::Occupied(_) => {
                    diag.push_error("Duplicated property binding".into(), &source);
                }
            }
        }

        for (prop_name, csn, source) in two_way_bindings {
            if r.bindings
                .0
                .insert(prop_name, BindingExpression::new_uncompiled(csn.into()).into())
                .is_some()
            {
                diag.push_error("Duplicated property binding".into(), &source);
            }
        }

        r.parse_bindings(
            node.Binding().filter_map(|b| {
                Some((b.child_token(SyntaxKind::Identifier)?, b.BindingExpression().into()))
            }),
            is_legacy_syntax,
            diag,
        );
        r.parse_bindings(
            node.TwoWayBinding()
                .filter_map(|b| Some((b.child_token(SyntaxKind::Identifier)?, b.into()))),
            is_legacy_syntax,
            diag,
        );

        apply_default_type_properties(&mut r);

        for sig_decl in node.CallbackDeclaration() {
            let name =
                unwrap_or_continue!(parser::identifier_text(&sig_decl.DeclaredIdentifier()); diag);

            let pure = Some(
                sig_decl.child_token(SyntaxKind::Identifier).is_some_and(|t| t.text() == "pure"),
            );

            #[cfg(feature = "slint-sc")]
            {
                // Only the root element's callbacks become part of the component's API
                if !is_component_root {
                    diag.slint_sc_error(
                        "Declaring a callback on an element other than the root is",
                        &sig_decl,
                    );
                }
                if pure == Some(true) {
                    diag.slint_sc_error("Pure callbacks are", &sig_decl);
                }
                if let Some(param) = sig_decl.CallbackDeclarationParameter().next() {
                    diag.slint_sc_error("Callback parameters are", &param);
                }
                if let Some(ret) = sig_decl.ReturnType() {
                    diag.slint_sc_error("Callback return types are", &ret);
                }
            }

            let declaration = r.member_declaration(&name);
            if let MemberDeclaration::Conflict { existing_type, declared_in } = &declaration {
                if matches!(existing_type, Type::Callback { .. }) {
                    // Already declared on this very element, rather than inherited
                    if r.declaration(&name).is_some() {
                        diag.push_error(
                            "Duplicated callback declaration".into(),
                            &sig_decl.DeclaredIdentifier(),
                        );
                    } else {
                        diag.push_error(
                            cannot_override_message(Some("callback"), &name, declared_in),
                            &sig_decl.DeclaredIdentifier(),
                        )
                    }
                } else {
                    diag.push_error(
                        format!(
                            "Cannot declare callback '{name}' when a {} with the same name exists",
                            if matches!(existing_type, Type::Function { .. }) {
                                "function"
                            } else {
                                "property"
                            }
                        ),
                        &sig_decl.DeclaredIdentifier(),
                    );
                }
                continue;
            }
            let shadowable = shadowable_attribute(sig_decl.ShadowableAttribute(), tr, diag);
            let deprecated = member_deprecation(
                sig_decl.PropertyDeprecation(),
                DeprecationHint::TwoWayBinding(
                    sig_decl.TwoWayBinding().and_then(|twb| twb.Expression().QualifiedName()),
                ),
                tr,
                diag,
            );
            let source_name = name;
            let name =
                declaration.register(&mut r, &source_name, &sig_decl.DeclaredIdentifier(), diag);
            let shadowed_name = (name != source_name).then_some(source_name);

            if let Some(csn) = sig_decl.TwoWayBinding() {
                #[cfg(feature = "slint-sc")]
                diag.slint_sc_error("Callback aliases are", &csn);
                r.bindings
                    .0
                    .insert(name.clone(), BindingExpression::new_uncompiled(csn.into()).into());
                r.property_declarations.insert(
                    name,
                    PropertyDeclaration {
                        property_type: Type::InferredCallback,
                        node: Some(sig_decl.into()),
                        visibility: PropertyVisibility::InOut,
                        pure,
                        shadowed_name,
                        shadowable,
                        deprecated,
                        ..Default::default()
                    },
                );
                continue;
            }

            let args = sig_decl
                .CallbackDeclarationParameter()
                .map(|p| type_from_node(p.Type(), diag, tr))
                .collect();
            let return_type = sig_decl
                .ReturnType()
                .map(|ret_ty| type_from_node(ret_ty.Type(), diag, tr))
                .unwrap_or(Type::Void);
            let arg_names = sig_decl
                .CallbackDeclarationParameter()
                .map(|a| {
                    a.DeclaredIdentifier()
                        .and_then(|x| parser::identifier_text(&x))
                        .unwrap_or_default()
                })
                .collect();
            r.property_declarations.insert(
                name,
                PropertyDeclaration {
                    property_type: Type::Callback(Arc::new(Function {
                        return_type,
                        args,
                        arg_names,
                    })),
                    node: Some(sig_decl.into()),
                    visibility: PropertyVisibility::InOut,
                    pure,
                    shadowed_name,
                    shadowable,
                    deprecated,
                    ..Default::default()
                },
            );
        }

        for func in node.Function() {
            #[cfg(feature = "slint-sc")]
            diag.slint_sc_error("Function declarations are", &func);
            let name =
                unwrap_or_continue!(parser::identifier_text(&func.DeclaredIdentifier()); diag);

            let member_decl = r.member_declaration(&name);
            if let MemberDeclaration::Conflict { existing_type, declared_in } = &member_decl {
                if matches!(existing_type, Type::Callback { .. } | Type::Function { .. }) {
                    diag.push_error(
                        cannot_override_message(None, &name, declared_in),
                        &func.DeclaredIdentifier(),
                    )
                } else {
                    diag.push_error(
                        format!("Cannot declare function '{name}' when a property with the same name exists"),
                        &func.DeclaredIdentifier(),
                    );
                }
                continue;
            }
            let source_name = name;
            let name = member_decl.register(&mut r, &source_name, &func.DeclaredIdentifier(), diag);
            let shadowed_name = (name != source_name).then_some(source_name);

            let mut args = Vec::new();
            let mut arg_names = Vec::new();
            for a in func.ArgumentDeclaration() {
                args.push(type_from_node(a.Type(), diag, tr));
                let name =
                    unwrap_or_continue!(parser::identifier_text(&a.DeclaredIdentifier()); diag);
                if arg_names.contains(&name) {
                    diag.push_error(
                        format!("Duplicated argument name '{name}'"),
                        &a.DeclaredIdentifier(),
                    );
                }
                arg_names.push(name);
            }
            let return_type = func
                .ReturnType()
                .map_or(Type::Void, |ret_ty| type_from_node(ret_ty.Type(), diag, tr));

            let mut visibility = PropertyVisibility::Private;
            let mut pure = None;
            for token in func.children_with_tokens() {
                if token.kind() != SyntaxKind::Identifier {
                    continue;
                }
                match token.as_token().unwrap().text() {
                    "pure" => pure = Some(true),
                    "public" => {
                        visibility = PropertyVisibility::Public;
                        pure = pure.or(Some(false));
                    }
                    "protected" => {
                        visibility = PropertyVisibility::Protected;
                        pure = pure.or(Some(false));
                    }
                    _ => (),
                }
            }

            if is_interface && visibility != PropertyVisibility::Public {
                diag.push_error(
                    "Function declarations in an interface must be public".into(),
                    &func,
                );
            }

            let declaration = PropertyDeclaration {
                property_type: Type::Function(Arc::new(Function { return_type, args, arg_names })),
                node: Some(func.clone().into()),
                visibility,
                pure,
                shadowed_name,
                shadowable: shadowable_attribute(func.ShadowableAttribute(), tr, diag),
                deprecated: member_deprecation(
                    func.PropertyDeprecation(),
                    DeprecationHint::MessageRequired,
                    tr,
                    diag,
                ),
                ..Default::default()
            };

            match (base_type.clone(), func.CodeBlock()) {
                (ElementType::Interface, Some(code_block)) => {
                    diag.push_error(
                        "Function declarations in interfaces must not have a body".into(),
                        &code_block,
                    );
                    continue;
                }
                (ElementType::Interface, None) => {
                    // Do not create a binding for this function, as it is just a declaration without body. It will be
                    // implemented by the component that implements the interface.
                    r.property_declarations.insert(name, declaration);
                    continue;
                }
                (_, None) => {
                    diag.push_error("Functions must have a code block".into(), &func);
                }
                (_, Some(_)) => {}
            }

            if r.bindings
                .0
                .insert(name.clone(), BindingExpression::new_uncompiled(func.clone().into()).into())
                .is_some()
            {
                assert!(diag.has_errors());
            }

            r.property_declarations.insert(name, declaration);
        }

        for con_node in node.CallbackConnection() {
            let unresolved_name = unwrap_or_continue!(parser::identifier_text(&con_node); diag);
            let lookup_result =
                r.lookup_property(&unresolved_name, PropertyLookupMode::ComponentLocal);
            #[cfg(feature = "slint-sc")]
            {
                // A callback declared in the file is in the subset by construction;
                // a builtin one only when marked in its declaration, which keeps
                // `init` and the rest of TouchArea out.
                if !r.is_user_declared_member(&unresolved_name) && !lookup_result.is_slint_sc {
                    diag.slint_sc_error(
                        &format!("The callback '{unresolved_name}' is"),
                        &con_node.child_token(SyntaxKind::Identifier).unwrap(),
                    );
                }
                // The application implements the callbacks of the root element,
                // so a handler here would be a second answer to one invocation.
                if is_component_root
                    && r.property_declarations
                        .get(lookup_result.internal_or_resolved_name().as_str())
                        .is_some_and(|d| d.node.is_some())
                {
                    diag.slint_sc_error(
                        "A handler for a callback declared on the root element is",
                        &con_node.child_token(SyntaxKind::Identifier).unwrap(),
                    );
                }
                if let Some(param) = con_node.DeclaredIdentifier().next() {
                    diag.slint_sc_error("Callback handler parameters are", &param);
                }
            }
            // Setting a handler on a deprecated callback from outside the declaring component warns,
            // like assigning a deprecated property does.
            let deprecation =
                lookup_result.deprecated.clone().filter(|_| !lookup_result.is_local_to_component);
            let resolved_name = lookup_result.internal_or_resolved_name();
            let property_type = lookup_result.property_type;
            if let Type::Callback(callback) = &property_type {
                let num_arg = con_node.DeclaredIdentifier().count();
                if num_arg > callback.args.len() {
                    diag.push_error(
                        format!(
                            "'{}' only has {} arguments, but {} were provided",
                            unresolved_name,
                            callback.args.len(),
                            num_arg
                        ),
                        &con_node.child_token(SyntaxKind::Identifier).unwrap(),
                    );
                }
            } else if property_type == Type::InferredCallback {
                // argument matching will happen later
            } else {
                if r.base_type != ElementType::Error {
                    diag.push_error(
                        format!("'{}' is not a callback in {}", unresolved_name, r.base_type),
                        &con_node.child_token(SyntaxKind::Identifier).unwrap(),
                    );
                }
                continue;
            }
            if let Some(message) = &deprecation {
                diag.push_property_deprecation_warning_with_message(
                    &unresolved_name,
                    message,
                    &con_node.child_token(SyntaxKind::Identifier).unwrap(),
                );
            }
            match r.bindings.0.entry(resolved_name) {
                Entry::Vacant(e) => {
                    e.insert(BindingExpression::new_uncompiled(con_node.clone().into()).into());
                }
                Entry::Occupied(mut e) => {
                    // A global may implement a callback declared in another global: the
                    // callback is declared as a two-way alias (`callback foo <=> Other.foo;`)
                    // and also given a handler (`foo => { ... }`). The alias node stays on
                    // the declaration, and the handler takes the binding expression slot.
                    let is_global_alias = r.base_type == ElementType::Global
                        && matches!(
                            &e.get().borrow().expression,
                            Expression::Uncompiled(node) if node.kind() == SyntaxKind::TwoWayBinding
                        );
                    if is_global_alias {
                        // Keep the handler as the binding and point its span at the handler
                        // name, so a duplicate-implementation error refers to the
                        // implementation rather than the alias. The alias is recovered from
                        // the declaration node, so dropping it from the binding is fine.
                        let mut handler =
                            BindingExpression::new_uncompiled(con_node.clone().into());
                        if let Some(name) = con_node.child_token(SyntaxKind::Identifier) {
                            handler.span = Some(name.to_source_location());
                        }
                        e.insert(handler.into());
                    } else {
                        diag.push_error(
                            "Duplicated callback".into(),
                            &con_node.child_token(SyntaxKind::Identifier).unwrap(),
                        );
                    }
                }
            }
        }

        for anim in node.PropertyAnimation() {
            #[cfg(feature = "slint-sc")]
            diag.slint_sc_error("Animations are", &anim);
            if let Some(star) = anim.child_token(SyntaxKind::Star) {
                diag.push_error(
                    "catch-all property is only allowed within transitions".into(),
                    &star,
                )
            };
            for prop_name_token in anim.QualifiedName() {
                match QualifiedTypeName::from_node(prop_name_token.clone()).members.as_slice() {
                    [unresolved_prop_name] => {
                        if r.base_type == ElementType::Error {
                            continue;
                        };
                        let lookup_result = r.lookup_property(
                            unresolved_prop_name,
                            PropertyLookupMode::ComponentLocal,
                        );
                        let valid_assign = lookup_result.is_valid_for_assignment();
                        let binding_name = lookup_result.internal_or_resolved_name();
                        if let Some(anim_element) = animation_element_from_node(
                            &anim,
                            &prop_name_token,
                            lookup_result.property_type.clone(),
                            diag,
                            tr,
                        ) {
                            if !valid_assign {
                                diag.push_error(
                                    format!(
                                        "Cannot animate '{}' property '{}'",
                                        lookup_result.property_visibility, unresolved_prop_name
                                    ),
                                    &prop_name_token,
                                );
                            }

                            if unresolved_prop_name != lookup_result.resolved_name.as_ref() {
                                diag.push_property_deprecation_warning(
                                    unresolved_prop_name,
                                    &lookup_result.resolved_name,
                                    &prop_name_token,
                                );
                            } else if let Some(message) = lookup_result
                                .deprecated
                                .as_ref()
                                .filter(|_| !lookup_result.is_local_to_component)
                            {
                                diag.push_property_deprecation_warning_with_message(
                                    unresolved_prop_name,
                                    message,
                                    &prop_name_token,
                                );
                            }

                            let expr_binding =
                                r.bindings.0.entry(binding_name).or_insert_with(|| {
                                    let mut r = BindingExpression::from(Expression::Invalid);
                                    r.priority = 1;
                                    r.span = Some(prop_name_token.to_source_location());
                                    r.into()
                                });
                            if expr_binding
                                .get_mut()
                                .animation
                                .replace(PropertyAnimation::Static(anim_element))
                                .is_some()
                            {
                                diag.push_error("Duplicated animation".into(), &prop_name_token)
                            }
                        }
                    }
                    _ => diag.push_error(
                        "Can only refer to property in the current element".into(),
                        &prop_name_token,
                    ),
                }
            }
        }

        for ch in node.PropertyChangedCallback() {
            #[cfg(feature = "slint-sc")]
            diag.slint_sc_error("Change callbacks are", &ch);
            let Some(prop) = parser::identifier_text(&ch.DeclaredIdentifier()) else { continue };
            let lookup_result = r.lookup_property(&prop, PropertyLookupMode::ComponentLocal);
            if !lookup_result.is_valid() {
                if r.base_type != ElementType::Error {
                    diag.push_error(
                        format!("Property '{prop}' does not exist"),
                        &ch.DeclaredIdentifier(),
                    );
                }
            } else if !lookup_result.property_type.is_property_type() {
                let what = match lookup_result.property_type {
                    Type::Function { .. } => "a function",
                    Type::Callback { .. } => "a callback",
                    _ => "not a property",
                };
                diag.push_error(
                    format!(
                        "Change callback can only be set on properties, and '{prop}' is {what}"
                    ),
                    &ch.DeclaredIdentifier(),
                );
            } else if lookup_result.property_visibility == PropertyVisibility::Private
                && !lookup_result.is_local_to_component
            {
                diag.push_error(
                    format!("Change callback on a private property '{prop}'"),
                    &ch.DeclaredIdentifier(),
                );
            }
            let handler = Expression::Uncompiled(ch.clone().into());
            match r.change_callbacks.entry(lookup_result.internal_or_resolved_name()) {
                Entry::Vacant(e) => {
                    e.insert(vec![handler].into());
                }
                Entry::Occupied(mut e) => {
                    diag.push_error(
                        format!("Duplicated change callback on '{prop}'"),
                        &ch.DeclaredIdentifier(),
                    );
                    e.get_mut().get_mut().push(handler);
                }
            }
        }

        let r = r.make_rc();

        for se in node.children() {
            if se.kind() != SyntaxKind::SlotForwarding {
                continue;
            }
            if !Self::assert_experimental_slots(diag, &se, "slot forwarding") {
                continue;
            }

            let target_node = se.child_node(SyntaxKind::DeclaredIdentifier).unwrap();
            let target = parser::identifier_text(&target_node.clone()).unwrap_or_default();

            if target == "children" {
                diag.push_error(
                    format!(
                        "The name '{target}' is reserved for the default slot. Use @children instead"
                    ),
                    &target_node,
                );
                continue;
            }

            if r.borrow().forwarded_slots.iter().any(|f| f.target == target) {
                diag.push_error(format!("Duplicate assignment to slot '{target}'"), &target_node);
                continue;
            }

            match &r.borrow().base_type {
                ElementType::Component(component)
                    if !component
                        .declared_slots
                        .borrow()
                        .iter()
                        .any(|slot| slot.name == target) =>
                {
                    diag.push_error(
                        format!("Unknown slot '{target}' in '{}'", component.id),
                        &target_node,
                    );
                    continue;
                }
                ElementType::Component(_) => {}
                _ => {
                    diag.push_error("Slot forwarding can only be used on components".into(), &se);
                    continue;
                }
            }

            let Some(expression_node) = se.child_node(SyntaxKind::Expression) else {
                diag.push_error(
                    "Slot forwarding requires a slot identifier on the right-hand side".into(),
                    &se,
                );
                continue;
            };
            let Some(source) = Self::slot_forwarding_expr_identifier(&expression_node) else {
                diag.push_error(
                    "Slot forwarding requires a slot identifier on the right-hand side".into(),
                    &expression_node,
                );
                continue;
            };

            if source == "children" {
                diag.push_error(
                    format!(
                        "The name '{source}' is reserved for the default slot. Use @children instead"
                    ),
                    &expression_node,
                );
                continue;
            }

            r.borrow_mut().forwarded_slots.push(SlotForwarding {
                target,
                source,
                expression_node: expression_node.into(),
            });
        }

        for forwarding in r.borrow().forwarded_slots.clone() {
            let source = forwarding.source.clone();
            if let Some(existing_cip) = component_child_insertion_points.get(source.as_str()) {
                if matches!(existing_cip.node, ChildInsertionPointNode::SlotPlaceholder(_)) {
                    diag.push_error(
                        format!(
                            "The slot '{source}' cannot be forwarded and used as a placeholder in the same component"
                        ),
                        &forwarding.expression_node,
                    );
                } else {
                    diag.push_error(
                        format!(
                            "{} can only appear once in an element",
                            slot_error_subject(&source)
                        ),
                        &forwarding.expression_node,
                    );
                }
                continue;
            }
            component_child_insertion_points.insert(
                source.to_string(),
                ChildrenInsertionPoint {
                    parent: r.clone(),
                    insertion_index: 0,
                    node: ChildInsertionPointNode::SlotForwarding(forwarding.expression_node),
                },
            );
        }

        let mut assigned_slots = HashSet::new();

        for se in node.children() {
            if se.kind() == SyntaxKind::SubElement {
                if let Some(slot_name) =
                    Self::sub_element_slot_placeholder_name(&se, declared_slots)
                {
                    Self::register_slot_placeholder(
                        &se,
                        slot_name,
                        &r,
                        component_child_insertion_points,
                        diag,
                        tr,
                    );
                    continue;
                }
                let parent_type = r.borrow().base_type.clone();
                r.borrow_mut().children.push(Element::from_sub_element_node(
                    se.into(),
                    parent_type,
                    component_child_insertion_points,
                    declared_slots,
                    is_legacy_syntax,
                    diag,
                    tr,
                ));
            } else if se.kind() == SyntaxKind::RepeatedElement {
                let mut sub_child_insertion_points = BTreeMap::new();
                let rep = Element::from_repeated_node(
                    se.into(),
                    &r,
                    &mut sub_child_insertion_points,
                    declared_slots,
                    is_legacy_syntax,
                    diag,
                    tr,
                );
                Self::reject_slot_placeholders(
                    diag,
                    declared_slots,
                    sub_child_insertion_points,
                    "a repeated element",
                );
                r.borrow_mut().children.push(rep);
            } else if se.kind() == SyntaxKind::ConditionalElement {
                let mut sub_child_insertion_points = BTreeMap::new();
                let rep = Element::from_conditional_node(
                    se.into(),
                    r.borrow().base_type.clone(),
                    &mut sub_child_insertion_points,
                    declared_slots,
                    is_legacy_syntax,
                    diag,
                    tr,
                );
                Self::reject_slot_placeholders(
                    diag,
                    declared_slots,
                    sub_child_insertion_points,
                    "a conditional element",
                );
                r.borrow_mut().children.push(rep);
            } else if se.kind() == SyntaxKind::MatchElement {
                let mut sub_child_insertion_points = BTreeMap::new();
                let match_element = Element::from_match_node(
                    se.into(),
                    r.borrow().base_type.clone(),
                    &mut sub_child_insertion_points,
                    declared_slots,
                    is_legacy_syntax,
                    diag,
                    tr,
                );
                Self::reject_slot_placeholders(
                    diag,
                    declared_slots,
                    sub_child_insertion_points,
                    "a match element",
                );
                let mut r = r.borrow_mut();
                r.children.extend(match_element.elements());
                r.match_elements.push(match_element);
            } else if se.kind() == SyntaxKind::ChildrenPlaceholder {
                #[cfg(feature = "slint-sc")]
                diag.slint_sc_error("The @children placeholder is", &se);
                if component_child_insertion_points.contains_key(DEFAULT_SLOT_NAME) {
                    diag.push_error(
                        format!(
                            "{} can only appear once in an element",
                            slot_error_subject(DEFAULT_SLOT_NAME)
                        ),
                        &se,
                    );
                } else {
                    component_child_insertion_points.insert(
                        DEFAULT_SLOT_NAME.into(),
                        ChildrenInsertionPoint {
                            parent: r.clone(),
                            insertion_index: r.borrow().children.len(),
                            node: ChildInsertionPointNode::ChildrenPlaceHolder(se.into()),
                        },
                    );
                }
            } else if se.kind() == SyntaxKind::SlotDeclaration {
                Self::assert_experimental_slots(diag, &se, "named slots");
                let decl: syntax_nodes::SlotDeclaration = se.into();
                let name_node = decl.DeclaredIdentifier();
                let name = parser::identifier_text(&name_node).unwrap_or_default();
                declared_slots.push(DeclaredSlot {
                    name,
                    name_node,
                    has_rejected_placeholder: false,
                });
            } else if se.kind() == SyntaxKind::SlotAssignment {
                if !Self::assert_experimental_slots(diag, &se, "named slots") {
                    continue;
                }
                let name_node = se.child_node(SyntaxKind::DeclaredIdentifier).unwrap();
                let name = parser::identifier_text(&name_node).unwrap_or_default();
                if name == "children" {
                    diag.push_error(
                        format!(
                            "The name '{name}' is reserved for the default slot. Use @children instead"
                        ),
                        &name_node,
                    );
                }
                if !assigned_slots.insert(name.clone()) {
                    diag.push_error(format!("Duplicate assignment to slot '{name}'"), &name_node);
                }
                if r.borrow().forwarded_slots.iter().any(|f| f.target == name) {
                    diag.push_error(format!("Duplicate assignment to slot '{name}'"), &name_node);
                }
                let sub_element_node = se.child_node(SyntaxKind::SubElement).unwrap();
                let parent_type = r.borrow().base_type.clone();
                match &parent_type {
                    ElementType::Component(component)
                        if !component
                            .declared_slots
                            .borrow()
                            .iter()
                            .any(|slot| slot.name == name) =>
                    {
                        diag.push_error(
                            format!("Unknown slot '{name}' in '{}'", component.id),
                            &name_node,
                        );
                    }
                    ElementType::Component(_) => {}
                    _ => {
                        diag.push_error(
                            "Slot assignments can only be used on components".to_string(),
                            &se,
                        );
                    }
                }
                let element = Element::from_sub_element_node(
                    sub_element_node.into(),
                    parent_type,
                    component_child_insertion_points,
                    declared_slots,
                    is_legacy_syntax,
                    diag,
                    tr,
                );
                element.borrow_mut().slot_target = Some(name);
                r.borrow_mut().children.push(element);
            }
        }

        for state in node.States().flat_map(|s| s.State()) {
            let condition = state.Expression();
            // `when` is a contextual keyword, so it is the state's only
            // `Identifier` token: its name is a `DeclaredIdentifier`.
            let when = state.child_token(SyntaxKind::Identifier).filter(|t| t.text() == "when");
            // Without a condition a state is never selected, so its property
            // changes are code that can't run.
            #[cfg(feature = "slint-sc")]
            if condition.is_none() {
                diag.slint_sc_error(
                    "A state without a 'when' condition is",
                    &state.DeclaredIdentifier(),
                );
            }
            let s = State {
                id: parser::identifier_text(&state.DeclaredIdentifier()).unwrap_or_default(),
                condition: condition.map(|e| Expression::Uncompiled(e.into())),
                property_changes: state
                    .StatePropertyChange()
                    .filter_map(|s| {
                        lookup_property_from_qualified_name_for_state(s.QualifiedName(), &r, diag)
                            .map(|(ne, _)| {
                                (ne, Expression::Uncompiled(s.BindingExpression().into()), s)
                            })
                    })
                    .collect(),
                selection: when.map(|when| ConditionLocation::StateSelection {
                    name: state.DeclaredIdentifier().to_source_location(),
                    when: when.to_source_location(),
                }),
            };
            for trs in state.Transition() {
                #[cfg(feature = "slint-sc")]
                diag.slint_sc_error("Transitions are", &trs);
                let mut t = Transition::from_node(trs, &r, tr, diag);
                t.state_id.clone_from(&s.id);
                r.borrow_mut().transitions.push(t);
            }
            r.borrow_mut().states.push(s);
        }

        for ts in node.Transitions() {
            #[cfg(feature = "slint-sc")]
            diag.slint_sc_error("Transitions are", &ts);
            if !is_legacy_syntax {
                diag.push_error("'transitions' block are no longer supported. Use 'in {...}' and 'out {...}' directly in the state definition".into(), &ts);
            }
            for trs in ts.Transition() {
                let trans = Transition::from_node(trs, &r, tr, diag);
                r.borrow_mut().transitions.push(trans);
            }
        }

        if r.borrow().base_type.to_smolstr() == "ListView" {
            let mut seen_for = false;
            for se in node.children() {
                if se.kind() == SyntaxKind::RepeatedElement && !seen_for {
                    seen_for = true;
                } else if matches!(
                    se.kind(),
                    SyntaxKind::SubElement
                        | SyntaxKind::ConditionalElement
                        | SyntaxKind::RepeatedElement
                        | SyntaxKind::ChildrenPlaceholder
                ) {
                    diag.push_error("A ListView can just have a single 'for' as children. Anything else is not supported".into(), &se)
                }
            }
        }

        interfaces::validate_self_implement_statements(&r.borrow(), &implemented_interfaces, diag);
        interfaces::apply_child_implement_statements(&r, child_implements, diag);

        r
    }

    fn from_sub_element_node(
        node: syntax_nodes::SubElement,
        parent_type: ElementType,
        component_child_insertion_points: &mut BTreeMap<String, ChildrenInsertionPoint>,
        declared_slots: &mut Vec<DeclaredSlot>,
        is_in_legacy_component: bool,
        diag: &mut BuildDiagnostics,
        tr: &TypeRegister,
    ) -> ElementRc {
        let mut id = parser::identifier_text(&node).unwrap_or_default();
        if matches!(id.as_ref(), "parent" | "self" | "root") {
            diag.push_error(
                format!("'{id}' is a reserved id"),
                &node.child_token(SyntaxKind::Identifier).unwrap(),
            );
            id = SmolStr::default();
        }
        Element::from_node(
            node.Element(),
            id,
            parent_type,
            component_child_insertion_points,
            declared_slots,
            is_in_legacy_component,
            diag,
            tr,
        )
    }

    fn assert_experimental_slots(
        diagnostics: &mut BuildDiagnostics,
        node: &SyntaxNode,
        what: &str,
    ) -> bool {
        if diagnostics.enable_experimental {
            return true;
        }
        diagnostics.push_error(format!("'{what}' is an experimental feature"), node);
        false
    }

    fn sub_element_slot_placeholder_name(
        node: &SyntaxNode,
        declared_slots: &[DeclaredSlot],
    ) -> Option<SmolStr> {
        if node.child_token(SyntaxKind::ColonEqual).is_some() {
            return None;
        }
        let element = node.child_node(SyntaxKind::Element)?;
        if element.children().any(|c| c.kind() != SyntaxKind::QualifiedName) {
            return None;
        }
        let qualified_name = element.child_node(SyntaxKind::QualifiedName)?;
        if qualified_name.child_token(SyntaxKind::Dot).is_some() {
            return None;
        }
        let name = parser::identifier_text(&qualified_name)?;
        declared_slots.iter().any(|slot| slot.name == name).then_some(name)
    }

    fn mark_placeholder_rejected(declared_slots: &mut [DeclaredSlot], name: &str) {
        if let Some(slot) = declared_slots.iter_mut().find(|slot| slot.name.as_str() == name) {
            slot.has_rejected_placeholder = true;
        }
    }

    fn reject_slot_placeholders(
        diagnostics: &mut BuildDiagnostics,
        declared_slots: &mut [DeclaredSlot],
        insertion_points: BTreeMap<String, ChildrenInsertionPoint>,
        context: &str,
    ) {
        for (name, ChildrenInsertionPoint { node, .. }) in insertion_points {
            Self::mark_placeholder_rejected(declared_slots, &name);
            diagnostics.push_error(
                format!("{} cannot appear in {context}", slot_error_subject(&name)),
                &node,
            );
        }
    }

    fn register_slot_placeholder(
        node: &SyntaxNode,
        slot_name: SmolStr,
        parent: &ElementRc,
        component_child_insertion_points: &mut BTreeMap<String, ChildrenInsertionPoint>,
        diagnostics: &mut BuildDiagnostics,
        type_register: &TypeRegister,
    ) {
        Self::assert_experimental_slots(diagnostics, node, "named slots");
        if let Some(existing) = component_child_insertion_points.get(slot_name.as_str()) {
            if matches!(existing.node, ChildInsertionPointNode::SlotForwarding(_)) {
                diagnostics.push_error(
                    format!(
                        "The slot '{slot_name}' cannot be forwarded and used as a placeholder in the same component"
                    ),
                    node,
                );
            } else {
                diagnostics.push_error(
                    format!(
                        "{} can only appear once in an element",
                        slot_error_subject(&slot_name)
                    ),
                    node,
                );
            }
            return;
        }
        if type_register.lookup_element(slot_name.as_str()).is_ok() {
            diagnostics.push_warning(
                format!(
                    "{} shadows an element type of the same name. This element is a slot placeholder, not an instance of '{slot_name}'",
                    slot_error_subject(&slot_name)
                ),
                node,
            );
        }
        let insertion_index = parent.borrow().children.len();
        component_child_insertion_points.insert(
            slot_name.to_string(),
            ChildrenInsertionPoint {
                parent: parent.clone(),
                insertion_index,
                node: ChildInsertionPointNode::SlotPlaceholder(node.clone().into()),
            },
        );
    }

    fn from_repeated_node(
        node: syntax_nodes::RepeatedElement,
        parent: &ElementRc,
        component_child_insertion_points: &mut BTreeMap<String, ChildrenInsertionPoint>,
        declared_slots: &mut Vec<DeclaredSlot>,
        is_in_legacy_component: bool,
        diag: &mut BuildDiagnostics,
        tr: &TypeRegister,
    ) -> ElementRc {
        #[cfg(feature = "slint-sc")]
        diag.slint_sc_error("Repeated elements (for-in) are", &node);
        let e = Element::from_sub_element_node(
            node.SubElement(),
            parent.borrow().base_type.clone(),
            component_child_insertion_points,
            declared_slots,
            is_in_legacy_component,
            diag,
            tr,
        );
        let parent_is_listview = {
            let parent = parent.borrow();
            parent.base_type.to_string() == "ListView"
                // Custom "ListView" is OK, but it must have these properties
                && [
                    "content-y",
                    "content-height",
                    "content-width",
                    "visible-height",
                    "visible-width",
                ]
                .iter()
                .all(|p| parent.lookup_property(p, PropertyLookupMode::InternalName).property_type == Type::LogicalLength)
        };
        let is_listview = if parent_is_listview
            && let Some(geometry_props) = e.borrow().geometry_props.as_ref()
        {
            let parent_elem = parent.borrow();
            // Check if content-width and content-height are explicitly set by the user,
            // either under their own name or through the deprecated viewport-* aliases.
            let (content_width_is_explicitly_set, content_height_is_explicitly_set) = {
                let has_binding = |name| parent_elem.binding(name).is_some_and(|b| b.has_binding());
                (
                    has_binding("content-width") || has_binding("viewport-width"),
                    has_binding("content-height") || has_binding("viewport-height"),
                )
            };
            drop(parent_elem); // Drop the borrow before creating NamedReference

            let lvi = ListViewInfo {
                content_y: NamedReference::new(parent, SmolStr::new_static("content-y")),
                content_height: (!content_height_is_explicitly_set)
                    .then(|| NamedReference::new(parent, SmolStr::new_static("content-height"))),
                content_width: (!content_width_is_explicitly_set)
                    .then(|| NamedReference::new(parent, SmolStr::new_static("content-width"))),
                listview_height: NamedReference::new(parent, SmolStr::new_static("visible-height")),
                listview_width: NamedReference::new(parent, SmolStr::new_static("visible-width")),
            };
            // these properties are set by the ListView layouting code
            if let Some(content_height) = &lvi.content_height {
                content_height.mark_as_set();
            }
            if let Some(content_width) = &lvi.content_width {
                content_width.mark_as_set();
            }
            geometry_props.y.mark_as_set();
            Some(lvi)
        } else {
            None
        };
        let rei = RepeatedElementInfo {
            model: Expression::Uncompiled(node.Expression().into()),
            model_data_id: node
                .DeclaredIdentifier()
                .and_then(|n| parser::identifier_text(&n))
                .unwrap_or_default(),
            index_id: node
                .RepeatedIndex()
                .and_then(|r| parser::identifier_text(&r))
                .unwrap_or_default(),
            is_conditional_element: false,
            is_listview,
        };
        e.borrow_mut().repeated = Some(rei);
        e
    }

    fn from_conditional_node(
        node: syntax_nodes::ConditionalElement,
        parent_type: ElementType,
        component_child_insertion_points: &mut BTreeMap<String, ChildrenInsertionPoint>,
        declared_slots: &mut Vec<DeclaredSlot>,
        is_in_legacy_component: bool,
        diag: &mut BuildDiagnostics,
        tr: &TypeRegister,
    ) -> ElementRc {
        #[cfg(feature = "slint-sc")]
        diag.slint_sc_error("Conditional elements (if) are", &node);
        let rei = RepeatedElementInfo {
            model: Expression::Uncompiled(node.Expression().into()),
            model_data_id: SmolStr::default(),
            index_id: SmolStr::default(),
            is_conditional_element: true,
            is_listview: None,
        };
        let e = Element::from_sub_element_node(
            node.SubElement(),
            parent_type,
            component_child_insertion_points,
            declared_slots,
            is_in_legacy_component,
            diag,
            tr,
        );
        e.borrow_mut().repeated = Some(rei);
        e
    }

    fn from_match_node(
        node: syntax_nodes::MatchElement,
        parent_type: ElementType,
        component_child_insertion_points: &mut BTreeMap<String, ChildrenInsertionPoint>,
        declared_slots: &mut Vec<DeclaredSlot>,
        is_in_legacy_component: bool,
        diag: &mut BuildDiagnostics,
        tr: &TypeRegister,
    ) -> MatchElementInfo {
        if !diag.enable_experimental {
            diag.push_error("match elements are an experimental feature".into(), &node);
        }
        if node.MatchCase().next().is_none() && node.WildcardMatchCase().is_none() {
            diag.push_error("Expected at least one case".into(), &node);
        }
        if let Some(wildcard) = node.WildcardMatchCase()
            && node.MatchCase().next().is_none()
        {
            diag.push_warning(
                "Unnecessary match statement always matches the '*' case".into(),
                &wildcard,
            );
        }
        let mut element_of = |sub_element| {
            Element::from_sub_element_node(
                sub_element,
                parent_type.clone(),
                component_child_insertion_points,
                declared_slots,
                is_in_legacy_component,
                diag,
                tr,
            )
        };
        // A case without a sub element is an empty case that shows nothing
        let cases = node
            .MatchCase()
            .map(|case| {
                let node = case.Expression();
                MatchCaseInfo {
                    value: Expression::Uncompiled(node.clone().into()),
                    node,
                    element: case.SubElement().map(&mut element_of),
                }
            })
            .collect();
        let wildcard = match node.WildcardMatchCase() {
            None => WildcardMatchCaseInfo::None,
            Some(w) => match w.SubElement().map(&mut element_of) {
                None => WildcardMatchCaseInfo::Empty,
                Some(element) => WildcardMatchCaseInfo::Element(element),
            },
        };
        MatchElementInfo {
            subject: Expression::Uncompiled(node.Expression().into()),
            node,
            cases,
            wildcard,
        }
    }

    /// Whether the member is declared in the source, on this element or on the
    /// root element of a component it inherits from, rather than coming from a
    /// builtin element. Follows the same chain as [`Self::lookup_property`].
    #[cfg(feature = "slint-sc")]
    pub fn is_user_declared_member(&self, name: &str) -> bool {
        match self.declaration(name) {
            Some((_, declaration)) => declaration.node.is_some(),
            None => match &self.base_type {
                ElementType::Component(c) => c.root_element.borrow().is_user_declared_member(name),
                _ => false,
            },
        }
    }

    /// Resolve `name` in the given [`PropertyLookupMode`], following aliases; `Type::Invalid` if absent.
    /// For a shadowing member the result's `internal_name` carries its storage key.
    pub fn lookup_property<'a>(
        &self,
        name: &'a str,
        mode: PropertyLookupMode,
    ) -> PropertyLookupResult<'a> {
        let declaration = match mode {
            PropertyLookupMode::InternalName => self.property_declarations.get_key_value(name),
            PropertyLookupMode::ComponentLocal | PropertyLookupMode::FromOutside => {
                self.declaration(name)
            }
        };
        if let Some((internal_name, decl)) = declaration {
            if mode == PropertyLookupMode::FromOutside && decl.is_private_shadow() {
                return from_base(
                    self.base_type.lookup_property(name, PropertyLookupMode::FromOutside),
                );
            }
            let mut r = self.lookup_result_for_declaration(name.into(), decl);
            if internal_name != name {
                r.internal_name = Some(internal_name.clone());
            }
            return r;
        }
        // A base component's private members are invisible from here.
        let base_mode = match mode {
            PropertyLookupMode::InternalName => PropertyLookupMode::InternalName,
            _ => PropertyLookupMode::FromOutside,
        };
        from_base(self.base_type.lookup_property(name, base_mode))
    }

    /// The declaration for a member written as `name` in `.slint` source, with its internal key.
    /// A mangled key is private: it is reachable only through `shadowing_members`, never as a source
    /// name.
    pub fn declaration(&self, name: &str) -> Option<(&SmolStr, &PropertyDeclaration)> {
        if let Some(internal_name) = self.shadowing_members.get(name) {
            return self.property_declarations.get_key_value(internal_name);
        }
        self.property_declarations.get_key_value(name).filter(|(_, d)| d.shadowed_name.is_none())
    }

    /// Source names of shadowing declarations that are visible from outside the component, so they
    /// hide the inherited member of the same name. A private shadow is excluded: it stays transparent
    /// from outside, leaving the inherited member reachable there.
    pub fn visible_shadowing_members(&self) -> impl Iterator<Item = &SmolStr> {
        self.shadowing_members.iter().filter_map(|(source, internal)| {
            self.property_declarations
                .get(internal)
                .filter(|d| !d.is_private_shadow())
                .map(|_| source)
        })
    }

    /// How a declaration of `name` relates to a member of the same name already reachable here.
    /// See [`MemberDeclaration`].
    fn member_declaration(&self, name: &SmolStr) -> MemberDeclaration {
        // A prior shadow's mangled key is private, so this declaration may take the source name and
        // get a fresh key of its own.
        if self.property_declarations.get(name.as_str()).is_some_and(|d| d.shadowed_name.is_some())
        {
            return MemberDeclaration::Shadow {
                internal_name: self.unique_member_name(name),
                warning: None,
            };
        }
        let existing = self.lookup_property(name, PropertyLookupMode::ComponentLocal);
        if !existing.is_valid() {
            return MemberDeclaration::New;
        }
        if existing.is_local_to_component {
            return MemberDeclaration::Conflict {
                existing_type: existing.property_type,
                declared_in: None,
            };
        }
        let declared_in = self.declaring_base_component(name);
        // A private member of a base component isn't visible here, so shadowing it can't
        // surprise anyone. Anything else has to be opted into by the base declaration.
        let private =
            declared_in.is_some() && existing.property_visibility == PropertyVisibility::Private;
        if !private && !existing.is_shadowable {
            return MemberDeclaration::Conflict {
                existing_type: existing.property_type,
                declared_in,
            };
        }
        let origin = if declared_in.is_some() { "inherited" } else { "builtin" };
        MemberDeclaration::Shadow {
            internal_name: self.unique_member_name(name),
            warning: (!private).then(|| {
                let kind = match existing.property_type {
                    Type::Callback { .. } => "callback",
                    Type::Function { .. } => "function",
                    _ => "property",
                };
                format!("'{name}' shadows the {origin} {kind} of the same name")
            }),
        }
    }

    /// A name derived from `base` that no member reachable from this element uses.
    pub fn unique_member_name(&self, base: &str) -> SmolStr {
        (1..)
            .map(|counter| format_smolstr!("{base}-{counter}"))
            .find(|n| !self.lookup_property(n, PropertyLookupMode::InternalName).is_valid())
            .unwrap()
    }

    /// The base component whose root element declares `name`, if any. `None` when the member comes
    /// from a builtin element or doesn't exist.
    fn declaring_base_component(&self, name: &str) -> Option<Rc<Component>> {
        let mut base = self.base_type.clone();
        loop {
            let ElementType::Component(c) = base else { return None };
            let declares = {
                let root = c.root_element.borrow();
                root.shadowing_members.contains_key(name)
                    || root.property_declarations.contains_key(name)
            };
            if declares {
                return Some(c);
            }
            base = c.root_element.borrow().base_type.clone();
        }
    }

    fn lookup_result_for_declaration<'a>(
        &self,
        resolved_name: std::borrow::Cow<'a, str>,
        p: &PropertyDeclaration,
    ) -> PropertyLookupResult<'a> {
        PropertyLookupResult {
            resolved_name,
            property_type: p.property_type.clone(),
            property_visibility: p.visibility,
            declared_pure: p.pure,
            is_local_to_component: true,
            is_in_direct_base: false,
            is_shadowable: p.shadowable,
            builtin_function: None,
            is_slint_sc: true,
            deprecated: p.deprecated.clone(),
            internal_name: None,
        }
    }

    fn parse_bindings(
        &mut self,
        bindings: impl Iterator<Item = (crate::parser::SyntaxToken, SyntaxNode)>,
        is_in_legacy_component: bool,
        diag: &mut BuildDiagnostics,
    ) {
        for (name_token, b) in bindings {
            let unresolved_name = crate::parser::normalize_identifier(name_token.text());
            let lookup_result =
                self.lookup_property(&unresolved_name, PropertyLookupMode::ComponentLocal);
            #[cfg(feature = "slint-sc")]
            if b.kind() == SyntaxKind::TwoWayBinding {
                diag.slint_sc_error("Two-way bindings are", &b);
            } else {
                lookup_result.check_slint_sc(&unresolved_name, &name_token, diag);
            }
            if !lookup_result.property_type.is_property_type() {
                match lookup_result.property_type {
                        Type::Invalid => {
                            if self.base_type != ElementType::Error {
                                let msg = if let Some(suggestion) = css_property_suggestion(&unresolved_name, &self.base_type) {
                                    suggestion
                                } else if self.base_type.to_smolstr() == "Empty" {
                                    format!( "Unknown property {unresolved_name}")
                                } else {
                                    format!( "Unknown property {unresolved_name} in {}", self.base_type)
                                };
                                diag.push_error(msg, &name_token);
                            }
                        }
                        Type::Callback { .. } => {
                            diag.push_error(format!("'{unresolved_name}' is a callback. Use `=>` to connect"),
                            &name_token)
                        }
                        _ => diag.push_error(format!(
                            "Cannot assign to {} in {} because it does not have a valid property type",
                            unresolved_name, self.base_type,
                        ),
                        &name_token),
                    }
            } else if !lookup_result.is_local_to_component
                && (lookup_result.property_visibility == PropertyVisibility::Private
                    || lookup_result.property_visibility == PropertyVisibility::Output)
            {
                if is_in_legacy_component
                    && lookup_result.property_visibility == PropertyVisibility::Output
                {
                    diag.push_warning(
                        format!(
                            "Assigning to '{}' property '{unresolved_name}' is deprecated",
                            PropertyVisibility::Output
                        ),
                        &name_token,
                    );
                } else {
                    diag.push_error(
                        format!(
                            "Cannot assign to '{}' property '{}'",
                            lookup_result.property_visibility, unresolved_name
                        ),
                        &name_token,
                    );
                }
            }

            if *lookup_result.resolved_name != *unresolved_name {
                diag.push_property_deprecation_warning(
                    &unresolved_name,
                    &lookup_result.resolved_name,
                    &name_token,
                );
            } else if let Some(message) =
                lookup_result.deprecated.as_ref().filter(|_| !lookup_result.is_local_to_component)
            {
                diag.push_property_deprecation_warning_with_message(
                    &unresolved_name,
                    message,
                    &name_token,
                );
            }

            match self.bindings.0.entry(lookup_result.internal_or_resolved_name()) {
                Entry::Occupied(_) => {
                    diag.push_error("Duplicated property binding".into(), &name_token);
                }
                Entry::Vacant(entry) => {
                    entry.insert(BindingExpression::new_uncompiled(b).into());
                }
            };
        }
    }

    /// Return the node declaring `name` in this element or one of its bases, if there is one.
    pub fn property_declaration_node(&self, name: &str) -> Option<SyntaxNode> {
        self.property_declarations
            .get(name)
            .and_then(|declaration| declaration.node.clone())
            .or_else(|| self.base_type.property_declaration_node(name))
    }

    fn slot_forwarding_expr_identifier(expression: &SyntaxNode) -> Option<SmolStr> {
        if expression.kind() != SyntaxKind::Expression {
            return None;
        }

        let mut expr_children = expression.children();
        let qualified_name = expr_children.find(|n| n.kind() == SyntaxKind::QualifiedName)?;
        if expr_children.next().is_some() {
            return None;
        }

        let mut identifiers = qualified_name
            .children_with_tokens()
            .filter(|n| n.kind() == SyntaxKind::Identifier)
            .filter_map(|n| n.into_token());
        let identifier = identifiers.next()?;
        if identifiers.next().is_some() {
            return None;
        }

        Some(crate::parser::normalize_identifier(identifier.text()))
    }

    /// Return the alias node of a `callback foo <=> ...;` declaration, if `name` is one.
    ///
    /// This lives on the callback declaration itself, which is where the alias of a
    /// global callback that also has a handler ends up (the handler takes the binding
    /// expression slot).
    pub fn callback_alias_declaration_node(
        &self,
        name: &str,
    ) -> Option<syntax_nodes::TwoWayBinding> {
        self.property_declarations
            .get(name)
            .and_then(|d| d.node.clone())
            .and_then(syntax_nodes::CallbackDeclaration::new)
            .and_then(|cb| cb.TwoWayBinding())
    }

    /// Return the two-way-binding syntax node of a `<=>` alias for the given property, if any.
    ///
    /// Usually the alias is the binding's own (uncompiled) expression. But a global
    /// callback may both alias another global's callback (`callback foo <=> Other.foo;`)
    /// and provide a handler (`foo => { ... }`): the handler then occupies the binding
    /// expression slot, so the alias node lives on the callback declaration instead.
    pub fn two_way_binding_node(&self, name: &str) -> Option<syntax_nodes::TwoWayBinding> {
        if let Some(binding) = self.bindings.0.get(name)
            && let Ok(b) = binding.try_borrow()
            && let Expression::Uncompiled(node) = b.value_expression()
            && let Some(twb) = syntax_nodes::TwoWayBinding::new(node.clone())
        {
            return Some(twb);
        }
        self.callback_alias_declaration_node(name)
    }

    pub fn native_class(&self) -> Option<Arc<NativeClass>> {
        let mut base_type = self.base_type.clone();
        loop {
            match &base_type {
                ElementType::Component(component) => {
                    base_type = component.root_element.clone().borrow().base_type.clone();
                }
                ElementType::Builtin(builtin) => break Some(builtin.native_class.clone()),
                ElementType::Native(native) => break Some(native.clone()),
                _ => break None,
            }
        }
    }

    pub fn builtin_type(&self) -> Option<Rc<BuiltinElement>> {
        let mut base_type = self.base_type.clone();
        loop {
            match &base_type {
                ElementType::Component(component) => {
                    base_type = component.root_element.clone().borrow().base_type.clone();
                }
                ElementType::Builtin(builtin) => break Some(builtin.clone()),
                _ => break None,
            }
        }
    }

    /// The property holding the layout info for that orientation. For the
    /// horizontal info of a column flex whose height is settled by the source
    /// (see [`Self::height_is_literal`]), that is `layout_info_h_at_own_height`;
    /// never on the root of a component with instances, which decide for themselves.
    pub(crate) fn effective_layout_info_prop(
        &self,
        orientation: Orientation,
    ) -> Option<&NamedReference> {
        let prop = self.layout_info_prop.as_ref()?;
        match orientation {
            Orientation::Horizontal => Some(
                self.layout_info_h_at_own_height
                    .as_ref()
                    .filter(|_| self.height_is_literal)
                    .unwrap_or(&prop.0),
            ),
            Orientation::Vertical => Some(&prop.1),
        }
    }

    /// Whether this element is a *builtin* whose vertical layout info
    /// depends on its width. Returns `false` for user components — even
    /// ones whose own bindings derive height from width (e.g.
    /// `component Foo { height: self.width; }`); those don't carry the
    /// information needed to detect the dependency here. The synthesis
    /// pass catches user components by other means (descendant
    /// height-for-width + `layoutinfo-v-with-constraint` propagation).
    pub fn is_builtin_height_for_width(&self) -> bool {
        let Some(builtin) = self.builtin_type() else { return false };
        match builtin.name.as_str() {
            // Conservatively treat any wrap binding (including a literal
            // `no-wrap`) as height-for-width.
            "Text" | "TextInput" => self.is_binding_set("wrap", false),
            // An Image is height-for-width only while its height comes from its
            // width; with an explicit height it is fixed, so it is not.
            "Image" | "ClippedImage" => !self.is_binding_set("height", true),
            // Markdown text always wraps to fill the given width.
            "StyledText" => true,
            _ => false,
        }
    }

    /// Returns the `layoutinfo-v-with-constraint` NamedReference reachable
    /// from `self`, looking through the base-type chain. The NR points to
    /// the element actually carrying the binding.
    pub fn inherited_layout_info_v_with_constraint(&self) -> Option<NamedReference> {
        if let Some(nr) = &self.layout_info_v_with_constraint {
            return Some(nr.clone());
        }
        let mut base = self.base_type.clone();
        while let ElementType::Component(base_comp) = base {
            let root = base_comp.root_element.borrow();
            if let Some(nr) = &root.layout_info_v_with_constraint {
                return Some(nr.clone());
            }
            base = root.base_type.clone();
        }
        None
    }

    /// Whether [`Self::inherited_layout_info_v_with_constraint`] would return
    /// `Some`, without cloning the `NamedReference`.
    pub fn has_inherited_layout_info_v_with_constraint(&self) -> bool {
        if self.layout_info_v_with_constraint.is_some() {
            return true;
        }
        let mut base = self.base_type.clone();
        while let ElementType::Component(base_comp) = base {
            let root = base_comp.root_element.borrow();
            if root.layout_info_v_with_constraint.is_some() {
                return true;
            }
            base = root.base_type.clone();
        }
        false
    }

    /// Whether this element's `layoutinfo-{orientation}` already incorporates its
    /// own explicit min/max/preferred/stretch constraints. True for elements with
    /// a `layoutinfo-*` property (layouts, sub-components) or an inherited
    /// `layoutinfo-v-with-constraint` function (a component forwarding a
    /// height-for-width layout).
    ///
    /// A parent layout must then NOT re-apply the cell's explicit constraints on
    /// top of the measured info — they are already included, and re-reading them
    /// unconstrained can reintroduce a height-for-width binding loop. Only native
    /// items (no `layoutinfo-*`) need their constraints applied separately.
    pub fn layout_info_includes_own_constraints(&self, orientation: Orientation) -> bool {
        self.effective_layout_info_prop(orientation).is_some()
            || (orientation == Orientation::Vertical
                && self.has_inherited_layout_info_v_with_constraint())
    }

    /// Returns the element's name as specified in the markup, not normalized.
    pub fn original_name(&self) -> SmolStr {
        self.debug
            .first()
            .and_then(|n| n.node.child_token(parser::SyntaxKind::Identifier))
            .map(|n| n.to_smolstr())
            .unwrap_or_else(|| self.id.clone())
    }

    /// Whether the children of this element are dynamically sorted by their z value
    pub fn has_dynamic_z_order(&self) -> bool {
        self.children.iter().any(|c| c.borrow().z_order.is_some())
    }

    /// Return true if the binding is set, either on this element or in a base
    ///
    /// If `need_explicit` is true, then only consider binding set in the code, not the ones set
    /// by the compiler later.
    ///
    /// Synthetic debug hooks (materialized for unbound properties) are never considered set
    /// (`has_binding` treats them as "no expression").
    pub fn is_binding_set(self: &Element, property_name: &str, need_explicit: bool) -> bool {
        self.any_in_inheritance_chain(|element| {
            element.bindings.0.get(property_name).is_some_and(|binding| {
                let binding = binding.borrow();
                binding.has_binding() && (!need_explicit || binding.priority > 0)
            })
        })
    }

    /// The layout info property of the base component's root that an instance
    /// reads. For the horizontal one, that is `layoutinfo-h-at-own-height` when
    /// `height_settled`, the instance's [`Self::height_is_literal`], which the
    /// root itself cannot know.
    pub(crate) fn base_layout_info_prop(
        &self,
        orientation: Orientation,
        height_settled: bool,
    ) -> Option<NamedReference> {
        let ElementType::Component(base) = &self.base_type else { return None };
        let root = base.root_element.borrow();
        root.layout_info_h_at_own_height
            .clone()
            .filter(|_| orientation == Orientation::Horizontal && height_settled)
            .or_else(|| root.effective_layout_info_prop(orientation).cloned())
    }

    /// Compute [`Self::height_is_literal`] for `elem`: whether its effective
    /// `height` binding is a length literal that is not a percentage.
    ///
    /// The effective binding is the one [`crate::layout::find_binding`] finds,
    /// the same walk that sets `LayoutConstraints::fixed_height`, so the two
    /// cannot disagree about which binding a height has. Why only a literal
    /// counts is in `docs/development/layout-system.md`, under "Width down,
    /// height up".
    pub(crate) fn compute_height_is_literal(elem: &ElementRc) -> bool {
        // The root of a component that is used elsewhere cannot answer for
        // itself: every instance may override the height, and each is asked
        // separately (see [`Element::base_layout_info_prop`]).
        let overridable_root = elem.borrow().enclosing_component.upgrade().is_some_and(|c| {
            Rc::ptr_eq(&c.root_element, elem)
                && c.used.get()
                && c.parent_element.borrow().upgrade().is_none()
        });
        if overridable_root {
            return false;
        }
        crate::layout::find_binding(elem, "height", |b, _, _| {
            matches!(b.value_expression(), Expression::NumberLiteral(_, unit) if *unit != Unit::Percent)
        })
        .unwrap_or(false)
    }

    /// Returns true if the property is set by a binding or an assignment expression
    ///
    /// Synthetic debug hooks (materialized for unbound properties) are not considered set.
    pub fn is_property_set(self: &Element, property_name: &str) -> bool {
        self.any_in_inheritance_chain(|element| {
            element
                .bindings
                .0
                .get(property_name)
                .is_some_and(|binding| !binding.borrow().expression.is_synthetic_debug_hook())
                || element
                    .property_analysis
                    .borrow()
                    .get(property_name)
                    .is_some_and(|analysis| analysis.is_set || analysis.is_linked)
        })
    }

    pub(crate) fn is_property_target_of_two_way_binding(&self, property_name: &str) -> bool {
        self.any_in_inheritance_chain(|element| {
            element
                .property_analysis
                .borrow()
                .get(property_name)
                .is_some_and(|analysis| analysis.is_linked)
        })
    }

    /// Whether `predicate` holds for this element or the root element of a component it derives from
    pub fn any_in_inheritance_chain(&self, predicate: impl Fn(&Element) -> bool + Copy) -> bool {
        predicate(self)
            || matches!(
                &self.base_type,
                ElementType::Component(base)
                    if base.root_element.borrow().any_in_inheritance_chain(predicate)
            )
    }

    /// The binding for `property_name`, if one exists and is not a synthetic debug hook.
    ///
    /// This is the hook-aware replacement for `self.bindings.get(..)`: a synthetic debug hook
    /// is a materialized placeholder for an *unbound* property and must read as "no binding".
    /// Use this instead of the raw map whenever the question is "did anything bind this
    /// property" or "what is this property's binding".
    pub fn binding(&self, property_name: &str) -> Option<Ref<'_, BindingExpression>> {
        self.bindings
            .0
            .get(property_name)
            .filter(|binding| !binding.borrow().expression.is_synthetic_debug_hook())
            .map(|binding| binding.borrow())
    }

    /// Same as [`Self::binding`], but returns a mutable reference to the binding.
    pub fn binding_mut(&self, property_name: &str) -> Option<RefMut<'_, BindingExpression>> {
        self.bindings
            .0
            .get(property_name)
            .filter(|binding| !binding.borrow().expression.is_synthetic_debug_hook())
            .map(|binding| binding.borrow_mut())
    }

    /// Iterate over the bindings that are not synthetic debug hooks.
    ///
    /// The hook-aware replacement for iterating `self.bindings` directly when enumerating the
    /// properties that are actually set on this element.
    pub fn real_bindings(&self) -> impl Iterator<Item = (&SmolStr, &RefCell<BindingExpression>)> {
        self.bindings
            .0
            .iter()
            .filter(|(_, binding)| !binding.borrow().expression.is_synthetic_debug_hook())
    }

    /// Iterate over every binding entry, including synthetic debug hooks.
    ///
    /// The counterpart to [`Self::real_bindings`]. Use only where synthetic hooks must be lowered
    /// or emitted (codegen, LLR, native-class selection); prefer `real_bindings()` everywhere else.
    pub fn bindings_including_synthetic(
        &self,
    ) -> impl Iterator<Item = (&SmolStr, &RefCell<BindingExpression>)> {
        self.bindings.0.iter()
    }

    /// The raw binding cell for `property_name`, including a synthetic debug hook.
    ///
    /// Returns the `&RefCell` rather than a borrow guard, so callers that need to borrow, drop,
    /// and re-borrow within one scope (reentrant binding analysis) or use `try_borrow` can do so.
    /// Does not filter synthetic hooks — prefer [`Self::binding`] unless synthetic hooks matter.
    pub fn binding_cell_including_synthetic(
        &self,
        property_name: &str,
    ) -> Option<&RefCell<BindingExpression>> {
        self.bindings.0.get(property_name)
    }

    /// Set the property `property_name` of this Element only if it was not set.
    /// the `expression_fn` will only be called if it isn't set.
    ///
    /// If a synthetic debug hook exists for this property, the hook's inner expression is
    /// replaced with the new value (keeping the wrapper and id) and the hook is marked
    /// non-synthetic — so the property becomes live-editable at its real computed value.
    ///
    /// Returns true if the binding was changed.
    pub fn set_binding_if_not_set(
        &mut self,
        property_name: SmolStr,
        expression_fn: impl FnOnce() -> Expression,
    ) -> bool {
        if self.is_binding_set(&property_name, false) {
            return false;
        }

        match self.bindings.0.entry(property_name) {
            Entry::Vacant(vacant_entry) => {
                let mut binding: BindingExpression = expression_fn().into();
                binding.priority = i32::MAX;
                vacant_entry.insert(binding.into());
            }
            Entry::Occupied(mut existing_entry) => {
                let inner = existing_entry.get_mut().get_mut();
                let mut binding: BindingExpression = expression_fn().into();
                binding.priority = i32::MAX;
                // merge_with takes care of overwriting synthetic debug hooks.
                inner.merge_with(&binding);
            }
        };
        true
    }

    /// Unconditionally set the property `property_name` to `new_binding`, but handle a synthetic
    /// debug hook that already occupies the slot specially: instead of replacing it, upgrade it
    /// in-place (replace its inner expression, clear `synthetic`, keep the wrapper+id so the
    /// property stays live-editable).
    ///
    /// Returns the old `BindingExpression` if a *real* (non-synthetic) binding was displaced so
    /// the caller can report a conflict.  Returns `None` if the slot was empty or held only a
    /// synthetic hook (no conflict).
    ///
    /// This is intended for passes like `lower_layout` that must force-set a property and need to
    /// distinguish a genuine conflict from a synthetic placeholder.
    pub fn set_binding(
        &mut self,
        property_name: SmolStr,
        mut new_binding: BindingExpression,
    ) -> Option<BindingExpression> {
        match self.bindings.0.entry(property_name) {
            Entry::Vacant(v) => {
                v.insert(RefCell::new(new_binding));
                None
            }
            Entry::Occupied(mut e) => {
                let existing = e.get_mut().get_mut();
                if let expression_tree::Expression::DebugHook { expression: _, synthetic, id } =
                    &mut existing.expression
                    && *synthetic
                {
                    // Adopt the previous synthetic debug hook into the new binding, which is now no
                    // longer synthetic.
                    let new_debug_hook = expression_tree::Expression::DebugHook {
                        expression: Box::new(new_binding.expression),
                        id: id.clone(),
                        synthetic: false,
                    };
                    new_binding.expression = new_debug_hook;
                    *existing = new_binding;
                    // previously the binding was only a synthetic debug hook - don't report a
                    // conflict
                    return None;
                }
                // Real (non-synthetic) binding exists: replace it and report the conflict.
                Some(std::mem::replace(e.get_mut().get_mut(), new_binding))
            }
        }
    }

    /// Remove the binding for `property_name` and return it.
    ///
    /// The map entry is removed whether it held a real binding or only a synthetic debug hook,
    /// but the result is `Some` only for a real binding — a synthetic-only slot reads as `None`,
    /// matching "nothing was ever bound here". Dropping a leftover synthetic hook is safe for the
    /// lowering passes that consume, rename, or delete a property this way.
    pub fn take_binding(&mut self, property_name: &str) -> Option<BindingExpression> {
        self.take_binding_including_synthetic(property_name)
            .filter(|binding| !binding.expression.is_synthetic_debug_hook())
    }

    /// Remove the binding for `property_name` and return it (including synthetic debug hooks).
    pub fn take_binding_including_synthetic(
        &mut self,
        property_name: &str,
    ) -> Option<BindingExpression> {
        self.bindings.0.remove(property_name).map(RefCell::into_inner)
    }

    /// Remove and return the whole binding map, including synthetic debug hooks.
    ///
    /// For bulk transfers that move an element's bindings wholesale.
    pub(crate) fn take_bindings_including_synthetic(&mut self) -> BindingsMap {
        std::mem::take(&mut self.bindings.0)
    }

    /// Add the given binding entries, including synthetic debug hooks, to this element.
    ///
    /// For bulk transfers; like `BTreeMap::extend`, an entry with the same name is overwritten
    /// (no merge or priority adjustment).
    pub(crate) fn extend_bindings_including_synthetic(
        &mut self,
        bindings: impl IntoIterator<Item = (SmolStr, RefCell<BindingExpression>)>,
    ) {
        self.bindings.0.extend(bindings);
    }

    pub fn sub_component(&self) -> Option<&Rc<Component>> {
        if self.repeated.is_some() {
            None
        } else if let ElementType::Component(sub_component) = &self.base_type {
            Some(sub_component)
        } else {
            None
        }
    }

    pub fn element_infos(&self) -> String {
        let mut debug_infos = self.debug.clone();
        let mut base = self.base_type.clone();
        while let ElementType::Component(b) = base {
            let elem = b.root_element.borrow();
            base = elem.base_type.clone();
            debug_infos.extend(elem.debug.iter().cloned());
        }

        let (infos, _, _) = debug_infos.into_iter().fold(
            (String::new(), false, true),
            |(mut infos, elem_boundary, first), debug_info| {
                if elem_boundary {
                    infos.push('/');
                } else if !first {
                    infos.push(';');
                }

                infos.push_str(&debug_info.encoded_element_info());
                (infos, debug_info.element_boundary, false)
            },
        );
        infos
    }
}

/// For FlexboxLayout, suggest Slint property names for CSS properties.
fn css_property_suggestion(property_name: &str, base_type: &ElementType) -> Option<String> {
    let base_name = base_type.to_smolstr();
    if base_name != "FlexboxLayout" {
        return None;
    }
    match property_name {
        "gap" => Some("Use spacing instead of gap".into()),
        "row-gap" => Some("Use spacing-vertical instead of row-gap".into()),
        "column-gap" => Some("Use spacing-horizontal instead of column-gap".into()),
        "justify-content" => Some("Use alignment instead of justify-content".into()),
        _ => None,
    }
}

/// Apply the default property values of the builtin element to the element.
pub(crate) fn apply_default_type_properties(element: &mut Element) {
    // Apply default property values on top:
    if let ElementType::Builtin(builtin_base) = &element.base_type {
        for (prop, info) in &builtin_base.properties {
            // A property the element declares under the same name is a different property.
            // `ensure_window` gets here with an element that declared its members before it
            // became a window.
            if element.property_declarations.contains_key(prop) {
                continue;
            }
            if let Some(expr) = info.default_value.expr_without_element() {
                element.bindings.0.entry(prop.clone()).or_insert_with(|| {
                    let mut binding = BindingExpression::from(expr);
                    binding.priority = i32::MAX;
                    RefCell::new(binding)
                });
            }
        }
    }
}

/// Create a Type for this node
pub fn type_from_node(
    node: syntax_nodes::Type,
    diag: &mut BuildDiagnostics,
    tr: &TypeRegister,
) -> Type {
    if let Some(qualified_type_node) = node.QualifiedName() {
        let qualified_type = QualifiedTypeName::from_node(qualified_type_node.clone());

        let prop_type = tr.lookup_qualified(&qualified_type.members);

        #[cfg(feature = "slint-sc")]
        if !prop_type.is_slint_sc() {
            diag.slint_sc_error(&format!("The type '{qualified_type}' is"), &qualified_type_node);
        }

        if prop_type == Type::Invalid && tr.lookup_element(&qualified_type.to_smolstr()).is_err() {
            diag.push_error(format!("Unknown type '{qualified_type}'"), &qualified_type_node);
        } else if !prop_type.is_property_type() {
            diag.push_error(
                format!("'{qualified_type}' is not a valid type"),
                &qualified_type_node,
            );
        }
        prop_type
    } else if let Some(object_node) = node.ObjectType() {
        #[cfg(feature = "slint-sc")]
        diag.slint_sc_error("Inline struct types are", &object_node);
        type_struct_from_node(object_node, diag, tr, None, None)
    } else if let Some(array_node) = node.ArrayType() {
        #[cfg(feature = "slint-sc")]
        diag.slint_sc_error("Array types are", &array_node);
        Type::Array(Arc::new(type_from_node(array_node.Type(), diag, tr)))
    } else {
        assert!(diag.has_errors());
        Type::Invalid
    }
}

/// Create a [`Type::Struct`] from a [`syntax_nodes::ObjectType`]
///
/// `symbol_counters` is only available for named struct declarations,
/// where field default values (`struct Foo { bar: int = 42 }`) are supported.
pub fn type_struct_from_node(
    object_node: syntax_nodes::ObjectType,
    diag: &mut BuildDiagnostics,
    tr: &TypeRegister,
    name: Option<SmolStr>,
    symbol_counters: Option<&Rc<crate::symbol_counters::SymbolCounters>>,
) -> Type {
    let mut field_defaults = BTreeMap::default();
    let mut field_order = Vec::new();
    let fields: BTreeMap<SmolStr, Type> = object_node
        .ObjectTypeMember()
        .map(|member| {
            let field_name = parser::identifier_text(&member).unwrap_or_default();
            field_order.push(field_name.clone());
            let field_ty = type_from_node(member.Type(), diag, tr);
            if let Some(default_value_node) = member.Expression() {
                if name.is_none() {
                    diag.push_error(
                        "Field default values are only supported in named struct declarations"
                            .into(),
                        &default_value_node,
                    );
                } else if let Some(expr) = resolve_struct_field_default_value(
                    default_value_node,
                    &field_ty,
                    diag,
                    tr,
                    symbol_counters.expect("named struct declarations have symbol counters"),
                ) {
                    field_defaults.insert(field_name.clone(), expr);
                }
            }
            (field_name, field_ty)
        })
        .collect();
    // The `@rust-attr` attributes and the declaration node live on the
    // enclosing `StructDeclaration` (the parent of the `ObjectType`).
    let struct_decl = object_node.parent();
    Type::Struct(Arc::new(Struct {
        fields,
        field_defaults,
        name: name.map_or(StructName::None, |name| {
            let rust_attributes = struct_decl
                .as_ref()
                .and_then(|p| syntax_nodes::StructDeclaration::new(p.clone()))
                .map(|d| d.AtRustAttr().map(|a| SmolStr::from(a.text().to_string())).collect())
                .unwrap_or_default();
            let node = struct_decl.as_ref().unwrap_or(&object_node).to_source_location();
            StructName::User { name, node, rust_attributes, field_order }
        }),
    }))
}

/// Resolve, type-check, and constant-fold the default value expression of a struct field.
/// Returns `None` (with a diagnostic) if the expression is not a compile time constant.
fn resolve_struct_field_default_value(
    node: syntax_nodes::Expression,
    field_ty: &Type,
    diag: &mut BuildDiagnostics,
    tr: &TypeRegister,
    symbol_counters: &Rc<crate::symbol_counters::SymbolCounters>,
) -> Option<crate::langtype::ConstantExpression> {
    #[cfg(feature = "slint-sc")]
    diag.slint_sc_error("Struct field default values are", &node);
    let mut expr = {
        let mut ctx = crate::lookup::LookupCtx::empty_context(tr, diag, symbol_counters.clone());
        ctx.property_type = field_ty.clone();
        Expression::from_expression_node(node.clone(), &mut ctx).maybe_convert_to(
            field_ty.clone(),
            &node,
            ctx.diag,
            &ctx.symbol_counters,
        )
    };
    crate::passes::const_propagation::fold_const_expression(&mut expr);
    // An error was already reported when a part of the expression failed to resolve
    // or convert; don't report a confusing constant-ness error on top of it
    let mut has_invalid = false;
    expr.visit_recursive(&mut |e| has_invalid |= matches!(e, Expression::Invalid));
    if has_invalid {
        return None;
    }
    let constant = crate::langtype::ConstantExpression::from_expression(&expr);
    if constant.is_none() {
        let reason = non_constant_expression_reason(&expr)
            .map_or_else(Default::default, |reason| format!(": {reason}"));
        diag.push_error(
            format!("The default value of a struct field must be a constant expression{reason}"),
            &node,
        );
    }
    constant
}

/// A user-facing explanation of what makes the expression non-constant, if there is
/// a better one than "it is not in the supported subset"
fn non_constant_expression_reason(expr: &Expression) -> Option<String> {
    use crate::expression_tree::{BuiltinFunction, Callable};
    let mut reason = None;
    expr.visit_recursive(&mut |e| {
        if reason.is_some() {
            return;
        }
        reason = match e {
            Expression::PropertyReference(nr) => {
                Some(format!("it references the property '{}'", nr.name()))
            }
            Expression::FunctionCall { function, .. } => match function {
                Callable::Function(nr) => Some(format!("it calls the function '{}'", nr.name())),
                Callable::Callback(nr) => Some(format!("it calls the callback '{}'", nr.name())),
                Callable::Builtin(BuiltinFunction::GetWindowScaleFactor) => Some(
                    "the conversion to logical pixels depends on the window's scale factor".into(),
                ),
                Callable::Builtin(BuiltinFunction::GetWindowDefaultFontSize) => Some(
                    "the conversion from 'rem' depends on the window's default font size".into(),
                ),
                Callable::Builtin(BuiltinFunction::Translate) => {
                    Some("the translation is selected at run-time".into())
                }
                Callable::Builtin(_) => Some("functions are not evaluated at compile time".into()),
            },
            Expression::Cast { to: Type::String, .. } => {
                Some("the conversion from a number to a string depends on the locale".into())
            }
            _ => None,
        };
    });
    reason
}

fn animation_element_from_node(
    anim: &syntax_nodes::PropertyAnimation,
    prop_name: &syntax_nodes::QualifiedName,
    prop_type: Type,
    diag: &mut BuildDiagnostics,
    tr: &TypeRegister,
) -> Option<ElementRc> {
    let anim_type = tr.property_animation_type_for_property(prop_type);
    if !matches!(anim_type, ElementType::Builtin(..)) {
        diag.push_error(
            format!(
                "'{}' is not a property that can be animated",
                prop_name.text().to_string().trim()
            ),
            prop_name,
        );
        None
    } else {
        let mut anim_element =
            Element { id: "".into(), base_type: anim_type, ..Default::default() };
        anim_element.parse_bindings(
            anim.Binding().filter_map(|b| {
                Some((b.child_token(SyntaxKind::Identifier)?, b.BindingExpression().into()))
            }),
            false,
            diag,
        );

        apply_default_type_properties(&mut anim_element);

        Some(Rc::new(RefCell::new(anim_element)))
    }
}

#[derive(Default, Debug, Clone)]
pub struct QualifiedTypeName {
    pub members: Vec<SmolStr>,
}

impl QualifiedTypeName {
    pub fn from_node(node: syntax_nodes::QualifiedName) -> Self {
        debug_assert_eq!(node.kind(), SyntaxKind::QualifiedName);
        let members = node
            .children_with_tokens()
            .filter(|n| n.kind() == SyntaxKind::Identifier)
            .filter_map(|x| x.as_token().map(|x| crate::parser::normalize_identifier(x.text())))
            .collect();
        Self { members }
    }

    pub fn to_smolstr(&self) -> SmolStr {
        self.members.join(".").into()
    }
}

impl Display for QualifiedTypeName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.members.join("."))
    }
}

/// Return a NamedReference for a qualified name used in a state (or transition),
/// if the reference is invalid, there will be a diagnostic
fn lookup_property_from_qualified_name_for_state(
    node: syntax_nodes::QualifiedName,
    r: &ElementRc,
    diag: &mut BuildDiagnostics,
) -> Option<(NamedReference, Type)> {
    let qualname = QualifiedTypeName::from_node(node.clone());
    let check = |lookup: &PropertyLookupResult<'_>, diag: &mut BuildDiagnostics| {
        #[cfg(feature = "slint-sc")]
        lookup.check_slint_sc(&qualname, &node, diag);
        if !lookup.property_type.is_property_type() {
            diag.push_error(format!("'{qualname}' is not a valid property"), &node);
        } else if !lookup.is_valid_for_assignment() {
            diag.push_error(
                format!(
                    "'{}' cannot be set in a state because it is '{}'",
                    qualname, lookup.property_visibility
                ),
                &node,
            );
        }
    };
    match qualname.members.as_slice() {
        [unresolved_prop_name] => {
            let lookup_result = r
                .borrow()
                .lookup_property(unresolved_prop_name.as_ref(), PropertyLookupMode::ComponentLocal);
            check(&lookup_result, diag);
            Some((
                NamedReference::new(r, lookup_result.internal_or_resolved_name()),
                lookup_result.property_type,
            ))
        }
        [elem_id, unresolved_prop_name] => {
            if let Some(element) = find_element_by_id(r, elem_id.as_ref()) {
                let lookup_result = element.borrow().lookup_property(
                    unresolved_prop_name.as_ref(),
                    PropertyLookupMode::ComponentLocal,
                );
                if !lookup_result.is_valid() {
                    diag.push_error(
                        format!("'{unresolved_prop_name}' not found in '{elem_id}'"),
                        &node,
                    );
                } else {
                    check(&lookup_result, diag);
                }
                Some((
                    NamedReference::new(&element, lookup_result.internal_or_resolved_name()),
                    lookup_result.property_type,
                ))
            } else {
                diag.push_error(format!("'{elem_id}' is not a valid element id"), &node);
                None
            }
        }
        _ => {
            diag.push_error(format!("'{qualname}' is not a valid property"), &node);
            None
        }
    }
}

/// FIXME: this is duplicated the resolving pass. Also, we should use a hash table
fn find_element_by_id(e: &ElementRc, name: &str) -> Option<ElementRc> {
    if e.borrow().id == name {
        return Some(e.clone());
    }
    for x in &e.borrow().children {
        if x.borrow().repeated.is_some() {
            continue;
        }
        if let Some(x) = find_element_by_id(x, name) {
            return Some(x);
        }
    }

    None
}

/// Find the parent element to a given element.
/// (since there is no parent mapping we need to fo an exhaustive search)
pub fn find_parent_element(e: &ElementRc) -> Option<ElementRc> {
    fn recurse(base: &ElementRc, e: &ElementRc) -> Option<ElementRc> {
        for child in &base.borrow().children {
            if Rc::ptr_eq(child, e) {
                return Some(base.clone());
            }
            if let Some(x) = recurse(child, e) {
                return Some(x);
            }
        }
        None
    }

    let root = e.borrow().enclosing_component.upgrade().unwrap().root_element.clone();
    if Rc::ptr_eq(&root, e) {
        return None;
    }
    recurse(&root, e)
}

/// Call the visitor for each children of the element recursively, starting with the element itself
///
/// The state returned by the visitor is passed to the children
pub fn recurse_elem<State>(
    elem: &ElementRc,
    state: &State,
    vis: &mut impl FnMut(&ElementRc, &State) -> State,
) {
    recurse_elem_dyn(elem, state, vis)
}

fn recurse_elem_dyn<State>(
    elem: &ElementRc,
    state: &State,
    vis: &mut dyn FnMut(&ElementRc, &State) -> State,
) {
    let state = vis(elem, state);
    for sub in &elem.borrow().children {
        recurse_elem_dyn(sub, &state, vis);
    }
}

/// Same as [`recurse_elem`] but include the elements from sub_components
pub fn recurse_elem_including_sub_components<State>(
    component: &Component,
    state: &State,
    vis: &mut impl FnMut(&ElementRc, &State) -> State,
) {
    recurse_elem_including_sub_components_dyn(component, state, vis)
}

fn recurse_elem_including_sub_components_dyn<State>(
    component: &Component,
    state: &State,
    vis: &mut dyn FnMut(&ElementRc, &State) -> State,
) {
    recurse_elem_dyn(&component.root_element, state, &mut |elem, state| {
        debug_assert!(std::ptr::eq(
            component as *const Component,
            (&*elem.borrow().enclosing_component.upgrade().unwrap()) as *const Component
        ));
        if elem.borrow().repeated.is_some()
            && let ElementType::Component(base) = &elem.borrow().base_type
            && base.parent_element().is_some()
        {
            recurse_elem_including_sub_components_dyn(base, state, vis);
        }
        vis(elem, state)
    });
    component
        .popup_windows
        .borrow()
        .iter()
        .for_each(|p| recurse_elem_including_sub_components_dyn(&p.component, state, vis));
    component
        .menu_item_tree
        .borrow()
        .iter()
        .for_each(|c| recurse_elem_including_sub_components_dyn(c, state, vis));
}

/// Same as recurse_elem, but will take the children from the element as to not keep the element borrow
pub fn recurse_elem_no_borrow<State>(
    elem: &ElementRc,
    state: &State,
    vis: &mut impl FnMut(&ElementRc, &State) -> State,
) {
    recurse_elem_no_borrow_dyn(elem, state, vis)
}

fn recurse_elem_no_borrow_dyn<State>(
    elem: &ElementRc,
    state: &State,
    vis: &mut dyn FnMut(&ElementRc, &State) -> State,
) {
    let state = vis(elem, state);
    let children = elem.borrow().children.clone();
    for sub in &children {
        recurse_elem_no_borrow_dyn(sub, &state, vis);
    }
}

/// Same as [`recurse_elem`] but include the elements form sub_components
pub fn recurse_elem_including_sub_components_no_borrow<State>(
    component: &Component,
    state: &State,
    vis: &mut impl FnMut(&ElementRc, &State) -> State,
) {
    recurse_elem_including_sub_components_no_borrow_dyn(component, state, vis)
}

fn recurse_elem_including_sub_components_no_borrow_dyn<State>(
    component: &Component,
    state: &State,
    vis: &mut dyn FnMut(&ElementRc, &State) -> State,
) {
    recurse_elem_no_borrow_dyn(&component.root_element, state, &mut |elem, state| {
        let base = if elem.borrow().repeated.is_some() {
            if let ElementType::Component(base) = &elem.borrow().base_type {
                if base.parent_element().is_some() {
                    Some(base.clone())
                } else {
                    // The process_repeater_components pass was not run yet
                    None
                }
            } else {
                None
            }
        } else {
            None
        };
        if let Some(base) = base {
            recurse_elem_including_sub_components_no_borrow_dyn(&base, state, vis);
        }
        vis(elem, state)
    });
    component.popup_windows.borrow().iter().for_each(|p| {
        recurse_elem_including_sub_components_no_borrow_dyn(&p.component, state, vis)
    });
    component
        .menu_item_tree
        .borrow()
        .iter()
        .for_each(|c| recurse_elem_including_sub_components_no_borrow_dyn(c, state, vis));
}

/// Visit the model expression of `elem`, if `elem` is the body of a `for`.
///
/// The expression is temporarily moved out of `repeated.model` so the visitor
/// can mutate it without holding a borrow on `elem`.
pub fn visit_repeater_model_expression(
    elem: &ElementRc,
    mut vis: impl FnMut(&mut Expression, Option<&str>, &dyn Fn() -> Type),
) {
    let repeated = elem
        .borrow_mut()
        .repeated
        .as_mut()
        .map(|r| (std::mem::take(&mut r.model), r.is_conditional_element));
    if let Some((mut model, is_cond)) = repeated {
        vis(&mut model, None, &|| if is_cond { Type::Bool } else { Type::Model });
        elem.borrow_mut().repeated.as_mut().unwrap().model = model;
    }
}

/// Like [`visit_element_expressions`] but skips the repeater model
/// expression. Use [`visit_repeater_model_expression`] separately for that.
pub fn visit_element_expressions_excluding_repeater_model(
    elem: &ElementRc,
    mut vis: impl FnMut(&mut Expression, Option<&str>, &dyn Fn() -> Type),
) {
    visit_element_expressions_excluding_repeater_model_dyn(elem, &mut vis)
}

fn visit_element_expressions_excluding_repeater_model_dyn(
    elem: &ElementRc,
    vis: &mut dyn FnMut(&mut Expression, Option<&str>, &dyn Fn() -> Type),
) {
    fn visit_element_expressions_simple(
        elem: &ElementRc,
        vis: &mut dyn FnMut(&mut Expression, Option<&str>, &dyn Fn() -> Type),
    ) {
        for (name, expr) in elem.borrow().bindings_including_synthetic() {
            vis(&mut expr.borrow_mut(), Some(name.as_str()), &|| {
                elem.borrow().lookup_property(name, PropertyLookupMode::InternalName).property_type
            });

            for twb in &mut expr.borrow_mut().two_way_bindings {
                if let expression_tree::TwoWayBinding::ModelData { repeated_element, .. } = twb {
                    let mut e =
                        Expression::RepeaterModelReference { element: repeated_element.clone() };
                    vis(&mut e, None, &|| Type::Invalid);
                    if let Expression::RepeaterModelReference { element } = e {
                        *repeated_element = element;
                    }
                }
            }

            match &mut expr.borrow_mut().animation {
                Some(PropertyAnimation::Static(e)) => visit_element_expressions_simple(e, vis),
                Some(PropertyAnimation::Transition { animations, state_ref }) => {
                    vis(state_ref, None, &|| Type::Int32);
                    for a in animations {
                        visit_element_expressions_simple(&a.animation, vis)
                    }
                }
                None => (),
            }
        }
    }

    visit_element_expressions_simple(elem, vis);

    for expr in elem.borrow().change_callbacks.values() {
        for expr in expr.borrow_mut().iter_mut() {
            vis(expr, Some("$change callback$"), &|| Type::Void);
        }
    }

    let mut states = std::mem::take(&mut elem.borrow_mut().states);
    for s in &mut states {
        if let Some(cond) = s.condition.as_mut() {
            vis(cond, None, &|| Type::Bool)
        }
        for (ne, e, _) in &mut s.property_changes {
            vis(e, Some(ne.name()), &|| {
                ne.element()
                    .borrow()
                    .lookup_property(ne.name(), PropertyLookupMode::InternalName)
                    .property_type
            });
        }
    }
    elem.borrow_mut().states = states;

    let mut transitions = std::mem::take(&mut elem.borrow_mut().transitions);
    for t in &mut transitions {
        for (_, _, a) in &mut t.property_animations {
            visit_element_expressions_simple(a, vis);
        }
    }
    elem.borrow_mut().transitions = transitions;

    let component = elem.borrow().enclosing_component.upgrade().unwrap();
    if Rc::ptr_eq(&component.root_element, elem) {
        for e in component.init_code.borrow_mut().iter_mut() {
            vis(e, None, &|| Type::Void);
        }
    }
}

pub fn visit_element_expressions(
    elem: &ElementRc,
    mut vis: impl FnMut(&mut Expression, Option<&str>, &dyn Fn() -> Type),
) {
    visit_repeater_model_expression(elem, &mut vis);
    visit_element_expressions_excluding_repeater_model(elem, &mut vis);
}

pub fn visit_named_references_in_expression(
    expr: &mut Expression,
    vis: &mut impl FnMut(&mut NamedReference),
) {
    visit_named_references_in_expression_dyn(expr, vis)
}

fn visit_named_references_in_expression_dyn(
    expr: &mut Expression,
    vis: &mut dyn FnMut(&mut NamedReference),
) {
    expr.visit_mut(|sub| visit_named_references_in_expression_dyn(sub, vis));
    match expr {
        Expression::PropertyReference(r) => vis(r),
        Expression::FunctionCall {
            function: Callable::Callback(r) | Callable::Function(r),
            ..
        } => vis(r),
        Expression::LayoutCacheAccess { layout_cache_prop, .. } => vis(layout_cache_prop),
        Expression::GridRepeaterCacheAccess { layout_cache_prop, .. } => vis(layout_cache_prop),
        Expression::OrganizeGridLayout(l) => l.visit_named_references(vis),
        Expression::ComputeBoxLayoutInfo { layout, .. } => layout.visit_named_references(vis),
        Expression::ComputeFlexboxLayoutInfo { layout, .. } => layout.visit_named_references(vis),
        Expression::ComputeGridLayoutInfo { layout_organized_data_prop, layout, .. } => {
            vis(layout_organized_data_prop);
            layout.visit_named_references(vis);
        }
        Expression::SolveBoxLayout(l, _) => l.visit_named_references(vis),
        Expression::SolveFlexboxLayout(l) => l.visit_named_references(vis),
        Expression::SolveGridLayout { layout_organized_data_prop, layout, .. } => {
            vis(layout_organized_data_prop);
            layout.visit_named_references(vis);
        }
        // This is not really a named reference, but the result is the same, it need to be updated
        // FIXME: this should probably be lowered into a PropertyReference
        Expression::RepeaterModelReference { element }
        | Expression::RepeaterIndexReference { element } => {
            // FIXME: this is questionable
            let mut nc =
                NamedReference::new(&element.upgrade().unwrap(), SmolStr::new_static("$model"));
            vis(&mut nc);
            debug_assert!(nc.element().borrow().repeated.is_some());
            *element = Rc::downgrade(&nc.element());
        }
        _ => {}
    }
}

/// Visit all the named reference in an element
/// But does not recurse in sub-elements. (unlike [`visit_all_named_references`] which recurse)
pub fn visit_all_named_references_in_element(
    elem: &ElementRc,
    mut vis: impl FnMut(&mut NamedReference),
) {
    visit_all_named_references_in_element_dyn(elem, &mut vis)
}

fn visit_all_named_references_in_element_dyn(
    elem: &ElementRc,
    mut vis: &mut dyn FnMut(&mut NamedReference),
) {
    visit_element_expressions(elem, |expr, _, _| {
        visit_named_references_in_expression_dyn(expr, vis)
    });
    let mut states = std::mem::take(&mut elem.borrow_mut().states);
    for s in &mut states {
        for (r, _, _) in &mut s.property_changes {
            vis(r);
        }
    }
    elem.borrow_mut().states = states;
    let mut transitions = std::mem::take(&mut elem.borrow_mut().transitions);
    for t in &mut transitions {
        for (r, _, _) in &mut t.property_animations {
            vis(r)
        }
    }
    elem.borrow_mut().transitions = transitions;
    let mut repeated = std::mem::take(&mut elem.borrow_mut().repeated);
    if let Some(r) = &mut repeated
        && let Some(lv) = &mut r.is_listview
    {
        vis(&mut lv.content_y);
        if let Some(content_height) = &mut lv.content_height {
            vis(content_height);
        }
        if let Some(content_width) = &mut lv.content_width {
            vis(content_width);
        }
        vis(&mut lv.listview_height);
        vis(&mut lv.listview_width);
    }
    elem.borrow_mut().repeated = repeated;
    let mut layout_info_prop = std::mem::take(&mut elem.borrow_mut().layout_info_prop);
    layout_info_prop.as_mut().map(|(h, b)| (vis(h), vis(b)));
    elem.borrow_mut().layout_info_prop = layout_info_prop;
    let mut constrained_v = std::mem::take(&mut elem.borrow_mut().layout_info_v_with_constraint);
    if let Some(nr) = constrained_v.as_mut() {
        vis(nr);
    }
    elem.borrow_mut().layout_info_v_with_constraint = constrained_v;
    let mut at_own_height = std::mem::take(&mut elem.borrow_mut().layout_info_h_at_own_height);
    if let Some(nr) = at_own_height.as_mut() {
        vis(nr);
    }
    elem.borrow_mut().layout_info_h_at_own_height = at_own_height;
    let mut debug = std::mem::take(&mut elem.borrow_mut().debug);
    for d in debug.iter_mut() {
        if let Some(l) = d.layout.as_mut() {
            l.visit_named_references(vis)
        }
    }
    elem.borrow_mut().debug = debug;

    let mut accessibility_props = std::mem::take(&mut elem.borrow_mut().accessibility_props);
    accessibility_props.0.iter_mut().for_each(|(_, x)| vis(x));
    elem.borrow_mut().accessibility_props = accessibility_props;

    let geometry_props = elem.borrow_mut().geometry_props.take();
    if let Some(mut geometry_props) = geometry_props {
        vis(&mut geometry_props.x);
        vis(&mut geometry_props.y);
        vis(&mut geometry_props.width);
        vis(&mut geometry_props.height);
        elem.borrow_mut().geometry_props = Some(geometry_props);
    }

    let z_order = elem.borrow_mut().z_order.take();
    if let Some(mut zo) = z_order {
        if let ZOrder::Dynamic(ref mut nr) | ZOrder::PerInstance(ref mut nr) = zo {
            vis(nr);
        }
        elem.borrow_mut().z_order = Some(zo);
    }

    // visit two way bindings
    for (_, expr) in elem.borrow().real_bindings() {
        for twb in &mut expr.borrow_mut().two_way_bindings {
            if let expression_tree::TwoWayBinding::Property { property, .. } = twb {
                vis(property);
            }
        }
    }

    let mut property_declarations = std::mem::take(&mut elem.borrow_mut().property_declarations);
    for pd in property_declarations.values_mut() {
        pd.is_alias.as_mut().map(&mut vis);
    }
    elem.borrow_mut().property_declarations = property_declarations;

    // Visit grid_layout_cell for repeated Row elements
    let grid_layout_cell = elem.borrow_mut().grid_layout_cell.take();
    if let Some(grid_layout_cell) = grid_layout_cell {
        grid_layout_cell.borrow_mut().visit_named_references(&mut vis);
        elem.borrow_mut().grid_layout_cell = Some(grid_layout_cell);
    }
}

/// Visit all named reference in this component and sub component
pub fn visit_all_named_references(
    component: &Component,
    vis: &mut impl FnMut(&mut NamedReference),
) {
    visit_all_named_references_dyn(component, vis)
}

fn visit_all_named_references_dyn(component: &Component, vis: &mut dyn FnMut(&mut NamedReference)) {
    recurse_elem_including_sub_components_no_borrow_dyn(
        component,
        &Weak::new(),
        &mut |elem, parent_compo| {
            visit_all_named_references_in_element_dyn(elem, vis);
            let compo = elem.borrow().enclosing_component.clone();
            if !Weak::ptr_eq(parent_compo, &compo) {
                let compo = compo.upgrade().unwrap();
                compo.root_constraints.borrow_mut().visit_named_references(vis);
                compo.popup_windows.borrow_mut().iter_mut().for_each(|p| {
                    vis(&mut p.x);
                    vis(&mut p.y);
                    if let Some(is_open) = &mut p.is_open {
                        vis(is_open);
                    }
                });
                compo.timers.borrow_mut().iter_mut().for_each(|t| {
                    vis(&mut t.interval);
                    vis(&mut t.triggered);
                    vis(&mut t.running);
                });
                for o in compo.optimized_elements.borrow().iter() {
                    visit_element_expressions(o, |expr, _, _| {
                        visit_named_references_in_expression_dyn(expr, vis)
                    });
                }
            }
            compo
        },
    );
}

/// Visit all expression in this component and sub components
///
/// Does not recurse in the expression itself
pub fn visit_all_expressions(
    component: &Component,
    mut vis: impl FnMut(&mut Expression, &dyn Fn() -> Type),
) {
    visit_all_expressions_dyn(component, &mut vis)
}

fn visit_all_expressions_dyn(
    component: &Component,
    vis: &mut dyn FnMut(&mut Expression, &dyn Fn() -> Type),
) {
    recurse_elem_including_sub_components_dyn(component, &Weak::new(), &mut |elem, parent_compo| {
        visit_element_expressions(elem, |expr, _, ty| vis(expr, ty));
        let compo = elem.borrow().enclosing_component.clone();
        if !Weak::ptr_eq(parent_compo, &compo) {
            let compo = compo.upgrade().unwrap();
            for o in compo.optimized_elements.borrow().iter() {
                visit_element_expressions(o, |expr, _, ty| vis(expr, ty));
            }
        }
        compo
    })
}

#[derive(Debug, Clone)]
pub struct State {
    pub id: SmolStr,
    pub condition: Option<Expression>,
    pub property_changes: Vec<(NamedReference, Expression, syntax_nodes::StatePropertyChange)>,
    /// Where the source writes this state's selection. `None` for a state
    /// without a condition, which is never selected.
    pub selection: Option<ConditionLocation>,
}

#[derive(Debug, Clone)]
pub struct Transition {
    pub direction: TransitionDirection,
    pub state_id: SmolStr,
    pub property_animations: Vec<(NamedReference, SourceLocation, ElementRc)>,
    pub node: syntax_nodes::Transition,
}

impl Transition {
    fn from_node(
        trs: syntax_nodes::Transition,
        r: &ElementRc,
        tr: &TypeRegister,
        diag: &mut BuildDiagnostics,
    ) -> Transition {
        if let Some(star) = trs.child_token(SyntaxKind::Star) {
            diag.push_error("catch-all not yet implemented".into(), &star);
        };
        let direction_text = trs
            .first_child_or_token()
            .and_then(|t| t.as_token().map(|tok| tok.text().to_string()))
            .unwrap_or_default();

        Transition {
            direction: match direction_text.as_str() {
                "in" => TransitionDirection::In,
                "out" => TransitionDirection::Out,
                "in-out" => TransitionDirection::InOut,
                "in_out" => TransitionDirection::InOut,
                _ => {
                    unreachable!("Unknown transition direction: '{}'", direction_text);
                }
            },
            state_id: trs
                .DeclaredIdentifier()
                .and_then(|x| parser::identifier_text(&x))
                .unwrap_or_default(),
            property_animations: trs
                .PropertyAnimation()
                .flat_map(|pa| pa.QualifiedName().map(move |qn| (pa.clone(), qn)))
                .filter_map(|(pa, qn)| {
                    lookup_property_from_qualified_name_for_state(qn.clone(), r, diag).and_then(
                        |(ne, prop_type)| {
                            animation_element_from_node(&pa, &qn, prop_type, diag, tr)
                                .map(|anim_element| (ne, qn.to_source_location(), anim_element))
                        },
                    )
                })
                .collect(),
            node: trs.clone(),
        }
    }
}

#[derive(Clone, Debug, derive_more::Deref)]
pub struct ExportedName {
    #[deref]
    pub name: SmolStr, // normalized
    pub name_ident: SyntaxNode,
}

impl ExportedName {
    pub fn original_name(&self) -> SmolStr {
        self.name_ident
            .child_token(parser::SyntaxKind::Identifier)
            .map(|n| n.to_smolstr())
            .unwrap_or_else(|| self.name.clone())
    }

    pub fn from_export_specifier(
        export_specifier: &syntax_nodes::ExportSpecifier,
    ) -> (SmolStr, ExportedName) {
        let internal_name =
            parser::identifier_text(&export_specifier.ExportIdentifier()).unwrap_or_default();

        let (name, name_ident): (SmolStr, SyntaxNode) = export_specifier
            .ExportName()
            .and_then(|ident| {
                parser::identifier_text(&ident).map(|text| (text, ident.clone().into()))
            })
            .unwrap_or_else(|| (internal_name.clone(), export_specifier.ExportIdentifier().into()));
        (internal_name, ExportedName { name, name_ident })
    }
}

#[derive(Default, Debug, derive_more::Deref)]
pub struct Exports {
    #[deref]
    components_or_types: Vec<(ExportedName, Either<Rc<Component>, Type>)>,
}

impl Exports {
    pub fn from_node(
        doc: &syntax_nodes::Document,
        inner_components: &[Rc<Component>],
        type_registry: &TypeRegister,
        diag: &mut BuildDiagnostics,
    ) -> Self {
        let resolve_export_to_inner_component_or_import =
            |internal_name: &str, internal_name_node: &dyn Spanned, diag: &mut BuildDiagnostics| {
                if let Ok(ElementType::Component(c)) = type_registry.lookup_element(internal_name) {
                    Some(Either::Left(c))
                } else if let ty @ Type::Struct { .. } | ty @ Type::Enumeration(_) =
                    type_registry.lookup(internal_name)
                {
                    Some(Either::Right(ty))
                } else if type_registry.lookup_element(internal_name).is_ok()
                    || type_registry.lookup(internal_name) != Type::Invalid
                {
                    diag.push_error(
                        format!("Cannot export '{internal_name}' because it is not a component",),
                        internal_name_node,
                    );
                    None
                } else {
                    diag.push_error(format!("'{internal_name}' not found",), internal_name_node);
                    None
                }
            };

        // Collect all exports from the three sources, then sort once (O(n log n))
        // instead of insertion sort (O(n²))
        let mut exports_with_duplicates: Vec<(ExportedName, Either<Rc<Component>, Type>)> =
            Vec::new();

        // Source 1: ExportSpecifiers
        exports_with_duplicates.extend(
            doc.ExportsList()
                // re-export are handled in the TypeLoader::load_dependencies_recursively_impl
                .filter(|exports| exports.ExportModule().is_none())
                .flat_map(|exports| exports.ExportSpecifier())
                .filter_map(|export_specifier| {
                    let (internal_name, exported_name) =
                        ExportedName::from_export_specifier(&export_specifier);
                    Some((
                        exported_name,
                        resolve_export_to_inner_component_or_import(
                            &internal_name,
                            &export_specifier.ExportIdentifier(),
                            diag,
                        )?,
                    ))
                }),
        );

        // Source 2: Exported components
        exports_with_duplicates.extend(
            doc.ExportsList().flat_map(|exports| exports.Component()).filter_map(|component| {
                let name_ident: SyntaxNode = component.DeclaredIdentifier().into();
                let name =
                    parser::identifier_text(&component.DeclaredIdentifier()).unwrap_or_else(|| {
                        debug_assert!(diag.has_errors());
                        SmolStr::default()
                    });

                let compo_or_type =
                    resolve_export_to_inner_component_or_import(&name, &name_ident, diag)?;

                Some((ExportedName { name, name_ident }, compo_or_type))
            }),
        );

        // Source 3: Exported structs and enums
        exports_with_duplicates.extend(
            doc.ExportsList()
                .flat_map(|exports| {
                    exports
                        .StructDeclaration()
                        .map(|st| st.DeclaredIdentifier())
                        .chain(exports.EnumDeclaration().map(|en| en.DeclaredIdentifier()))
                })
                .filter_map(|name_ident| {
                    let name = parser::identifier_text(&name_ident).unwrap_or_else(|| {
                        debug_assert!(diag.has_errors());
                        SmolStr::default()
                    });

                    let name_ident = name_ident.into();

                    let compo_or_type =
                        resolve_export_to_inner_component_or_import(&name, &name_ident, diag)?;

                    Some((ExportedName { name, name_ident }, compo_or_type))
                }),
        );

        exports_with_duplicates.sort_by(|(a, _), (b, _)| a.name.cmp(&b.name));

        let mut sorted_deduped_exports = Vec::with_capacity(exports_with_duplicates.len());
        let mut it = exports_with_duplicates.into_iter().peekable();
        while let Some((exported_name, compo_or_type)) = it.next() {
            let mut warning_issued_on_first_occurrence = false;

            // Skip over duplicates and issue warnings
            while it.peek().map(|(name, _)| &name.name) == Some(&exported_name.name) {
                let message = format!("Duplicated export '{}'", exported_name.name);

                if !warning_issued_on_first_occurrence {
                    diag.push_error(message.clone(), &exported_name.name_ident);
                    warning_issued_on_first_occurrence = true;
                }

                let duplicate_loc = it.next().unwrap().0.name_ident;
                diag.push_error(message.clone(), &duplicate_loc);
            }

            sorted_deduped_exports.push((exported_name, compo_or_type));
        }

        if let Some(last_compo) = inner_components.last() {
            let name = last_compo.id.clone();
            if last_compo.is_global() {
                if sorted_deduped_exports.is_empty() {
                    diag.push_warning("Global singleton is implicitly marked for export. This is deprecated and it should be explicitly exported".into(), &last_compo.node.as_ref().map(|n| n.to_source_location()));
                    sorted_deduped_exports.push((
                        ExportedName { name, name_ident: doc.clone().into() },
                        Either::Left(last_compo.clone()),
                    ))
                }
            } else if !sorted_deduped_exports
                .iter()
                .any(|e| e.1.as_ref().left().is_some_and(|c| !c.is_global()))
            {
                diag.push_warning("Component is implicitly marked for export. This is deprecated and it should be explicitly exported".into(), &last_compo.node.as_ref().map(|n| n.to_source_location()));
                let insert_pos = sorted_deduped_exports
                    .partition_point(|(existing_export, _)| existing_export.name <= name);
                sorted_deduped_exports.insert(
                    insert_pos,
                    (
                        ExportedName { name, name_ident: doc.clone().into() },
                        Either::Left(last_compo.clone()),
                    ),
                )
            }
        }
        Self { components_or_types: sorted_deduped_exports }
    }

    pub fn add_reexports(
        &mut self,
        other_exports: impl IntoIterator<Item = (ExportedName, Either<Rc<Component>, Type>)>,
        diag: &mut BuildDiagnostics,
    ) {
        for export in other_exports {
            match self.components_or_types.binary_search_by(|entry| entry.0.cmp(&export.0)) {
                Ok(_) => {
                    diag.push_warning(
                        format!(
                            "'{}' is already exported in this file; it will not be re-exported",
                            *export.0
                        ),
                        &export.0.name_ident,
                    );
                }
                Err(insert_pos) => {
                    self.components_or_types.insert(insert_pos, export);
                }
            }
        }
    }

    pub fn find(&self, name: &str) -> Option<Either<Rc<Component>, Type>> {
        self.components_or_types
            .binary_search_by(|(exported_name, _)| exported_name.as_str().cmp(name))
            .ok()
            .map(|index| self.components_or_types[index].1.clone())
    }

    /// The `(original, alias)` pairs for renamed `export { Original as Alias }`
    /// of components (non-global), structs and enums — the aliases the
    /// generators attach to the generated type. Global aliases are handled
    /// separately, through `GlobalComponent::aliases`.
    pub fn named_type_aliases(&self) -> Vec<(SmolStr, SmolStr)> {
        self.iter()
            .filter_map(|(exported, item)| match item {
                Either::Left(component) if !component.is_global() => {
                    Some((component.id.clone(), exported.name.clone()))
                }
                Either::Right(ty) => match ty {
                    Type::Struct(s) if s.node().is_some() => match &s.name {
                        StructName::User { name, .. } => {
                            Some((name.clone(), exported.name.clone()))
                        }
                        _ => None,
                    },
                    Type::Enumeration(en) => Some((en.name.clone(), exported.name.clone())),
                    _ => None,
                },
                _ => None,
            })
            .filter(|(original, alias)| original != alias)
            .collect()
    }

    pub fn retain(
        &mut self,
        func: impl FnMut(&mut (ExportedName, Either<Rc<Component>, Type>)) -> bool,
    ) {
        self.components_or_types.retain_mut(func)
    }

    pub(crate) fn snapshot(&self, snapshotter: &mut crate::typeloader::Snapshotter) -> Self {
        let components_or_types = self
            .components_or_types
            .iter()
            .map(|(en, either)| {
                let en = en.clone();
                let either = match either {
                    itertools::Either::Left(l) => itertools::Either::Left({
                        Weak::upgrade(&snapshotter.use_component(l))
                            .expect("Component should cleanly upgrade here")
                    }),
                    itertools::Either::Right(r) => itertools::Either::Right(r.clone()),
                };
                (en, either)
            })
            .collect();

        Self { components_or_types }
    }
}

impl std::iter::IntoIterator for Exports {
    type Item = (ExportedName, Either<Rc<Component>, Type>);

    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.components_or_types.into_iter()
    }
}

/// Re-declare constrained layout info on an injected wrapper.
///
/// Forward an existing function when the child has one. A builtin root may depend
/// on width without a synthetic function, so rebuild its implicit vertical info
/// with the wrapper's width parameter.
fn forward_layout_info_with_constraint(new_root: &ElementRc, old_root: &ElementRc) {
    let width = Expression::FunctionParameterReference { index: 0, ty: Type::LogicalLength };
    let body = if let Some(nr) = old_root.borrow().inherited_layout_info_v_with_constraint() {
        Some(Expression::FunctionCall {
            function: Callable::Function(NamedReference::new(old_root, nr.name().clone())),
            arguments: vec![width],
            source_location: None,
        })
    } else if old_root.borrow().is_builtin_height_for_width() {
        crate::layout::implicit_layout_info_call(
            old_root,
            Orientation::Vertical,
            crate::layout::BuiltinFilter::All,
            Some(width),
        )
    } else {
        None
    };
    if let Some(body) = body {
        crate::passes::lower_layout::synthesize_layoutinfo_v_with_constraint_on(
            new_root,
            old_root.borrow().to_source_location(),
            body,
        );
    }
}

/// This function replace the root element of a repeated element. the previous root becomes the only
/// child of the new root element.
/// Note that no reference to the base component must exist outside of repeated_element.base_type
pub fn inject_element_as_repeated_element(repeated_element: &ElementRc, new_root: ElementRc) {
    let component = repeated_element.borrow().base_type.as_component().clone();
    // Since we're going to replace the repeated element's component, we need to assert that
    // outside this function no strong reference exists to it. Then we can unwrap and
    // replace the root element.
    debug_assert_eq!(Rc::strong_count(&component), 2);
    let old_root = &component.root_element;

    adjust_geometry_for_injected_parent(&new_root, old_root);

    // Any elements with a weak reference to the repeater's component will need fixing later.
    let mut elements_with_enclosing_component_reference = Vec::new();
    recurse_elem(old_root, &(), &mut |element: &ElementRc, _| {
        if let Some(enclosing_component) = element.borrow().enclosing_component.upgrade()
            && Rc::ptr_eq(&enclosing_component, &component)
        {
            elements_with_enclosing_component_reference.push(element.clone());
        }
    });
    elements_with_enclosing_component_reference
        .extend_from_slice(component.optimized_elements.borrow().as_slice());
    elements_with_enclosing_component_reference.push(new_root.clone());

    new_root.borrow_mut().child_of_layout =
        std::mem::replace(&mut old_root.borrow_mut().child_of_layout, false);
    // The injected parent becomes the repeated element, so it takes over the grid cell role.
    new_root.borrow_mut().grid_layout_cell = old_root.borrow_mut().grid_layout_cell.take();
    // Likewise it takes over the flexbox cell role, so the flex item-info accessor is
    // generated on the wrapper the layout actually calls it on.
    if old_root.borrow().child_of_flexbox {
        new_root.borrow_mut().child_of_flexbox = true;
    }
    new_root.borrow_mut().parent_box_layout_orientation =
        old_root.borrow().parent_box_layout_orientation;
    // The item-info accessors read the per-item layout properties from the repeated
    // root (now the wrapper). Link them to the inner element that still carries the
    // bindings (and the layout's captured references keeping them alive), rather
    // than moving them, which would leave those references dangling.
    for prop in ["layout-order", "cross-axis-self-alignment"].iter() {
        if old_root.borrow().binding(prop).is_some() {
            new_root.borrow_mut().set_binding(
                SmolStr::new_static(prop),
                BindingExpression::new_two_way(
                    NamedReference::new(old_root, SmolStr::new_static(prop)).into(),
                ),
            );
        }
    }
    // Resolved through the accessor: the wrapper has no height binding of its
    // own, so it must inherit the choice the wrapped flex made.
    let layout_info_prop = {
        let old = old_root.borrow();
        old.effective_layout_info_prop(Orientation::Horizontal)
            .cloned()
            .zip(old.effective_layout_info_prop(Orientation::Vertical).cloned())
    }
    .or_else(|| {
        // generate the layout_info_prop that forward to the implicit layout for that item
        let li_v = crate::layout::create_new_prop(
            &new_root,
            SmolStr::new_static("layoutinfo-v"),
            crate::typeregister::layout_info_type().into(),
        );
        let li_h = crate::layout::create_new_prop(
            &new_root,
            SmolStr::new_static("layoutinfo-h"),
            crate::typeregister::layout_info_type().into(),
        );
        let expr_h = crate::layout::implicit_layout_info_call(
            old_root,
            Orientation::Horizontal,
            crate::layout::BuiltinFilter::All,
            None,
        )
        .unwrap();
        let expr_v = crate::layout::implicit_layout_info_call(
            old_root,
            Orientation::Vertical,
            crate::layout::BuiltinFilter::All,
            None,
        )
        .unwrap();
        let expr_v =
            BindingExpression::new_with_span(expr_v, old_root.borrow().to_source_location());
        li_v.element().borrow_mut().set_binding(li_v.name().clone(), expr_v);
        let expr_h =
            BindingExpression::new_with_span(expr_h, old_root.borrow().to_source_location());
        li_h.element().borrow_mut().set_binding(li_h.name().clone(), expr_h);
        Some((li_h.clone(), li_v.clone()))
    });
    new_root.borrow_mut().layout_info_prop = layout_info_prop;
    forward_layout_info_with_constraint(&new_root, old_root);

    // Replace the repeated component's element with our shadow element. That requires a bit of reference counting
    // surgery and relies on nobody having a strong reference left to the component, which we take out of the Rc.
    drop(std::mem::take(&mut repeated_element.borrow_mut().base_type));

    debug_assert_eq!(Rc::strong_count(&component), 1);

    let mut component = Rc::try_unwrap(component).expect("internal compiler error: more than one strong reference left to repeated component when lowering shadow properties");

    let old_root = std::mem::replace(&mut component.root_element, new_root.clone());
    new_root.borrow_mut().children.push(old_root);

    let component = Rc::new(component);
    repeated_element.borrow_mut().base_type = ElementType::Component(component.clone());

    for elem in elements_with_enclosing_component_reference {
        elem.borrow_mut().enclosing_component = Rc::downgrade(&component);
    }
}

/// Make the geometry of the `injected_parent` that of the old_elem. And the old_elem
/// will cover the `injected_parent`
pub fn adjust_geometry_for_injected_parent(injected_parent: &ElementRc, old_elem: &ElementRc) {
    let mut injected_parent_mut = injected_parent.borrow_mut();
    injected_parent_mut.set_binding(
        "z".into(),
        BindingExpression::new_two_way(
            NamedReference::new(old_elem, SmolStr::new_static("z")).into(),
        ),
    );
    // (should be removed by const propagation in the llr)
    injected_parent_mut.property_declarations.insert(
        "dummy".into(),
        PropertyDeclaration { property_type: Type::LogicalLength, ..Default::default() },
    );
    let mut old_elem_mut = old_elem.borrow_mut();
    injected_parent_mut.default_fill_parent = std::mem::take(&mut old_elem_mut.default_fill_parent);
    injected_parent_mut.geometry_props.clone_from(&old_elem_mut.geometry_props);
    // The injected element takes the old element's place among the z-sorted siblings
    injected_parent_mut.z_order = old_elem_mut.z_order.take();
    drop(injected_parent_mut);
    old_elem_mut.geometry_props.as_mut().unwrap().x =
        NamedReference::new(injected_parent, SmolStr::new_static("dummy"));
    old_elem_mut.geometry_props.as_mut().unwrap().y =
        NamedReference::new(injected_parent, SmolStr::new_static("dummy"));
}