mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-02 22:31:17 +00:00
Compare commits
974
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d68512302f | ||
|
|
79c0836f34 | ||
|
|
894bb14be2 | ||
|
|
a4d025e778 | ||
|
|
79c31a6a9f | ||
|
|
80e5bf2857 | ||
|
|
52276ad881 | ||
|
|
7f8a981d8a | ||
|
|
9d00fe9cca | ||
|
|
4e8d4f2d80 | ||
|
|
505e303d13 | ||
|
|
4434e3bd05 | ||
|
|
7960441bca | ||
|
|
a09cd4fa30 | ||
|
|
3547cd1593 | ||
|
|
e605ad4e69 | ||
|
|
4eb8e3e38d | ||
|
|
d176602488 | ||
|
|
14493aa259 | ||
|
|
d4ef6064a4 | ||
|
|
60c72b77a6 | ||
|
|
226a5d3d26 | ||
|
|
585970c542 | ||
|
|
9ed28ba9ea | ||
|
|
4d94d3e27c | ||
|
|
9a1e05f442 | ||
|
|
be7732912b | ||
|
|
c869fdb23c | ||
|
|
d0661f8505 | ||
|
|
be07bd69fd | ||
|
|
5f22c7c01c | ||
|
|
838c9104c0 | ||
|
|
ade107ab73 | ||
|
|
44b8fc5b52 | ||
|
|
331486148e | ||
|
|
28bd4b42d0 | ||
|
|
684d86b78d | ||
|
|
5b43c2abc8 | ||
|
|
01c94182f5 | ||
|
|
0ff6f02485 | ||
|
|
f2934fd009 | ||
|
|
ba597305a1 | ||
|
|
0e57a9d37d | ||
|
|
b15dde1795 | ||
|
|
b742816737 | ||
|
|
2b71cf261f | ||
|
|
500f380504 | ||
|
|
a608301540 | ||
|
|
97f2754c1d | ||
|
|
6357908c69 | ||
|
|
3bed16aea8 | ||
|
|
dd6a17d239 | ||
|
|
296a4bf9a6 | ||
|
|
8cc5022abb | ||
|
|
4d5c8f2a4d | ||
|
|
1af87a37c5 | ||
|
|
401041f00c | ||
|
|
959497cad6 | ||
|
|
c10f94fcd3 | ||
|
|
5c4fcc65bd | ||
|
|
86a0c41e8f | ||
|
|
c159362b95 | ||
|
|
93d8e97d16 | ||
|
|
55d6879a94 | ||
|
|
791beee9f4 | ||
|
|
f45c122e79 | ||
|
|
3c9fc0d7c2 | ||
|
|
6868b7eb7b | ||
|
|
39dacab93a | ||
|
|
5aa0bd29e2 | ||
|
|
94cb40be98 | ||
|
|
ed881a564f | ||
|
|
33e37398fd | ||
|
|
d88f56be7b | ||
|
|
269eb10bed | ||
|
|
90ec7db3b5 | ||
|
|
7807aaed67 | ||
|
|
565b4ea705 | ||
|
|
364e967e69 | ||
|
|
b55ea8acd3 | ||
|
|
6fba6d3688 | ||
|
|
16c9ef0b76 | ||
|
|
989a267cb0 | ||
|
|
996c7ba467 | ||
|
|
9e8fdbc2df | ||
|
|
088f9193a8 | ||
|
|
2f7ac98c44 | ||
|
|
89bf004226 | ||
|
|
59f6b6c14a | ||
|
|
604cdf03f0 | ||
|
|
279c530efd | ||
|
|
abee6d6926 | ||
|
|
79285118ca | ||
|
|
072493baec | ||
|
|
707091be3f | ||
|
|
3852c2335a | ||
|
|
5bc7f92680 | ||
|
|
04720627bd | ||
|
|
91f9b87070 | ||
|
|
396c794844 | ||
|
|
93e42af30d | ||
|
|
cf9a1aba48 | ||
|
|
b5386047d9 | ||
|
|
b8cd3891fb | ||
|
|
2469308bf6 | ||
|
|
c5e735410a | ||
|
|
728f639332 | ||
|
|
6f57f7f4ae | ||
|
|
6ec2bab62b | ||
|
|
eb73335d12 | ||
|
|
4b35af1609 | ||
|
|
2fbd3585af | ||
|
|
e3f897ce7e | ||
|
|
2514c099b1 | ||
|
|
34da5683a6 | ||
|
|
24a0ce5a67 | ||
|
|
a5039ec907 | ||
|
|
a09a6ac3c8 | ||
|
|
f70dcc0e2e | ||
|
|
c08f843218 | ||
|
|
a99895c037 | ||
|
|
41b8ec1218 | ||
|
|
5fbc21b2b3 | ||
|
|
f53f8ede73 | ||
|
|
55a9a23d04 | ||
|
|
dbc919b3f7 | ||
|
|
916371a2b1 | ||
|
|
e59e03cd9e | ||
|
|
eda1871f36 | ||
|
|
74b93f3766 | ||
|
|
1dbd8db607 | ||
|
|
501fca9eb5 | ||
|
|
23d0784b11 | ||
|
|
6842aee683 | ||
|
|
22b85c371f | ||
|
|
271ece082d | ||
|
|
cc92d8a941 | ||
|
|
c9b822b858 | ||
|
|
ceaa6c129f | ||
|
|
7c5fec1a69 | ||
|
|
d5ebe99cd7 | ||
|
|
3dd804da3f | ||
|
|
dc5db3ccde | ||
|
|
8efbabf8e9 | ||
|
|
f27f874e3c | ||
|
|
b6dd901fe6 | ||
|
|
a2ac77711d | ||
|
|
d731fef146 | ||
|
|
77a569cf91 | ||
|
|
85d6d048d9 | ||
|
|
c2ddc94c0d | ||
|
|
17e94d26d2 | ||
|
|
5c89c4adc2 | ||
|
|
62c4cb3cb7 | ||
|
|
4744b591d1 | ||
|
|
0887efd788 | ||
|
|
2983959016 | ||
|
|
203b41a0c2 | ||
|
|
40dbdd23c6 | ||
|
|
bd050fc833 | ||
|
|
dbe301d9bb | ||
|
|
b22fa1d193 | ||
|
|
35ea16aa63 | ||
|
|
23fe90cd42 | ||
|
|
545ed706a9 | ||
|
|
abda1fe767 | ||
|
|
508caac2d1 | ||
|
|
313f50a96b | ||
|
|
ac5bfaf3a6 | ||
|
|
b38b2f8900 | ||
|
|
3ac1f3746f | ||
|
|
8c911f0f25 | ||
|
|
0d32f7a504 | ||
|
|
aa2d0d1f17 | ||
|
|
09d25ecaf6 | ||
|
|
2c28d0fc7e | ||
|
|
62aacb3e7e | ||
|
|
9120829df1 | ||
|
|
21df25dbed | ||
|
|
167f25f405 | ||
|
|
8192019564 | ||
|
|
bfe8dd24f9 | ||
|
|
ab445c1f7b | ||
|
|
3352b90f1e | ||
|
|
e1b87cab01 | ||
|
|
86a539e22b | ||
|
|
b5766097e8 | ||
|
|
404c71b9c3 | ||
|
|
8cee925a0b | ||
|
|
c1bc906ee7 | ||
|
|
bc43e71e5b | ||
|
|
7cff2527df | ||
|
|
b6ef428a89 | ||
|
|
8f0ac5ad69 | ||
|
|
03fcfaa33b | ||
|
|
4884d635a7 | ||
|
|
ed4230f8b9 | ||
|
|
4a0d24013f | ||
|
|
4ef9f58ecc | ||
|
|
a79a50120c | ||
|
|
8de700ad93 | ||
|
|
cbefffe721 | ||
|
|
2bb8f32254 | ||
|
|
fa6c397a44 | ||
|
|
def333fe42 | ||
|
|
d57bbabe76 | ||
|
|
c3ff583280 | ||
|
|
4318d0e82e | ||
|
|
1c9a8ae835 | ||
|
|
47a382c3e0 | ||
|
|
3e888103c1 | ||
|
|
0f36a7aee3 | ||
|
|
1eff34e69d | ||
|
|
2d97c9c629 | ||
|
|
01be559f9d | ||
|
|
062c34b69a | ||
|
|
2798b67d09 | ||
|
|
7360e8c50b | ||
|
|
4870243e3f | ||
|
|
5f9b38946b | ||
|
|
014e0583b7 | ||
|
|
8105980843 | ||
|
|
0a785c7f12 | ||
|
|
60e424ee52 | ||
|
|
b876c97212 | ||
|
|
4e8562a9a4 | ||
|
|
66610a7a16 | ||
|
|
628b2c99f3 | ||
|
|
e716c268ee | ||
|
|
d4b8aae4d4 | ||
|
|
1e6c3f2a61 | ||
|
|
168370bc2a | ||
|
|
9934dfd0b3 | ||
|
|
37c5dbf021 | ||
|
|
00bed75921 | ||
|
|
1b95f93b30 | ||
|
|
6d12ac6720 | ||
|
|
7538c56868 | ||
|
|
bd943295a8 | ||
|
|
4097668066 | ||
|
|
a53b23d470 | ||
|
|
8466440421 | ||
|
|
42abed0978 | ||
|
|
531989a2e5 | ||
|
|
fe30de8f7f | ||
|
|
55222b8814 | ||
|
|
3f8d3930bf | ||
|
|
fde057f8c2 | ||
|
|
45181a217f | ||
|
|
86a7d5e0c0 | ||
|
|
4d0333367b | ||
|
|
7436c503a9 | ||
|
|
5149a85932 | ||
|
|
c068f77254 | ||
|
|
45ac58cf03 | ||
|
|
aab0a9c385 | ||
|
|
ccbf56c05c | ||
|
|
a5709e22e0 | ||
|
|
8fc8aa7857 | ||
|
|
aab64fdebc | ||
|
|
5fb3b44f69 | ||
|
|
9c7fc39563 | ||
|
|
6144228f45 | ||
|
|
de4e878aa8 | ||
|
|
dddc649a78 | ||
|
|
b1216a17e8 | ||
|
|
15373a0fe7 | ||
|
|
3a37c2e882 | ||
|
|
f96096f97e | ||
|
|
731c90dcc1 | ||
|
|
8bbc760f5d | ||
|
|
cfc0922126 | ||
|
|
966c634b1c | ||
|
|
e9449b55ab | ||
|
|
7f2ae3cff8 | ||
|
|
5682daedc1 | ||
|
|
3e43b2bce2 | ||
|
|
643b52cb29 | ||
|
|
c41535a75c | ||
|
|
4f7a511b9f | ||
|
|
1175b54e65 | ||
|
|
acba6346ca | ||
|
|
c2c9e2bc52 | ||
|
|
73a2fd7148 | ||
|
|
33bb59307b | ||
|
|
5c54cce8dc | ||
|
|
2f585b0edd | ||
|
|
30fff82145 | ||
|
|
786f88c0f6 | ||
|
|
b467062692 | ||
|
|
2c4652d3d8 | ||
|
|
cf877fb11a | ||
|
|
c09881beaa | ||
|
|
5e2bca0ae7 | ||
|
|
d23654cdf0 | ||
|
|
dd86b43150 | ||
|
|
f9b39debd2 | ||
|
|
637e7809f0 | ||
|
|
7486d1021b | ||
|
|
35ca6435a8 | ||
|
|
8d6e207f04 | ||
|
|
0d23a0b12c | ||
|
|
d4c97a3329 | ||
|
|
e16b5fa179 | ||
|
|
7d0f153f9d | ||
|
|
d5c8c079cb | ||
|
|
30013b349c | ||
|
|
a1b96711b6 | ||
|
|
2f4b702530 | ||
|
|
fdb96edf1f | ||
|
|
b8dcf17039 | ||
|
|
ed6ab029e8 | ||
|
|
086a464792 | ||
|
|
d8e5faee9b | ||
|
|
9d9c9cdf83 | ||
|
|
c00fb9b67e | ||
|
|
e86b2ef0ef | ||
|
|
1e087adf28 | ||
|
|
50a6ea444a | ||
|
|
7bd4c2d17b | ||
|
|
51ab33dbe3 | ||
|
|
dec0e1a6c0 | ||
|
|
c2a0cae3fe | ||
|
|
7f57431b57 | ||
|
|
06c16b3c8d | ||
|
|
169f5660c3 | ||
|
|
9e40767a60 | ||
|
|
a730bbe78a | ||
|
|
bdf7d657a4 | ||
|
|
3f3199fcbb | ||
|
|
427cfad27e | ||
|
|
3c22a5fd7a | ||
|
|
5236d8e4ba | ||
|
|
5b59dbf73f | ||
|
|
9e1abd22a2 | ||
|
|
0a642f86eb | ||
|
|
7e05f4e57e | ||
|
|
0329de4388 | ||
|
|
1da7c3ae92 | ||
|
|
cff2302172 | ||
|
|
0ed3425179 | ||
|
|
81daff425b | ||
|
|
1cf5054de4 | ||
|
|
ad45897ec5 | ||
|
|
93bb7443b2 | ||
|
|
cb08a89917 | ||
|
|
595a2ee0a8 | ||
|
|
f5737157a0 | ||
|
|
53fafbf5d5 | ||
|
|
f06ecfaceb | ||
|
|
0980f3aa2f | ||
|
|
c77d94f07d | ||
|
|
bc320680e1 | ||
|
|
06247bf36c | ||
|
|
f8892ee1c1 | ||
|
|
a87983891f | ||
|
|
f7fd68e709 | ||
|
|
7cf59c0a5a | ||
|
|
93378f27bb | ||
|
|
b189d8f7df | ||
|
|
f187179552 | ||
|
|
b92f45b004 | ||
|
|
46a8525585 | ||
|
|
ce12e9f7f8 | ||
|
|
b75b155848 | ||
|
|
0a6e534676 | ||
|
|
0f2c32d1a8 | ||
|
|
d89a3afd22 | ||
|
|
36a932c933 | ||
|
|
5e75ffe429 | ||
|
|
67bea056d5 | ||
|
|
e6f5de7e42 | ||
|
|
14bc675778 | ||
|
|
e59c6dfda2 | ||
|
|
ef124ce4a9 | ||
|
|
e4d0388944 | ||
|
|
384e6189e7 | ||
|
|
80897d8bd4 | ||
|
|
7299661159 | ||
|
|
dea77f4811 | ||
|
|
187f88aa1c | ||
|
|
6429399f20 | ||
|
|
69a36a3b37 | ||
|
|
33eaca4524 | ||
|
|
fe730ad3fc | ||
|
|
e435c58930 | ||
|
|
710ece507c | ||
|
|
43bf785515 | ||
|
|
d977856457 | ||
|
|
a05d381c5c | ||
|
|
e7177f4948 | ||
|
|
c395f2d60b | ||
|
|
fc4701104c | ||
|
|
2537e5ff0a | ||
|
|
ba59c101c4 | ||
|
|
3d38b86232 | ||
|
|
4091ad6fe7 | ||
|
|
5f73d9787c | ||
|
|
7d571db2d0 | ||
|
|
7c3b4e288a | ||
|
|
dd1ba0e33d | ||
|
|
4d5ff9dc6a | ||
|
|
3f6de52269 | ||
|
|
a7ae5a8668 | ||
|
|
111fc70b75 | ||
|
|
cf6e4a57a8 | ||
|
|
7853f14449 | ||
|
|
f678a3f99c | ||
|
|
3316bac277 | ||
|
|
fe07dbc654 | ||
|
|
8b9f9527f1 | ||
|
|
7769efdbb9 | ||
|
|
c46a90c8c8 | ||
|
|
2ae710e65b | ||
|
|
f32fefddcf | ||
|
|
35996c6e2e | ||
|
|
d56e3638fd | ||
|
|
f17f730887 | ||
|
|
a4aee78391 | ||
|
|
815627264f | ||
|
|
b98a7c43de | ||
|
|
ad7ec8d775 | ||
|
|
28086016fe | ||
|
|
8aa01a7750 | ||
|
|
512bf992f5 | ||
|
|
322cc7e93a | ||
|
|
045f938332 | ||
|
|
61a3a47940 | ||
|
|
7cd04cd023 | ||
|
|
810b95bf68 | ||
|
|
8cb34cd312 | ||
|
|
a85ee924d6 | ||
|
|
0d868b83df | ||
|
|
05b883379a | ||
|
|
ba6385b388 | ||
|
|
989782f1a0 | ||
|
|
292a0e1e8e | ||
|
|
60ec576e0c | ||
|
|
c0feebc9b4 | ||
|
|
cb42d58c54 | ||
|
|
04c30b4901 | ||
|
|
349fb760b1 | ||
|
|
7e8ffc7474 | ||
|
|
21306e150f | ||
|
|
82397d57ac | ||
|
|
cd4ea7b481 | ||
|
|
ff4d018290 | ||
|
|
edc9afad59 | ||
|
|
c4d0aa8773 | ||
|
|
c50fa8d3e1 | ||
|
|
6d02203e8f | ||
|
|
7ee5c5ef36 | ||
|
|
d70646adfc | ||
|
|
46dc11dc9f | ||
|
|
e2174a9595 | ||
|
|
50e660c119 | ||
|
|
94fbd67d78 | ||
|
|
cea63e0611 | ||
|
|
ca5796662f | ||
|
|
ba605b4f69 | ||
|
|
bb91ea0410 | ||
|
|
f21dc313db | ||
|
|
fd664055df | ||
|
|
72778aba99 | ||
|
|
2a506bfc85 | ||
|
|
09d52cc7cd | ||
|
|
313fdef652 | ||
|
|
92b3ab1886 | ||
|
|
84e0a241b7 | ||
|
|
6315dacc9e | ||
|
|
0afc01aa1a | ||
|
|
57de9d5d6f | ||
|
|
f56753ddb7 | ||
|
|
19b8009d2a | ||
|
|
618ad0ba74 | ||
|
|
5f5dda7249 | ||
|
|
ed1f3964af | ||
|
|
ad380da0e9 | ||
|
|
094ce5ec8d | ||
|
|
1b128ffb24 | ||
|
|
1fb2dfd720 | ||
|
|
d5cdd4b335 | ||
|
|
23d2906408 | ||
|
|
d098a7dfc3 | ||
|
|
7984f0f2bd | ||
|
|
302019d815 | ||
|
|
2240950eb6 | ||
|
|
a7a319c5c7 | ||
|
|
30f24fd239 | ||
|
|
fe9162c9cf | ||
|
|
ee886d6db6 | ||
|
|
2829120d4d | ||
|
|
def4067247 | ||
|
|
51bc57b489 | ||
|
|
0622859f49 | ||
|
|
3b70b106ef | ||
|
|
c7e254c372 | ||
|
|
38e98cbe9b | ||
|
|
98d7238838 | ||
|
|
77c6bfb286 | ||
|
|
9fab68fd8f | ||
|
|
c8ef1b8b1b | ||
|
|
9291c39687 | ||
|
|
8b0949f8ae | ||
|
|
5f0e1d1347 | ||
|
|
62899818be | ||
|
|
f9921b99c8 | ||
|
|
f90c2c0fe2 | ||
|
|
de3d3073e0 | ||
|
|
f33a2eb90a | ||
|
|
7fc0147965 | ||
|
|
ccb757dff2 | ||
|
|
2464b4f6aa | ||
|
|
0ade51f7aa | ||
|
|
94bdc71889 | ||
|
|
8662072a92 | ||
|
|
1198e1ddf9 | ||
|
|
a8b9913c31 | ||
|
|
682d777b85 | ||
|
|
0f074e4702 | ||
|
|
6f965710c0 | ||
|
|
581b085e9b | ||
|
|
68389e865b | ||
|
|
c040089f8d | ||
|
|
10a2c02378 | ||
|
|
39ece863d8 | ||
|
|
5d578bef00 | ||
|
|
c3969a34c9 | ||
|
|
b3e25437cc | ||
|
|
88717cd5ac | ||
|
|
8fbd9ea4ab | ||
|
|
b4c8238594 | ||
|
|
c3c7ac378d | ||
|
|
1ec173a087 | ||
|
|
d16e311b8c | ||
|
|
707cbc0742 | ||
|
|
a8e8bd70c6 | ||
|
|
d24debac57 | ||
|
|
2af770def2 | ||
|
|
14916f64af | ||
|
|
f00e1da135 | ||
|
|
c37fa6a799 | ||
|
|
292f0a3447 | ||
|
|
5e1b519955 | ||
|
|
278f95e26a | ||
|
|
6dbb9e3c8e | ||
|
|
9e7497210b | ||
|
|
e96107dae5 | ||
|
|
934561c3ae | ||
|
|
3f5c55a052 | ||
|
|
d1cc151fc7 | ||
|
|
30bfcac0d1 | ||
|
|
21212be16a | ||
|
|
5a73c66a1f | ||
|
|
7332a12c17 | ||
|
|
eebfbf5d66 | ||
|
|
40350bad7a | ||
|
|
c24fe0d105 | ||
|
|
4e2fe3206e | ||
|
|
faab395ce4 | ||
|
|
5c9f1b757a | ||
|
|
3ca82dd1e6 | ||
|
|
4ff74072db | ||
|
|
a7abddee7d | ||
|
|
81a593dbcf | ||
|
|
a89acaa9a6 | ||
|
|
5c0e27c556 | ||
|
|
4f6500320d | ||
|
|
d049f1a595 | ||
|
|
f0de6913d1 | ||
|
|
1baac9125c | ||
|
|
c01eb6cd2a | ||
|
|
3131f30f5c | ||
|
|
b2cb4eb91f | ||
|
|
baff2e50cc | ||
|
|
335109beb5 | ||
|
|
4b65b85b23 | ||
|
|
155d254977 | ||
|
|
b006c956eb | ||
|
|
6fb9b5cc3d | ||
|
|
3fb6f4334e | ||
|
|
8ad676b85c | ||
|
|
078ef5f7cc | ||
|
|
b1a1eee435 | ||
|
|
7a19af93dd | ||
|
|
68d54cc1b6 | ||
|
|
5b6c4a0739 | ||
|
|
839c35635a | ||
|
|
a8e5fdcb75 | ||
|
|
61e3275c42 | ||
|
|
d2e97a485c | ||
|
|
1bfd0f0cf0 | ||
|
|
ed365d9502 | ||
|
|
73037efbc5 | ||
|
|
e5c66c0c56 | ||
|
|
6856c3cfdf | ||
|
|
25715e77c3 | ||
|
|
493ceae678 | ||
|
|
4ae322a973 | ||
|
|
f954ca72b2 | ||
|
|
b346a5fcce | ||
|
|
e1ae4d55ce | ||
|
|
2be4be9dd2 | ||
|
|
dd55a1f4ce | ||
|
|
d8be9537ac | ||
|
|
58f4a5d6f3 | ||
|
|
a4094cc173 | ||
|
|
7b758ef1c3 | ||
|
|
2de9f32d4b | ||
|
|
e27bb51c58 | ||
|
|
c69969fbfc | ||
|
|
475019d69c | ||
|
|
6376c5ddb2 | ||
|
|
a7b39a0ed3 | ||
|
|
379c6e2265 | ||
|
|
f81a8d84b2 | ||
|
|
5168a1c9c7 | ||
|
|
3f935e0461 | ||
|
|
1ac75eb858 | ||
|
|
5f4f5ce4c5 | ||
|
|
1e8541d050 | ||
|
|
5aac662668 | ||
|
|
d9d9e3c628 | ||
|
|
8516e5fd0d | ||
|
|
b4beded739 | ||
|
|
9c5b6b2dbe | ||
|
|
b815f11184 | ||
|
|
78f0b47b43 | ||
|
|
6e2bf00b14 | ||
|
|
eb94d99326 | ||
|
|
d2a608c750 | ||
|
|
25b01d9497 | ||
|
|
2f7e6bf878 | ||
|
|
a738b160db | ||
|
|
455d11bd5a | ||
|
|
be0b6232e8 | ||
|
|
9f5919dd87 | ||
|
|
b1ecd718af | ||
|
|
a1fc982132 | ||
|
|
8c0f60ec96 | ||
|
|
8e0d621a0f | ||
|
|
6d3c10bbf2 | ||
|
|
5f55b755fa | ||
|
|
1f3c7a3390 | ||
|
|
0ba908412c | ||
|
|
adbcd14233 | ||
|
|
145c253a60 | ||
|
|
a97d858b9e | ||
|
|
5f1e609a69 | ||
|
|
e69515aff1 | ||
|
|
6c447a8082 | ||
|
|
c9e5cdbf7d | ||
|
|
fb68684795 | ||
|
|
6b34b6c6a8 | ||
|
|
c122e5f893 | ||
|
|
80f29610ee | ||
|
|
4595d8dace | ||
|
|
9fbd95e037 | ||
|
|
0de56624d5 | ||
|
|
af4f17184c | ||
|
|
921cdc974f | ||
|
|
6aa6a9cee8 | ||
|
|
73999fcd89 | ||
|
|
bcac6859e3 | ||
|
|
4f7f73cd4b | ||
|
|
210b8c9cd6 | ||
|
|
1668d576a8 | ||
|
|
478e21a988 | ||
|
|
7eb044921b | ||
|
|
7047dca872 | ||
|
|
a5e03454a4 | ||
|
|
b3b0ceabae | ||
|
|
f3b88ae36b | ||
|
|
787b12069d | ||
|
|
1836cd83a1 | ||
|
|
ab6a4b4030 | ||
|
|
a5d6efab4d | ||
|
|
b5e831d461 | ||
|
|
17abd46b97 | ||
|
|
9187049f7f | ||
|
|
946b98c375 | ||
|
|
14fbd977b7 | ||
|
|
26b9dec45b | ||
|
|
53228adb7d | ||
|
|
743865a836 | ||
|
|
364e48dcab | ||
|
|
a0a2627894 | ||
|
|
47c5e3b816 | ||
|
|
9777459eb6 | ||
|
|
91e6a41a63 | ||
|
|
5378f80672 | ||
|
|
437b7f2df0 | ||
|
|
8893ead179 | ||
|
|
cd6fe4f8bd | ||
|
|
a276e2f21d | ||
|
|
496aa28ed3 | ||
|
|
2506ba3ddb | ||
|
|
15eef6b434 | ||
|
|
3b8daf900c | ||
|
|
2295cc71c6 | ||
|
|
2c976a6e6b | ||
|
|
4efd8fc0db | ||
|
|
40268a3c67 | ||
|
|
cc2229a08b | ||
|
|
2c6ba8a658 | ||
|
|
1396236440 | ||
|
|
6531650600 | ||
|
|
c998ff1ffb | ||
|
|
dac313337d | ||
|
|
2c4f471566 | ||
|
|
6a15912b06 | ||
|
|
96ae211258 | ||
|
|
04f8797ee4 | ||
|
|
9680794bc4 | ||
|
|
3adf662578 | ||
|
|
a6f9b80e43 | ||
|
|
4d0d3bdbfa | ||
|
|
4550a1eba7 | ||
|
|
8e81dade33 | ||
|
|
b4b89a4e36 | ||
|
|
6fe8a65c5c | ||
|
|
5846f59081 | ||
|
|
a2312fff8b | ||
|
|
92dcd308c2 | ||
|
|
2a8cc47a3f | ||
|
|
1ccc95d846 | ||
|
|
10bbee4047 | ||
|
|
b83f717a39 | ||
|
|
cc3858a394 | ||
|
|
cf17534e7b | ||
|
|
7e643e2930 | ||
|
|
dbacb4cc80 | ||
|
|
7b83509a93 | ||
|
|
f3c214b2dd | ||
|
|
a2e3f265c0 | ||
|
|
10115f41ed | ||
|
|
d57d5cf267 | ||
|
|
be8efa6d0b | ||
|
|
2cdffc6282 | ||
|
|
2e1a744c6c | ||
|
|
8ec8445b5a | ||
|
|
0b31398c0d | ||
|
|
fb19a4fb87 | ||
|
|
d479ff2f4b | ||
|
|
843e09fb77 | ||
|
|
f4e7a1e33f | ||
|
|
d853b05dbd | ||
|
|
73d36eef04 | ||
|
|
7a3f75d7c3 | ||
|
|
db21e558d1 | ||
|
|
8211e218ce | ||
|
|
2f744078ec | ||
|
|
ef732f04ce | ||
|
|
f300a41236 | ||
|
|
f4049f9e49 | ||
|
|
5c987d1eae | ||
|
|
4d0074e5cf | ||
|
|
efac07d32f | ||
|
|
af3b87e965 | ||
|
|
9dae419df2 | ||
|
|
f0397d5f5b | ||
|
|
e1a5244c0c | ||
|
|
19bc9660ff | ||
|
|
b7547111f3 | ||
|
|
a19b16f211 | ||
|
|
1fcaffe7b7 | ||
|
|
a7a708d0f6 | ||
|
|
7369738a28 | ||
|
|
01da1806d1 | ||
|
|
2fbe96820c | ||
|
|
abf93c2e23 | ||
|
|
9bbcb7ce90 | ||
|
|
7155ced916 | ||
|
|
571bdf68ad | ||
|
|
c4920c463b | ||
|
|
0ddd8684ef | ||
|
|
15661dc973 | ||
|
|
1053b66a0e | ||
|
|
b023410ca4 | ||
|
|
7a8b2261f8 | ||
|
|
dacff8ff97 | ||
|
|
c708afad34 | ||
|
|
4081acd660 | ||
|
|
712a17f1e6 | ||
|
|
077533edb8 | ||
|
|
8af1e4fd84 | ||
|
|
9319fb44b4 | ||
|
|
b56d13da75 | ||
|
|
260b84d093 | ||
|
|
9bd604aa12 | ||
|
|
cfcde5bfbd | ||
|
|
2f86b52706 | ||
|
|
e3fa42607f | ||
|
|
4b86dc9dc9 | ||
|
|
fbb33c42ee | ||
|
|
1fe4f79db6 | ||
|
|
55e73b2564 | ||
|
|
1e3fc9ee37 | ||
|
|
07600d3523 | ||
|
|
b4feff7be2 | ||
|
|
2051a15c30 | ||
|
|
e3f6c66a6a | ||
|
|
de8f36ee33 | ||
|
|
06c2b1440b | ||
|
|
f7380202fe | ||
|
|
4fa40fb932 | ||
|
|
a53483874e | ||
|
|
dd136062f5 | ||
|
|
6f63c784bc | ||
|
|
a98f290ec0 | ||
|
|
d5b23a5e79 | ||
|
|
870e2658ae | ||
|
|
18f11876e3 | ||
|
|
80b8786969 | ||
|
|
d0ad5ba6dc | ||
|
|
a5b1415c9e | ||
|
|
ce64da3286 | ||
|
|
87f9c4b12d | ||
|
|
ceca4b151e | ||
|
|
70fb318377 | ||
|
|
14c81bfdd6 | ||
|
|
5a035ac5c6 | ||
|
|
81a8abc12b | ||
|
|
8b17f1e779 | ||
|
|
6cfd7d83aa | ||
|
|
a327501fb1 | ||
|
|
516b19c151 | ||
|
|
fded60a325 | ||
|
|
c693db2b9f | ||
|
|
a2caeedcd9 | ||
|
|
2a10509d65 | ||
|
|
38fa0dc050 | ||
|
|
ae50127952 | ||
|
|
95c0800c22 | ||
|
|
707ce9e14c | ||
|
|
b97c27f2b3 | ||
|
|
2d65676f5d | ||
|
|
79324b6c17 | ||
|
|
d2506c03d9 | ||
|
|
214ad97372 | ||
|
|
46bdd416bb | ||
|
|
3d923f3b30 | ||
|
|
937634a31a | ||
|
|
d07795efae | ||
|
|
591b97aede | ||
|
|
c506178922 | ||
|
|
a6b73d11e9 | ||
|
|
5e0fe2d28d | ||
|
|
fb38290e45 | ||
|
|
b107dedf7e | ||
|
|
9b7c5ca1f6 | ||
|
|
ec77c810f8 | ||
|
|
8471ccace5 | ||
|
|
bf9531954d | ||
|
|
41a1a3f8bc | ||
|
|
10c023754e | ||
|
|
fa17a79cba | ||
|
|
154273a7d8 | ||
|
|
2a59d7f15d | ||
|
|
818c97a632 | ||
|
|
c4ef580a22 | ||
|
|
17aae2da04 | ||
|
|
aea9a02bce | ||
|
|
a4309846b2 | ||
|
|
fd6d6cee88 | ||
|
|
852b1a4bfb | ||
|
|
a6bedd5153 | ||
|
|
3aa8727fd6 | ||
|
|
1d0360153f | ||
|
|
df2b24dbfd | ||
|
|
8513c584cb | ||
|
|
db2fffa9be | ||
|
|
7e4f2c4a0d | ||
|
|
1da552fc9f | ||
|
|
42ad67ab13 | ||
|
|
b21dd9151f | ||
|
|
b9324d9179 | ||
|
|
edd64e9afc | ||
|
|
81e523e431 | ||
|
|
60c758af66 | ||
|
|
6ce1ce9c6d | ||
|
|
9b594efc67 | ||
|
|
db2ff17229 | ||
|
|
2681d7b6df | ||
|
|
f30c206a05 | ||
|
|
3d82a9cf4e | ||
|
|
5b8c2cde8d | ||
|
|
78cf72ae0f | ||
|
|
0a659997ee | ||
|
|
a6870d0e3f | ||
|
|
38696b93a4 | ||
|
|
744c6cde44 | ||
|
|
8338a35da6 | ||
|
|
4e85a1fd21 | ||
|
|
d51a6de104 | ||
|
|
9424a96d9b | ||
|
|
4f92fc417b | ||
|
|
f3a7c72bb6 | ||
|
|
b56c2ddc7e | ||
|
|
12c08d7e9d | ||
|
|
7bce227ed6 | ||
|
|
32b2bbe471 | ||
|
|
2b297cd194 | ||
|
|
727c727ff5 | ||
|
|
1f6adbe382 | ||
|
|
c29f282712 | ||
|
|
76433d99a6 | ||
|
|
c0ae95f721 | ||
|
|
601cc60cfc | ||
|
|
132bd4e9a8 | ||
|
|
fdad356fd2 | ||
|
|
a8810d7a7a | ||
|
|
0c78ddf79f | ||
|
|
1af4d38e71 | ||
|
|
4215f07bb3 | ||
|
|
9f127b5b80 | ||
|
|
480b8a88b5 | ||
|
|
b82c4fbd30 | ||
|
|
b2a2e74316 | ||
|
|
6421731f9a | ||
|
|
df97bf8445 | ||
|
|
b321e50197 | ||
|
|
c2362ccff5 | ||
|
|
826ba30f5e | ||
|
|
cdb3c163ec | ||
|
|
5a72aff0c5 | ||
|
|
43ccb39ba3 | ||
|
|
e24a8631b4 | ||
|
|
df34dac2d1 | ||
|
|
8d90b1ea03 | ||
|
|
921405fa02 | ||
|
|
f066fe994e | ||
|
|
8732325b58 | ||
|
|
ec3666f913 | ||
|
|
20a85b2caf | ||
|
|
7fe89ba872 | ||
|
|
1ba5d323d0 | ||
|
|
ef6776db8b | ||
|
|
766b6d3a93 | ||
|
|
0739f71fac | ||
|
|
b60d37e4e9 | ||
|
|
fadcec3683 | ||
|
|
e16b95eb82 | ||
|
|
df4599d2cd | ||
|
|
374ab0f127 | ||
|
|
add4ebf5d8 | ||
|
|
8fc6aa7082 | ||
|
|
ce8f5fca22 | ||
|
|
bf15f965ae | ||
|
|
cde1dbb2e4 | ||
|
|
c77b8ac3cb | ||
|
|
270995c299 | ||
|
|
6f8c4d09c7 | ||
|
|
1e865962dc | ||
|
|
9f224b6ca9 | ||
|
|
a5bcbe5c05 | ||
|
|
e07b5e39b0 | ||
|
|
7d3516ab33 | ||
|
|
a7e1a4a99b | ||
|
|
4972675b1b | ||
|
|
d38ebe3853 | ||
|
|
21672fea59 | ||
|
|
3bbd2afb0f | ||
|
|
871b025921 | ||
|
|
51a6d64c23 | ||
|
|
4629c063ab | ||
|
|
e765690c18 | ||
|
|
0d0e6d5e39 | ||
|
|
c39fcd884e | ||
|
|
8d495f9ce0 | ||
|
|
85ab340ccd | ||
|
|
27fc0e828f | ||
|
|
c0f4480504 | ||
|
|
669f9cc53d |
@@ -0,0 +1,16 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/gridcraft",
|
||||
"repository_id": 1408285582,
|
||||
"producer_workflow_id": 429713469,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
"echelon",
|
||||
"FredApps",
|
||||
"skylartaylor"
|
||||
],
|
||||
"max_age_seconds": 86400,
|
||||
"candidate_policy": {
|
||||
"schema": "craft-nightly-candidate-policy/v3",
|
||||
"epoch": "gridcraft-nightly-20261124",
|
||||
"repository": "storytold/gridcraft",
|
||||
"branch": "main",
|
||||
"required_workflows": [
|
||||
{
|
||||
"workflow_id": 380135773,
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "gate / gate (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sonar": {
|
||||
"organization": "storytold",
|
||||
"project": "storytold_gridcraft",
|
||||
"app_id": 12526,
|
||||
"check_name": "SonarCloud Code Analysis",
|
||||
"details_url": "https://sonarcloud.io/dashboard?id=storytold_gridcraft&branch=main",
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_maintainability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_coverage",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "80"
|
||||
},
|
||||
{
|
||||
"metric": "new_duplicated_lines_density",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "3"
|
||||
},
|
||||
{
|
||||
"metric": "new_security_hotspots_reviewed",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "100"
|
||||
}
|
||||
],
|
||||
"debt": []
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {
|
||||
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
|
||||
}
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,11 @@ workflows:
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
'.github/workflows/nightly-dispatch.yml': []
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/nix.yml': []
|
||||
'.github/workflows/notify-services.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [GridCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
if: >-
|
||||
github.repository == 'storytold/gridcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/gridcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/gridcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/gridcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/gridcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'gridcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -0,0 +1,59 @@
|
||||
name: GridCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
|
||||
# fast-forwards to reviewed main commits (never the stable release branch).
|
||||
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
producer_run_id:
|
||||
description: Exact untrusted producer Actions run ID
|
||||
required: true
|
||||
type: string
|
||||
producer_run_attempt:
|
||||
description: Exact untrusted producer Actions run attempt
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: gridcraft-nightly-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/gridcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: main
|
||||
app-name: gridcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
# Forward exactly the secrets the signer's sign steps read, named explicitly (never `inherit`),
|
||||
# as the stable Release caller does. The callee must declare them; it does since the shared
|
||||
# change that added them, and `uses:` is pinned to that revision.
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
@@ -0,0 +1,35 @@
|
||||
name: GridCraft unsigned nightly
|
||||
|
||||
# Automated daily nightly builds at 03:30 UTC (plus manual dispatch by reviewed manual actors).
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 3 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
unsigned:
|
||||
# Actual context guards only; no inherited/platform secrets.
|
||||
if: >-
|
||||
github.repository == 'storytold/gridcraft' &&
|
||||
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
|
||||
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
|
||||
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
|
||||
# no OIDC, attestation write, release environment or platform secrets in compilation.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: main
|
||||
app-name: gridcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged 8389cad8 (#375, the signer Windows fix).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -5,9 +5,9 @@ name: Packaging lint
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -22,6 +22,25 @@ jobs:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
|
||||
|
||||
nightly-source-contract:
|
||||
name: Nightly source contracts (no build or signing)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/[email protected]
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/[email protected]
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic nightly packaging suites
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Check the committed nightly icons still match their provenance
|
||||
run: python3 packaging/nightly-icons.py --check
|
||||
|
||||
windows-install-policy:
|
||||
timeout-minutes: 10
|
||||
name: Windows installation policy (no app build)
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
name: Workbook print range verification
|
||||
on:
|
||||
push:
|
||||
branches: [verify/gridcraft-print-range-4859]
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
CARGO_PROFILE_TEST_DEBUG: 0
|
||||
CARGO_PROFILE_DEV_DEBUG: 0
|
||||
CARGO_INCREMENTAL: 0
|
||||
jobs:
|
||||
shared:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
repository: storytold/craft-libs
|
||||
ref: 2ed780c05a40870fe0487b04d74aa0d4d89a18c8
|
||||
persist-credentials: false
|
||||
- run: |
|
||||
set -euo pipefail
|
||||
cargo test --locked -p craft-pages --lib | tee "$RUNNER_TEMP/shared.txt"
|
||||
grep -E 'print_page_spans_follow_whole_job_bounds.*ok' "$RUNNER_TEMP/shared.txt"
|
||||
workbook:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 115
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: 1
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
with:
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev
|
||||
libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev xvfb xauth
|
||||
- name: Resolve all framework dependencies at the verification revision
|
||||
run: |
|
||||
set -euo pipefail
|
||||
old=8fa4db64a9bb943520259ea95331a303ba788f21
|
||||
new=2ed780c05a40870fe0487b04d74aa0d4d89a18c8
|
||||
git grep -lz -F "$old" -- Cargo.toml Cargo.lock ':(glob)**/Cargo.toml' | xargs -0 sed -i "s/$old/$new/g"
|
||||
cargo metadata --format-version 1 > "$RUNNER_TEMP/graph.json"
|
||||
python3 - "$RUNNER_TEMP/graph.json" "$new" <<'PY'
|
||||
import json, sys
|
||||
packages = json.load(open(sys.argv[1]))["packages"]
|
||||
sources = {p["source"] for p in packages if "github.com/storytold/craft-libs" in (p["source"] or "")}
|
||||
assert len(sources) == 1 and sources.pop().endswith("#" + sys.argv[2])
|
||||
assert any(p["name"] == "craft-pages" for p in packages)
|
||||
PY
|
||||
- name: Workbook print and PDF output
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo test --locked -p gridcraft-engine --lib cmd::print::tests | tee "$RUNNER_TEMP/engine.txt"
|
||||
grep -E 'a_page_range_prints_its_pages_under_the_whole_jobs_numbers.*ok' "$RUNNER_TEMP/engine.txt"
|
||||
grep -E 'a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages.*ok' "$RUNNER_TEMP/engine.txt"
|
||||
- name: Native print window, range selection, submission and PDF export
|
||||
run: |
|
||||
set -euo pipefail
|
||||
xvfb-run -a cargo test --locked -p gridcraft-ui-egui --test it native_print:: -- --test-threads=1 | tee "$RUNNER_TEMP/ui.txt"
|
||||
grep -E 'each_window_keeps_its_own_page_range.*ok' "$RUNNER_TEMP/ui.txt"
|
||||
grep -E 'create_pdf_exports_the_page_range_under_it.*ok' "$RUNNER_TEMP/ui.txt"
|
||||
@@ -8,3 +8,9 @@ plan/
|
||||
/.claude/
|
||||
/target-*/
|
||||
/craft-fonts/
|
||||
|
||||
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
__pycache__/
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
# Accessibility
|
||||
|
||||
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
|
||||
|
||||
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
|
||||
|
||||
## Supported environments and how accessibility works
|
||||
|
||||
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
|
||||
|
||||
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
|
||||
- **macOS:** NSAccessibility (VoiceOver)
|
||||
- **Linux and FreeBSD:** AT-SPI (Orca)
|
||||
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
|
||||
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
|
||||
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
|
||||
|
||||
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
|
||||
|
||||
## Known limitations and workarounds
|
||||
|
||||
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
|
||||
|
||||
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
|
||||
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
|
||||
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
|
||||
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
|
||||
|
||||
See [This application](#this-application) below for repository-specific links and details.
|
||||
|
||||
## Reporting an accessibility barrier
|
||||
|
||||
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
|
||||
|
||||
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
|
||||
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
|
||||
- **Helpful details to share (when convenient):**
|
||||
- What you were trying to do, what happened, and what you expected
|
||||
- Application version (or commit) and operating system or browser
|
||||
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
|
||||
|
||||
## How we respond
|
||||
|
||||
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
|
||||
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
|
||||
|
||||
## Note for contributors and coding agents
|
||||
|
||||
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
|
||||
|
||||
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
|
||||
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
|
||||
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
|
||||
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
|
||||
|
||||
## Ownership
|
||||
|
||||
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
|
||||
|
||||
## This application
|
||||
|
||||
**GridCraft** (`storytold/gridcraft`) is an open-source spreadsheet application written in pure Rust.
|
||||
|
||||
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
|
||||
- **Command-line and automation interface:** `gridcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
|
||||
- **Report an accessibility barrier:** [Open an issue in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues/new)
|
||||
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
|
||||
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
|
||||
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
|
||||
@@ -81,4 +81,5 @@ Paths and conventions:
|
||||
- Test corpora live in a separate corpus repository, pinned and sha256-verified. Test workbooks are built in code.
|
||||
- Progress log: `ROADMAP.md`. `plan/` is an optional gitignored notebook.
|
||||
- Run with a control channel: `cargo run --release -p gridcraft -- --sample sales --control 7979`. Drive it with `gridcraft-cli send 7979 <method> '<json>'`; methods are in `crates/ui-egui/src/control.rs`, the protocol in `docs/control-protocol.md`. Offscreen render: `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli mcp`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog id `headless: yes` only when the engine registry (what `gridcraft-cli` and the MCP server load) has it. A missing id takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs`, or reads `unknown`. When a command lands, delete its mark; the check fails on a stale one.
|
||||
- Docs: `ROADMAP.md`, `docs/gaps.md` (ranked work), `docs/architecture.md`, `docs/target-app-parity.md`, `docs/roadmap.md`, `docs/contributors.md`.
|
||||
|
||||
@@ -13,6 +13,7 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
| `epaint_default_fonts::NOTO_EMOJI_REGULAR` (dependency font input) | The Noto Project Authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Noto Emoji](https://fonts.google.com/noto/specimen/Noto+Emoji) | SIL Open Font License 1.1 (full upstream text in `NOTICE`) | NotoEmoji-Regular.ttf is enabled by egui's `monochrome_emoji_fonts` feature and used as the monochrome emoji fallback. Dependency asset unmodified here, no font file copied into this repository. |
|
||||
| `epaint_default_fonts::UBUNTU_LIGHT` (dependency font input) | Canonical Ltd. and the Ubuntu Font Family authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Ubuntu font](https://design.ubuntu.com/font) | Ubuntu Font Licence 1.0 (full upstream text in `NOTICE`) | Ubuntu-Light.ttf is egui's default proportional face. Dependency asset unmodified here, no font file copied into this repository. |
|
||||
| Regional format data in `crates/core/src/region.rs` (data, no file of its own) | Unicode, Inc. (Unicode CLDR) | [cldr-json](https://github.com/unicode-org/cldr-json) (`cldr-numbers-full`, `cldr-dates-full`) and ICU's CLDR 48 data | Unicode License v3 (`Unicode-3.0`; full text in `NOTICE`) | Separators, month and weekday names, AM/PM words, currency symbols and date order of the built-in regions. No CLDR file is copied into this repository. |
|
||||
| Polish formula function names in `crates/formula/src/input/pl.rs` (data, no file of its own) | PhpSpreadsheet Authors | [PhpSpreadsheet `locale/pl/functions`](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Calculation/locale/pl/functions) | MIT (Copyright (c) 2019-2026 PhpSpreadsheet Authors; full upstream text in `NOTICE`) | The English-to-Polish function name table (`FUNCTIONS`). Names not in that table come from Microsoft's pl-pl support pages and #1678's Excel for the web observation. No PhpSpreadsheet file is copied into this repository. |
|
||||
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
|
||||
| `docs/brand/artcraft-logo.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
|
||||
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
|
||||
@@ -38,6 +39,12 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
|
||||
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
|
||||
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, copy of gridcraft.svg |
|
||||
| `assets/app-icon/gridcraft-nightly.svg` | GridCraft contributors | original (the stable placeholder artwork with only its field colour deepened; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly (nightly-v1) icon master |
|
||||
| `assets/app-icon/gridcraft-nightly.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, 256 px (Linux tar and runtime window icon) |
|
||||
| `assets/app-icon/gridcraft-nightly-1024.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg` on the 824/1024 Mac grid; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, padded Mac master |
|
||||
| `assets/app-icon/gridcraft-nightly.icns` | GridCraft contributors | original (PNG slots packed from `gridcraft-nightly.svg` renders; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS bundle icon |
|
||||
| `assets/app-icon/gridcraft-nightly.ico` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows exe icon |
|
||||
| `assets/app-icon/nightly-provenance.json` | GridCraft contributors | original (written by `packaging/nightly-icons.py`) | MIT OR Apache-2.0 | Hashes and method of the nightly icon derivatives |
|
||||
| `assets/app-icon/README.md` | GridCraft contributors | original | MIT OR Apache-2.0 | Icon documentation |
|
||||
| `assets/app-icon/LICENSE.txt` | (licence text) | original | — | Licence of the app icon files |
|
||||
| `docs/images/hero-sales.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content |
|
||||
|
||||
Generated
+1456
-204
File diff suppressed because it is too large
Load Diff
+46
-33
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -16,6 +16,7 @@ gridcraft-core = { path = "crates/core" }
|
||||
gridcraft-numfmt = { path = "crates/numfmt" }
|
||||
gridcraft-sandbox = { path = "crates/sandbox" }
|
||||
gridcraft-formula = { path = "crates/formula" }
|
||||
gridcraft-dax = { path = "crates/dax" }
|
||||
gridcraft-functions = { path = "crates/functions" }
|
||||
gridcraft-model = { path = "crates/model" }
|
||||
gridcraft-calc = { path = "crates/calc" }
|
||||
@@ -30,29 +31,31 @@ gridcraft-math = { path = "crates/math" }
|
||||
# ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one
|
||||
# craft-libs revision.
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] }
|
||||
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0", default-features = false }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
|
||||
# turn them into workbooks.
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-pages = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
|
||||
# SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx.
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -64,9 +67,11 @@ chrono = { version = "0.4.45", default-features = false, features = ["std", "clo
|
||||
web-time = "1.1.0"
|
||||
rayon = "1"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
quick-xml = "0.42"
|
||||
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`).
|
||||
sha1 = { version = "0.11", default-features = false }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
|
||||
# equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is
|
||||
@@ -92,7 +97,15 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
epaint_default_fonts = "0.37"
|
||||
# One native window per workbook: the window list, Window menu titles and the immediate-viewport
|
||||
# driver. Same craft-libs revision as craft-update above.
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["ui"] }
|
||||
# The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is
|
||||
# to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the
|
||||
# printer controls. Same craft-libs revision as above.
|
||||
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -120,18 +133,18 @@ debug = 0
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
[patch.crates-io]
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -324,6 +324,35 @@ authorization of the copyright holder.
|
||||
|
||||
SPDX-License-Identifier: Unicode-3.0
|
||||
|
||||
The Polish formula function names in crates/formula/src/input/pl.rs (the English-to-Polish
|
||||
name table) are taken from PhpSpreadsheet's locale/pl/functions table, under the MIT License.
|
||||
Source: https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Calculation/locale/pl/functions
|
||||
The following text is reproduced verbatim from PhpSpreadsheet's LICENSE:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019-2026 PhpSpreadsheet Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
SPDX-License-Identifier: MIT
|
||||
|
||||
Linux Wayland window decorations
|
||||
-------------------------------
|
||||
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
|
||||
|
||||
@@ -165,6 +165,10 @@ directives, e.g. `RUST_LOG=debug` or `RUST_LOG=warn,gridcraft_engine=debug` (a t
|
||||
matches a prefix: `gridcraft*=debug`). Runs with `GRIDCRAFT_NO_PREFS` set (no saved settings)
|
||||
log to standard error only.
|
||||
|
||||
The `nightly-v1` channel keeps all of that in its own profile instead, which the Launcher names
|
||||
(`--launch-profile nightly-v1 --profile-root <dir>`); a nightly build refuses to start without one,
|
||||
so a Nightly run never touches the stable app's settings, prefs or logs.
|
||||
|
||||
## For agents: MCP, CLI and the control channel
|
||||
|
||||
```sh
|
||||
|
||||
+30
-1
@@ -2,9 +2,10 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (Polish formula language; earlier: File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
|
||||
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
|
||||
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
|
||||
This page is the summary. The detail is in:
|
||||
@@ -151,10 +152,15 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) |
|
||||
| 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used |
|
||||
| 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged |
|
||||
| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 |
|
||||
| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) |
|
||||
| 2026-10-25 | Charts: 100% Stacked Line and 100% Stacked Line with Markers (`insert.chart` `{type: "line", subtype: "stacked100"}` and `"stacked100Markers"`), drawn as each value's share of its category's total; XLSX `percentStacked` line charts open as 100% stacked instead of stacked |
|
||||
| 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently |
|
||||
| 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export |
|
||||
| 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority |
|
||||
| 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks |
|
||||
| 2026-10-26 | `cargo xtask bench`: ten fixed in-code workbooks (100k rows) time edits, formula entry, Calculate Now, sort and XLSX save/open, check their results and compare with a saved baseline. On an M2 Pro a 100k-dependent edit recalculates in 90–106 ms and 300k formulas in 395–455 ms |
|
||||
| 2026-10-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) |
|
||||
| 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before |
|
||||
| 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step |
|
||||
| 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) |
|
||||
@@ -165,6 +171,9 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does |
|
||||
| 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share |
|
||||
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
|
||||
| 2026-10-24 | XLSX charts keep what GridCraft doesn't model on save: an embedded chart that was not edited (moving or resizing aside) is written back from its original chart part, with its style, colour and user-shape parts, while every sheet its formulas name still exists; an edited chart is written from the model as before (#1668) |
|
||||
| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) |
|
||||
| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel |
|
||||
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
|
||||
| 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row |
|
||||
| 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) |
|
||||
@@ -184,14 +193,20 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change |
|
||||
| 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS |
|
||||
| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) |
|
||||
| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root), with known differences in some `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) |
|
||||
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
|
||||
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
|
||||
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
|
||||
| 2026-10-15 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it |
|
||||
| 2026-10-15 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends it |
|
||||
| 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it |
|
||||
| 2026-10-14 | SORT, SORTBY and Data > Sort order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison |
|
||||
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
|
||||
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
|
||||
| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate |
|
||||
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
|
||||
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
|
||||
| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning |
|
||||
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
|
||||
| 2026-10-14 | XLSX: formulas opened with dynamic-array metadata (`cm`) keep it on save, with `xl/metadata.xml`. Before, a formula returning one value lost it (11 of 40 corpus files that have the part lost it entirely), and Excel recalculated some of them with implicit intersection (`SUMPRODUCT(IFERROR(...))` changed value) |
|
||||
| 2026-10-14 | Recalculation: a dynamic array's anchor given a new formula that reads its old spill area (`A1` was `=SEQUENCE(3)`, becomes `=SUM(A2:A3)+1` or `=SEQUENCE(1,A2+1)`) sees that area empty instead of the old values |
|
||||
@@ -209,6 +224,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
|
||||
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
|
||||
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
|
||||
| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) |
|
||||
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
|
||||
| 2026-10-12 | PDF writer: objects are written straight to the output, identical pictures are stored once, style operators are emitted only when they change, `q` nesting is limited to 28 and polyline joins no longer leak into later strokes (#816) |
|
||||
| 2026-10-12 | Insert › Text › WordArt (`insert.wordArt`, `wordArt.set`): floating decorative text with 10 original styles, outline and shadow, in-place editing, XLSX and print (#784) |
|
||||
@@ -281,9 +297,11 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) |
|
||||
| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; the roadmap qualifies XIRR's known `#NUM!` differences |
|
||||
| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) |
|
||||
| 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update |
|
||||
| 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row |
|
||||
| 2026-11-02 | minor | Polish formula language (`FormulaLocale::Pl`: 434 function names, PRAWDA/FAŁSZ, error values, table specifiers, `;` arguments, decimal comma) |
|
||||
| 2026-11-02 | minor | Progress log: RefEdit reference boxes in dialogs |
|
||||
| 2026-11-02 | minor | Progress log: Python mode in the formula bar |
|
||||
| 2026-11-02 | minor | Progress log: Python cells as data |
|
||||
@@ -296,13 +314,17 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories |
|
||||
| 2026-10-31 | minor | Progress log: Function Library |
|
||||
| 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles |
|
||||
| 2026-10-26 | minor | Progress log: Excel open check |
|
||||
| 2026-10-26 | minor | Progress log: PDF reading direction and RTL sheets |
|
||||
| 2026-10-26 | minor | Progress log: Arabic PDF text |
|
||||
| 2026-10-26 | minor | Progress log: Arabic bidi display and editing |
|
||||
| 2026-10-26 | minor | Progress log: Arabic font fallback |
|
||||
| 2026-10-26 | minor | Progress log: `cargo xtask bench` |
|
||||
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
|
||||
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
|
||||
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
|
||||
| 2026-10-24 | trivial | Progress log: unedited embedded charts keep their XML on save (#1668) |
|
||||
| 2026-10-24 | minor | Progress log: password to modify (#921) |
|
||||
| 2026-10-23 | minor | Progress log: accounting negatives in number text |
|
||||
| 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! |
|
||||
| 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) |
|
||||
@@ -315,14 +337,21 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
|
||||
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
|
||||
| 2026-10-19 | trivial | Progress log: desktop theme portal read timeout |
|
||||
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) |
|
||||
| 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes |
|
||||
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
|
||||
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
|
||||
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
|
||||
| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers |
|
||||
| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save |
|
||||
| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes |
|
||||
| 2026-10-14 | minor | Progress log: sorts order numbers exactly |
|
||||
| 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) |
|
||||
| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting |
|
||||
| 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook kept on save |
|
||||
| 2026-10-14 | minor | Progress log: lookups compare numbers exactly |
|
||||
| 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references |
|
||||
| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save |
|
||||
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
|
||||
| 2026-10-14 | minor | Progress log: spill anchor reading its old spill area |
|
||||
| 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict |
|
||||
|
||||
@@ -65,6 +65,13 @@ fn cond_format_list(s: &Sheet) -> Vec<String> {
|
||||
cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect()
|
||||
}
|
||||
|
||||
/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is
|
||||
/// in another workbook, a data connection or the Data Model).
|
||||
fn pivot_count(s: &Sheet) -> usize {
|
||||
let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count());
|
||||
s.pivots.len() + kept
|
||||
}
|
||||
|
||||
fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) {
|
||||
if a != b {
|
||||
d.push(|| format!("{sheet}: {a} → {b}"));
|
||||
@@ -154,7 +161,7 @@ pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec<Categor
|
||||
}
|
||||
diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len());
|
||||
diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len());
|
||||
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
|
||||
diff_count(&mut pivots, &name, pivot_count(sa), pivot_count(sb));
|
||||
}
|
||||
let mut names = Diffs::new("names", m);
|
||||
let name_list = |wb: &Workbook| -> BTreeSet<String> {
|
||||
|
||||
@@ -16,11 +16,8 @@ pub(super) const REBUILT_KINDS: [&str; 1] = ["calcchain"];
|
||||
|
||||
// ---------------------------------------------------------------- package validation
|
||||
|
||||
fn local_name(name: &[u8]) -> &[u8] {
|
||||
match name.iter().rposition(|&b| b == b':') {
|
||||
Some(i) => name.get(i + 1..).unwrap_or(name),
|
||||
None => name,
|
||||
}
|
||||
fn local_name(name: &str) -> &str {
|
||||
name.rsplit(':').next().unwrap_or(name)
|
||||
}
|
||||
|
||||
/// `(element local name, attributes)` for every start/empty element of an XML part.
|
||||
@@ -41,12 +38,12 @@ fn xml_elements(xml: &[u8]) -> Result<Vec<XmlElement>, String> {
|
||||
.map(|a| {
|
||||
let v = match a.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
|
||||
Ok(v) => v.into_owned(),
|
||||
Err(_) => String::from_utf8_lossy(&a.value).into_owned(),
|
||||
Err(_) => a.value.to_string(),
|
||||
};
|
||||
(String::from_utf8_lossy(local_name(a.key.as_ref())).into_owned(), v)
|
||||
(local_name(a.key.as_ref()).to_string(), v)
|
||||
})
|
||||
.collect();
|
||||
out.push((String::from_utf8_lossy(local_name(e.name().as_ref())).into_owned(), attrs));
|
||||
out.push((local_name(e.name().as_ref()).to_string(), attrs));
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Ok(_) => {}
|
||||
@@ -110,12 +107,20 @@ fn resolve_target(source_dir: &str, target: &str) -> String {
|
||||
|
||||
type Zip<'a> = zip::ZipArchive<Cursor<&'a [u8]>>;
|
||||
|
||||
fn zip_names(zip: &mut Zip<'_>) -> Vec<String> {
|
||||
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| f.name().to_string())).collect()
|
||||
/// `(index, name)` of every file entry. Parts are read by index: two entries can decode to the
|
||||
/// same name, and looking up a CP437 name scans the whole archive.
|
||||
fn zip_names(zip: &mut Zip<'_>) -> Vec<(usize, String)> {
|
||||
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| (i, entry_name(&f)))).collect()
|
||||
}
|
||||
|
||||
fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
|
||||
let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
|
||||
/// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode
|
||||
/// is listed with its raw bytes made lossy, so the entry is still checked and reported.
|
||||
fn entry_name<R: std::io::Read>(f: &zip::read::ZipFile<'_, R>) -> String {
|
||||
f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned())
|
||||
}
|
||||
|
||||
fn read_zip_part(zip: &mut Zip<'_>, index: usize, name: &str) -> Result<Vec<u8>, String> {
|
||||
let f = zip.by_index(index).map_err(|e| format!("{name}: {e}"))?;
|
||||
let mut buf = Vec::new();
|
||||
f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?;
|
||||
Ok(buf)
|
||||
@@ -128,8 +133,8 @@ enum PartError {
|
||||
}
|
||||
|
||||
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
|
||||
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
|
||||
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
|
||||
fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Result<Vec<u8>, PartError> {
|
||||
let f = zip.by_index(index).map_err(|_| PartError::Unreadable)?;
|
||||
// One byte past what is left shows that the part doesn't fit.
|
||||
let limit = MAX_XML_PART.min(budget.saturating_add(1));
|
||||
let mut buf = Vec::new();
|
||||
@@ -150,10 +155,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Resu
|
||||
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
let Ok(mut zip) = zip::ZipArchive::new(Cursor::new(bytes)) else { return false };
|
||||
let names = zip_names(&mut zip);
|
||||
let find = |key: &str| names.iter().find(|n| part_key(n) == key).cloned();
|
||||
let find = |key: &str| names.iter().find(|(_, n)| part_key(n) == key).cloned();
|
||||
let mut workbook = "xl/workbook.xml".to_string();
|
||||
if let Some(rels) = find("_rels/.rels")
|
||||
&& let Ok(xml) = read_zip_part(&mut zip, &rels)
|
||||
if let Some((i, rels)) = find("_rels/.rels")
|
||||
&& let Ok(xml) = read_zip_part(&mut zip, i, &rels)
|
||||
&& let Ok(els) = xml_elements(&xml)
|
||||
&& let Some(target) = els
|
||||
.iter()
|
||||
@@ -162,8 +167,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
{
|
||||
workbook = resolve_target("", target);
|
||||
}
|
||||
let Some(name) = find(&part_key(&workbook)) else { return false };
|
||||
let Ok(xml) = read_zip_part(&mut zip, &name) else { return false };
|
||||
let Some((i, name)) = find(&part_key(&workbook)) else { return false };
|
||||
let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false };
|
||||
xml_elements(&xml)
|
||||
.ok()
|
||||
.into_iter()
|
||||
@@ -177,15 +182,15 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
|
||||
let names = zip_names(&mut zip);
|
||||
let parts: HashSet<String> = names.iter().map(|n| part_key(n)).collect();
|
||||
let mut read_part = |name: &str| read_zip_part(&mut zip, name);
|
||||
let parts: HashSet<String> = names.iter().map(|(_, n)| part_key(n)).collect();
|
||||
let mut read_part = |index: usize, name: &str| read_zip_part(&mut zip, index, name);
|
||||
let mut issues = Vec::new();
|
||||
let ct_name = names.iter().find(|n| part_key(n) == "[content_types].xml").cloned();
|
||||
let ct_name = names.iter().find(|(_, n)| part_key(n) == "[content_types].xml").cloned();
|
||||
let (mut defaults, mut overrides) = (HashSet::new(), HashSet::new());
|
||||
match ct_name {
|
||||
None => issues.push("no [Content_Types].xml".to_string()),
|
||||
Some(n) => {
|
||||
for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
|
||||
Some((i, n)) => {
|
||||
for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
|
||||
match el.as_str() {
|
||||
"Default" => {
|
||||
if let Some(x) = attr(&attrs, "Extension") {
|
||||
@@ -202,9 +207,9 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sorted: Vec<&String> = names.iter().collect();
|
||||
sorted.sort();
|
||||
for n in &sorted {
|
||||
let mut sorted: Vec<&(usize, String)> = names.iter().collect();
|
||||
sorted.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
|
||||
for (_, n) in &sorted {
|
||||
let key = part_key(n);
|
||||
if key == "[content_types].xml" {
|
||||
continue;
|
||||
@@ -219,7 +224,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
for p in missing_overrides {
|
||||
issues.push(format!("content type override for missing part /{p}"));
|
||||
}
|
||||
for n in sorted {
|
||||
for (i, n) in sorted {
|
||||
let key = part_key(n);
|
||||
let Some(rels_file) = key.strip_suffix(".rels") else { continue };
|
||||
// `dir/_rels/name.rels` describes `dir/name`; `_rels/.rels` the package itself.
|
||||
@@ -233,7 +238,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
issues.push(format!("{n} describes missing part {source}"));
|
||||
}
|
||||
let mut ids = HashSet::new();
|
||||
for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? {
|
||||
for (el, attrs) in xml_elements(&read_part(*i, n)?).map_err(|e| format!("{n}: {e}"))? {
|
||||
if el != "Relationship" {
|
||||
continue;
|
||||
}
|
||||
@@ -268,17 +273,17 @@ pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String
|
||||
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
|
||||
let names = zip_names(&mut zip);
|
||||
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
|
||||
let by_key: HashMap<String, &(usize, String)> = names.iter().map(|e| (part_key(&e.1), e)).collect();
|
||||
// Several relationships name the same part; each fresh check decompressed it again, so
|
||||
// repeated references to one highly compressible part multiplied the work. The verdict is
|
||||
// remembered per (part, named content) and the decompression the package can cause is
|
||||
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
|
||||
// would otherwise each spend a full per-part allowance.
|
||||
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
|
||||
let mut verdicts: HashMap<(usize, &'static str), bool> = HashMap::new();
|
||||
let mut kinds = BTreeMap::new();
|
||||
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
|
||||
for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) {
|
||||
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
|
||||
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
|
||||
let xml = match read_zip_part_within(&mut zip, *i, &mut budget) {
|
||||
Ok(xml) => xml,
|
||||
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
|
||||
Err(PartError::Unreadable) => continue,
|
||||
@@ -292,8 +297,8 @@ fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<S
|
||||
}
|
||||
let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External"));
|
||||
if !external
|
||||
&& let Some(part) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
|
||||
&& !holds_something(&mut zip, part, kind, &mut verdicts, &mut budget)
|
||||
&& let Some((index, _)) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
|
||||
&& !holds_something(&mut zip, *index, kind, &mut verdicts, &mut budget)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -314,7 +319,7 @@ fn rels_source_dir(key: &str) -> Option<String> {
|
||||
/// comes first) a comment, for VML a shape. Read only as far as needed; an unreadable part counts.
|
||||
/// `verdicts` remembers the answer per (part, named content); `budget` is the decompression this
|
||||
/// package's remaining checks may cause, and once it is spent the part counts as having content.
|
||||
fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'static str), bool>, budget: &mut u64) -> bool {
|
||||
fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool {
|
||||
let wanted: Option<&'static [u8]> = match kind.to_ascii_lowercase().as_str() {
|
||||
"comments" => Some(b"comment"),
|
||||
"vmldrawing" => Some(b"shape"),
|
||||
@@ -325,26 +330,26 @@ fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut Has
|
||||
Some(_) => "shape",
|
||||
None => "any",
|
||||
};
|
||||
if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) {
|
||||
if let Some(v) = verdicts.get(&(index, marker)) {
|
||||
return *v;
|
||||
}
|
||||
let v = holds_something_uncached(zip, name, marker, budget);
|
||||
verdicts.insert((name.to_ascii_lowercase(), marker), v);
|
||||
let v = holds_something_uncached(zip, index, marker, budget);
|
||||
verdicts.insert((index, marker), v);
|
||||
v
|
||||
}
|
||||
|
||||
fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool {
|
||||
fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool {
|
||||
use quick_xml::events::Event;
|
||||
let Ok(f) = zip.by_name(name) else { return true };
|
||||
let Ok(f) = zip.by_index(index) else { return true };
|
||||
if *budget == 0 {
|
||||
return true;
|
||||
}
|
||||
let take = f.size().min(MAX_XML_PART).min(*budget);
|
||||
*budget -= take;
|
||||
let mut reader = quick_xml::Reader::from_reader(std::io::BufReader::new(f.take(take)));
|
||||
let wanted: Option<&'static [u8]> = match marker {
|
||||
"comment" => Some(b"comment"),
|
||||
"shape" => Some(b"shape"),
|
||||
let wanted: Option<&'static str> = match marker {
|
||||
"comment" => Some("comment"),
|
||||
"shape" => Some("shape"),
|
||||
_ => None,
|
||||
};
|
||||
let mut buf = Vec::new();
|
||||
@@ -392,6 +397,57 @@ mod tests {
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// A package with two relationship parts whose names both read `xl/_rels/é.xml.rels`: the first
|
||||
/// stored as UTF-8 holding `first`, the second stored as CP437 (byte 0x82) holding `second`.
|
||||
fn same_name_rels(first: &str, second: &str) -> Vec<u8> {
|
||||
const PLACEHOLDER: &[u8] = b"xl/_rels/Q.xml.rels";
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
z.start_file("xl/_rels/\u{e9}.xml.rels", opts).unwrap();
|
||||
z.write_all(first.as_bytes()).unwrap();
|
||||
z.start_file(String::from_utf8(PLACEHOLDER.to_vec()).unwrap(), opts).unwrap();
|
||||
z.write_all(second.as_bytes()).unwrap();
|
||||
let mut bytes = z.finish().unwrap().into_inner();
|
||||
// The name sits in the local header and in the central directory; both get the CP437 byte.
|
||||
let mut at = 0;
|
||||
let mut patched = 0;
|
||||
while let Some(i) = bytes.get(at..).and_then(|rest| rest.windows(PLACEHOLDER.len()).position(|w| w == PLACEHOLDER)) {
|
||||
bytes[at + i + 9] = 0x82;
|
||||
at += i + PLACEHOLDER.len();
|
||||
patched += 1;
|
||||
}
|
||||
assert_eq!(patched, 2);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn rels_xml(rels: &[(&str, &str)]) -> String {
|
||||
let body: String = rels
|
||||
.iter()
|
||||
.map(|(id, kind)| {
|
||||
format!(
|
||||
r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}" Target="https://example.com" TargetMode="External"/>"#
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
format!(r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{body}</Relationships>"#)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_with_the_same_decoded_name_are_each_validated() {
|
||||
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "custom"), ("rId1", "custom")]));
|
||||
let issues = validate_package(&bytes).unwrap();
|
||||
let duplicates = issues.iter().filter(|i| i.ends_with("duplicate relationship id rId1")).count();
|
||||
assert_eq!(duplicates, 1, "{issues:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_kinds_read_parts_with_the_same_decoded_name() {
|
||||
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "audio")]));
|
||||
let kinds = relationship_kinds(&bytes).unwrap();
|
||||
assert!(kinds.contains_key("custom"), "{kinds:?}");
|
||||
assert!(kinds.contains_key("audio"), "{kinds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_parts_count_against_the_decompression_budget() {
|
||||
// Each part fits the per-part allowance, but together they need more than the budget.
|
||||
|
||||
@@ -344,7 +344,7 @@ fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec
|
||||
let mut pending: Vec<(&str, &str)> = rels.to_vec();
|
||||
for i in 0..src.len() {
|
||||
let mut f = src.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut body = String::new();
|
||||
f.read_to_string(&mut body).unwrap();
|
||||
if let Some(at) = pending.iter().position(|(r, _)| *r == name) {
|
||||
|
||||
@@ -65,12 +65,35 @@ fn stdout_failed(e: std::io::Error) -> ! {
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the
|
||||
/// tokens a shell would see before `--` count: after it they are file names.
|
||||
fn launch_profile_argument(args: &[std::ffi::OsString]) -> Option<String> {
|
||||
for arg in args {
|
||||
if arg == "--" {
|
||||
return None;
|
||||
}
|
||||
let text = arg.to_string_lossy();
|
||||
for flag in ["--launch-profile", "--profile-root"] {
|
||||
if text == flag || text.starts_with(&format!("{flag}=")) {
|
||||
return Some(flag.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
// A confined launcher run (and its probes) comes first, before anything else starts.
|
||||
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
|
||||
return ExitCode::from(u8::try_from(code).unwrap_or(1));
|
||||
}
|
||||
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a
|
||||
// CLI option, and a CLI that silently ignored it would act on the wrong files.
|
||||
if let Some(flag) = launch_profile_argument(&raw) {
|
||||
eprintln!("gridcraft-cli: {flag} belongs to the GridCraft desktop app, not this CLI");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let rest = args.get(1..).unwrap_or_default();
|
||||
let r = match args.first().map(String::as_str) {
|
||||
@@ -164,7 +187,7 @@ impl Args {
|
||||
|
||||
fn exec(s: &mut Session, id: &str, params: Value) -> Result<Value, String> {
|
||||
let r = s.execute_headless(id, params).map_err(|e| e.to_string());
|
||||
if id == "file.open"
|
||||
if matches!(id, "file.open" | "file.save" | "file.saveAs" | "file.saveBytes")
|
||||
&& let Ok(value) = &r
|
||||
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
|
||||
{
|
||||
@@ -305,6 +328,9 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
eprintln!("wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
|
||||
return Ok(());
|
||||
}
|
||||
for warning in gridcraft_engine::cmd::file::save_losses(&s, "file.save", &json!({"path": out})).messages() {
|
||||
eprintln!("Warning: {warning}");
|
||||
}
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(|e| e.to_string())?;
|
||||
gridcraft_engine::io::write_file(out, &bytes).map_err(|e| e.to_string())?;
|
||||
@@ -590,6 +616,22 @@ mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2
|
||||
/// rather than acting on whatever it thinks the file list is.
|
||||
#[test]
|
||||
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
|
||||
let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
|
||||
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
|
||||
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
|
||||
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
|
||||
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
|
||||
// After `--` they are file names, exactly as the desktop app parses them.
|
||||
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
|
||||
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
|
||||
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
|
||||
assert_eq!(launch_profile_argument(&[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_commands() {
|
||||
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
|
||||
|
||||
@@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true }
|
||||
gridcraft-ui-egui = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.gridcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -49,6 +49,7 @@ pub fn start() {
|
||||
canvas,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
gridcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
|
||||
let inbox: Inbox = Inbox::default();
|
||||
let mut session = Session::new();
|
||||
// In host mode the host sends the workbook to edit; no sample meanwhile.
|
||||
@@ -158,6 +159,7 @@ impl eframe::App for WebShell {
|
||||
});
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
self.app.close_path(ctx);
|
||||
// Store changed preferences straight away: a reload or closed tab runs no exit code (#1562).
|
||||
let changed = self.prefs.changed(&self.app);
|
||||
if !changed.is_empty() {
|
||||
@@ -177,6 +179,7 @@ impl eframe::App for WebShell {
|
||||
/// Forwards a browser frame's raw input to the shared app before eframe handles it.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
self.app.before_input(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
|
||||
@@ -30,9 +30,11 @@ winresource = "0.1"
|
||||
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Nightly self-isolation, launch protocol, and security fence (storytold/craft-libs).
|
||||
craft-nightly = { workspace = true }
|
||||
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
|
||||
# Cargo.toml).
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
|
||||
craft-print = { workspace = true }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true, features = ["image-data"] }
|
||||
@@ -43,9 +45,15 @@ getrandom = "0.4"
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
|
||||
arboard = { workspace = true, features = ["image-data", "wayland-data-control"] }
|
||||
|
||||
# GNOME does not provide server-side decorations on Wayland. Keep the Adwaita frame
|
||||
# and buttons without embedding its fallback title font; the ribbon shows the name (#54).
|
||||
winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe.
|
||||
pollster = "1"
|
||||
# The explicit AppUserModelID the nightly channel sets before its first window (`process_identity.rs`).
|
||||
winsafe = { version = "0.0.29", features = ["user", "shell"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
muda = { version = "0.21", default-features = false }
|
||||
|
||||
+48
-6
@@ -1,25 +1,67 @@
|
||||
//! Windows only: embed the app icon and version info (VERSIONINFO) into `gridcraft.exe`, so it
|
||||
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
|
||||
//!
|
||||
//! On every other target this does nothing. A missing resource compiler is a warning, so a
|
||||
//! cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! into an error (for release builds).
|
||||
//! On every other target this does nothing but the channel work. A missing resource compiler is a
|
||||
//! warning, so a cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1`
|
||||
//! turns it into an error (for release builds).
|
||||
//!
|
||||
//! The nightly channel is a build-time decision: `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` sets
|
||||
//! `cfg(gridcraft_nightly_v1)` and requires the prepared `GRIDCRAFT_VERSION` feed identity, which
|
||||
//! becomes the executable's `ProductVersion` (the Launcher checks that, not `FileVersion`) and the
|
||||
//! version the app answers `--version` with. Anything else than `stable`, empty or `nightly-v1`
|
||||
//! is a build error, so a typo cannot silently ship the wrong channel.
|
||||
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-env-changed=GRIDCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo:rustc-check-cfg=cfg(gridcraft_nightly_v1)");
|
||||
let nightly = match std::env::var("GRIDCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=gridcraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
// An empty value (an unset CI input) means the default stable build.
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
eprintln!("unsupported GRIDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft.ico");
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft-nightly.ico");
|
||||
println!("cargo:rerun-if-env-changed=GRIDCRAFT_REQUIRE_WINRES");
|
||||
println!("cargo:rerun-if-env-changed=GRIDCRAFT_VERSION");
|
||||
let built_version = if nightly {
|
||||
match std::env::var("GRIDCRAFT_VERSION") {
|
||||
Ok(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit GRIDCRAFT_VERSION feed identity");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=GRIDCRAFT_BUILT_VERSION={built_version}");
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("../../assets/app-icon/gridcraft.ico")
|
||||
.set("ProductName", "GridCraft")
|
||||
.set("FileDescription", "GridCraft spreadsheet")
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "GridCraft Nightly" } else { "GridCraft" })
|
||||
.set("FileDescription", if nightly { "GridCraft Nightly spreadsheet" } else { "GridCraft spreadsheet" })
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the GridCraft authors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "gridcraft.exe")
|
||||
.set("InternalName", "gridcraft");
|
||||
if nightly {
|
||||
// The Launcher compares the PE ProductVersion with the exact feed identity.
|
||||
res.set("ProductVersion", &built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("GRIDCRAFT_REQUIRE_WINRES").is_some() {
|
||||
eprintln!("embedding Windows resources failed: {e}");
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//! The one place a GridCraft data root is resolved, so the nightly profile and the platform
|
||||
//! default can never disagree.
|
||||
//!
|
||||
//! Everything the desktop writes about the user lives under [`config_dir`]: `ui.json`,
|
||||
//! `prefs.json` and `logs/` (see `logging`). The control channel's token folder is resolved by
|
||||
//! `gridcraft_mcp` from the same root at start-up. Nothing else in the app persists user state.
|
||||
//! A nightly takes its root from the Launcher's validated profile and nothing else, so stable has
|
||||
//! no environment override of its own: the platform's published folder is the whole story.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
match platform {
|
||||
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
|
||||
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
|
||||
_ => env("XDG_CONFIG_HOME")
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("gridcraft")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder the settings and the log files live in.
|
||||
pub fn config_dir_for(platform: &str, env: &impl Fn(&str) -> Option<OsString>, nightly_root: Option<&std::path::Path>) -> Option<PathBuf> {
|
||||
match nightly_root {
|
||||
// The profile was already validated (absolute, fenced, writable) before this runs.
|
||||
Some(root) => Some(root.to_path_buf()),
|
||||
None => default_config_dir(platform, env),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
config_dir_for(std::env::consts::OS, &|key| std::env::var_os(key), crate::launch_profile::current().root())
|
||||
}
|
||||
|
||||
/// Where the log files live: `logs` in the settings folder, next to `ui.json`.
|
||||
pub fn log_dir() -> Option<PathBuf> {
|
||||
Some(config_dir()?.join("logs"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<OsString> {
|
||||
let map: BTreeMap<String, OsString> = pairs.iter().map(|(k, v)| ((*k).to_string(), OsString::from(v))).collect();
|
||||
move |key| map.get(key).cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_platform_keeps_its_published_folder() {
|
||||
// The base is joined with the host's own separator, so these hold on any machine the gate
|
||||
// runs on: what each platform publishes is the folder name, not how the host spells a slash.
|
||||
let appdata = PathBuf::from(r"C:\Users\u\AppData\Roaming");
|
||||
assert_eq!(config_dir_for("windows", &env(&[("APPDATA", &appdata.to_string_lossy())]), None), Some(appdata.join("GridCraft")));
|
||||
let home = PathBuf::from("/home/u");
|
||||
assert_eq!(
|
||||
config_dir_for("macos", &env(&[("HOME", &home.to_string_lossy())]), None),
|
||||
Some(home.join("Library/Application Support/GridCraft"))
|
||||
);
|
||||
assert_eq!(config_dir_for("linux", &env(&[("HOME", &home.to_string_lossy())]), None), Some(home.join(".config").join("gridcraft")));
|
||||
assert_eq!(
|
||||
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home.to_string_lossy())]), None),
|
||||
Some(PathBuf::from("/xdg").join("gridcraft"))
|
||||
);
|
||||
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "")]), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_xdg_config_home_falls_back_to_the_home_folder() {
|
||||
let home = PathBuf::from("/home/u");
|
||||
let home_str = home.to_string_lossy().into_owned();
|
||||
assert_eq!(
|
||||
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", ""), ("HOME", &home_str)]), None),
|
||||
Some(home.join(".config").join("gridcraft"))
|
||||
);
|
||||
assert_eq!(
|
||||
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home_str)]), None),
|
||||
Some(PathBuf::from("/xdg").join("gridcraft"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nightly_profile_is_the_whole_answer() {
|
||||
let profile = std::path::Path::new("/var/lib/gridcraft-nightly/profile");
|
||||
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", "/home/u")]), Some(profile)), Some(profile.to_path_buf()));
|
||||
assert_eq!(config_dir_for("linux", &env(&[("HOME", "/home/u")]), Some(profile)).unwrap().join("logs"), profile.join("logs"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/gridcraft-nightly.ico" } else { "../../assets/app-icon/gridcraft.ico" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
|
||||
assert_eq!(windows_icon_path(false), "../../assets/app-icon/gridcraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/gridcraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.19.1-nightly.20261124.7.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.19.1",
|
||||
"0.19.1-nightly",
|
||||
"0.19.1-nightly.20261124",
|
||||
"0.19.1-nightly.20261124.7.1.gABCDEF012345",
|
||||
"0.19.1-nightly.20261124.7.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.19.1-nightly.20261124.1.1.gabcdef012345",
|
||||
"0.19.1-nightly.20261124.1.1.gabcdef012345/other",
|
||||
"0.19.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
|
||||
//! stable build, and a nightly build always stays isolated in its nightly profile.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{BuildFlavor, needs_native_error, version, version_query};
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.19.1"), "0.19.1 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Nightly-v1 bootstrap backed by `craft-nightly`, selected before logging, updates, fonts or saved
|
||||
//! state. Direct launches of a nightly build self-isolate into
|
||||
//! `craft_nightly::canonical_profile_root("gridcraft")`, while ArtCraft Launcher may still pass
|
||||
//! `--launch-profile nightly-v1 --profile-root <absolute> -- <files...>`. Stable launches keep
|
||||
//! their original arguments and directory policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
pub use craft_nightly::Profile;
|
||||
|
||||
/// Returns the process-wide profile installed by `craft_nightly::prepare_launch`, defaulting to
|
||||
/// [`Profile::Stable`] before startup selection.
|
||||
pub fn current() -> &'static Profile {
|
||||
craft_nightly::current().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
/// Restores the `--` option terminator when `craft_nightly::parse_startup` consumed it after an
|
||||
/// explicit `--launch-profile` / `--profile-root` header, so downstream argument parsing keeps
|
||||
/// treating every launcher-supplied tail token (such as a file named `--control`) as a filename.
|
||||
pub fn restore_launcher_separator(raw_args: &[OsString], passthrough_args: Vec<OsString>) -> Vec<OsString> {
|
||||
let separator_index = raw_args.len().checked_sub(passthrough_args.len() + 1);
|
||||
if let Some(index) = separator_index
|
||||
&& raw_args.get(index).is_some_and(|arg| arg == "--")
|
||||
{
|
||||
return std::iter::once(OsString::from("--")).chain(passthrough_args).collect();
|
||||
}
|
||||
passthrough_args
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use craft_nightly::{
|
||||
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup,
|
||||
};
|
||||
|
||||
use super::restore_launcher_separator;
|
||||
use crate::profile_root;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
launch_arguments(Path::new(absolute()), &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
|
||||
let spec = profile_root::app_spec();
|
||||
let expected_root = canonical_profile_root("gridcraft").expect("canonical root");
|
||||
let argv = args(&["sales.xlsx", "--sample", "budget"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert!(launch.profile.is_nightly());
|
||||
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let spec = profile_root::app_spec();
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(
|
||||
restore_launcher_separator(&argv, launch.passthrough_args),
|
||||
args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_build_refuses_nightly_launch_flags() {
|
||||
let spec = profile_root::app_spec();
|
||||
let result = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::default());
|
||||
assert!(matches!(result, Err(ProfileError::NightlyFlagsInStableBuild)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "sales.xlsx", "--profile-root", absolute()]),
|
||||
args(&["sales.xlsx", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).is_err(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launcher_version_queries_are_recognized_without_touching_the_profile() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["-V"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
|
||||
launch_arguments(Path::new(absolute()), &args(&["--version"])),
|
||||
launch_arguments(Path::new(absolute()), &args(&["-V"])),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
for argv in [
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--help"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--control", "7979", "--version"]),
|
||||
launch_arguments(Path::new(absolute()), &args(&["sales.xlsx", "--version"])),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(!launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+357
-73
@@ -9,16 +9,25 @@
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod app_dirs;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod apple_events;
|
||||
// The build channel's own parser and icon-path tests (build.rs compiles the same file by path).
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
#[cfg(any(target_os = "windows", target_os = "macos", test))]
|
||||
mod graphics;
|
||||
mod launch_profile;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod opener;
|
||||
mod print;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
@@ -29,45 +38,63 @@ use gridcraft_ui_egui::{Services, SheetApp};
|
||||
use serde_json::json;
|
||||
|
||||
/// The app, its native window per workbook window, and (macOS) the menu bar and Finder events.
|
||||
struct App(SheetApp, DocWindows, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>, #[cfg(target_os = "macos")] fmv_macos_events::Inbox);
|
||||
/// The session record and its notice flag are only meaningful in the nightly channel.
|
||||
struct App {
|
||||
app: SheetApp,
|
||||
windows: DocWindows,
|
||||
#[cfg(target_os = "macos")]
|
||||
menu: Option<native_menu::NativeMenu>,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
/// The Nightly session record, shared with the exit hook and the return path.
|
||||
nightly: nightly_session::Shared,
|
||||
/// Whether this window already told the user the previous session did not finish.
|
||||
nightly_notice_shown: bool,
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if self.2.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
|
||||
self.2 = Some(native_menu::NativeMenu::install(ctx));
|
||||
if self.menu.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
|
||||
self.menu = Some(native_menu::NativeMenu::install(ctx));
|
||||
}
|
||||
if let Some(m) = &mut self.2 {
|
||||
m.poll(&mut self.0, ctx, self.1.focused_viewport());
|
||||
if let Some(m) = &mut self.menu {
|
||||
m.poll(&mut self.app, ctx, self.windows.focused_viewport());
|
||||
}
|
||||
apple_events::poll(&self.3, &mut self.0, ctx);
|
||||
}
|
||||
self.0.logic(ctx);
|
||||
self.1.logic(&mut self.0, ctx);
|
||||
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
apple_events::poll(&self.apple_events, &mut self.app, ctx);
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
self.windows.logic(&mut self.app, ctx);
|
||||
self.app.close_path(ctx);
|
||||
}
|
||||
/// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
self.app.before_input(ctx);
|
||||
// Files dropped on the window open as workbooks.
|
||||
for f in std::mem::take(&mut raw.dropped_files) {
|
||||
if let Some(p) = f.path().to_str().map(str::to_string).filter(|p| !p.is_empty()) {
|
||||
self.0.open_path(&p);
|
||||
self.app.open_path(&p);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.1.show(&mut self.0, ui);
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
self.windows.show(&mut self.app, ui);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
print::finish_pending_jobs();
|
||||
save_prefs(&self.0);
|
||||
save_prefs(&self.app);
|
||||
// A ready update installs once the process has exited. The macOS exit below skips
|
||||
// dropping the app, so the helper is started here.
|
||||
self.0.start_pending_update();
|
||||
// dropping the app, so the helper is started here. A nightly has no updater at all.
|
||||
if gridcraft_ui_egui::channel::stable_services_allowed() {
|
||||
self.app.start_pending_update();
|
||||
}
|
||||
// The Nightly session record is finished here: every way of quitting reaches `on_exit`,
|
||||
// and on macOS AppKit's terminate ends the process right after it, so nothing after
|
||||
// `eframe::run_native` can run there. `finish_once` makes the later call a no-op.
|
||||
nightly_session::finish_once(&self.nightly, self.nightly_notice_shown);
|
||||
// macOS (#117): end the process here, before eframe tears the window down. AccessKit's
|
||||
// macOS adapter subclasses the window's content view and restores its class on teardown;
|
||||
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
|
||||
@@ -81,17 +108,10 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings folder: the validated nightly profile, else the platform's own folder
|
||||
/// (`app_dirs`). Every writer of user state goes through it.
|
||||
fn config_dir() -> Option<std::path::PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/GridCraft"))
|
||||
} else if cfg!(windows) {
|
||||
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("GridCraft"))
|
||||
} else {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("gridcraft"))
|
||||
}
|
||||
app_dirs::config_dir()
|
||||
}
|
||||
|
||||
/// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write
|
||||
@@ -102,7 +122,7 @@ fn prefs_enabled() -> bool {
|
||||
|
||||
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
|
||||
fn log_dir() -> Option<std::path::PathBuf> {
|
||||
Some(config_dir()?.join("logs"))
|
||||
app_dirs::log_dir()
|
||||
}
|
||||
|
||||
fn load_prefs(app: &mut SheetApp) {
|
||||
@@ -194,8 +214,13 @@ fn services() -> Services {
|
||||
let path = std::path::Path::new(suggested);
|
||||
let stem = path.file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("Book1").to_string();
|
||||
// The suggested name's type (an export asks for .pdf, .csv or .html) comes first.
|
||||
const TYPES: [(&str, &str); 4] =
|
||||
[("Excel Workbook (.xlsx)", "xlsx"), ("CSV UTF-8 (.csv)", "csv"), ("Web Page (.html)", "html"), ("PDF (.pdf)", "pdf")];
|
||||
const TYPES: [(&str, &str); 5] = [
|
||||
("Excel Workbook (.xlsx)", "xlsx"),
|
||||
("CSV UTF-8 (.csv)", "csv"),
|
||||
("Web Page (.html)", "html"),
|
||||
("PDF (.pdf)", "pdf"),
|
||||
("GridCraft Workbook (.json)", "json"),
|
||||
];
|
||||
let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).filter(|e| TYPES.iter().any(|(_, x)| x == e));
|
||||
let ext = ext.unwrap_or_else(|| "xlsx".to_string());
|
||||
let mut dialog = rfd::FileDialog::new().set_file_name(format!("{stem}.{ext}"));
|
||||
@@ -241,13 +266,156 @@ fn icon() -> Option<egui::IconData> {
|
||||
Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() })
|
||||
}
|
||||
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(
|
||||
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
|
||||
gridcraft_ui_egui::channel::id_for(gridcraft_ui_egui::channel::Channel::NightlyV1),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// Tell a desktop user why a nightly launch was refused, in a native box where one renders without the
|
||||
/// app's event loop (Windows, X11/Wayland), and on standard error always. A headless form (`--version`
|
||||
/// on a runner) never gets here: the version query is answered before this and before any profile work.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("GridCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("GridCraft launch profile: {error}");
|
||||
return;
|
||||
}
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title("GridCraft Nightly")
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the immutable launch channel and profile before any startup service or side effect.
|
||||
/// `None` means the answer was printed (`--version`) and the process is done.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
|
||||
// Plain `--version` / `-V` on a nightly build is answered before any profile resolution,
|
||||
// process identity, IPC, or window (a dialog here would hang a headless runner and fail a
|
||||
// Linux build, and `--version` must still work when HOME / LOCALAPPDATA is unset).
|
||||
if nightly_build && build_flavor::version_query(&argv) {
|
||||
use std::io::Write as _;
|
||||
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
|
||||
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
|
||||
return None;
|
||||
}
|
||||
let spec = profile_root::app_spec();
|
||||
let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv.iter().cloned(), &craft_nightly::StartupOptions::default())
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
|
||||
// `craft_nightly::prepare_launch` performs no filesystem preparation and installs no profile.
|
||||
if nightly_build && launch.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
|
||||
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let channel =
|
||||
if launch.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
|
||||
if let Err(error) = gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(launch_profile::restore_launcher_separator(&argv, launch.passthrough_args))
|
||||
}
|
||||
|
||||
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
|
||||
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
|
||||
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
|
||||
/// documents (`launch_profile::restore_launcher_separator` preserves the separator first), so the
|
||||
/// separator itself is never opened as a file.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct DesktopArgs {
|
||||
control_port: Option<u16>,
|
||||
control_token: Option<String>,
|
||||
sample: Option<String>,
|
||||
files: Vec<String>,
|
||||
}
|
||||
|
||||
fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Option<String>) -> DesktopArgs {
|
||||
let mut parsed = DesktopArgs { control_port, control_token, ..DesktopArgs::default() };
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--" => {
|
||||
parsed.files.extend(args[i + 1..].iter().cloned());
|
||||
break;
|
||||
}
|
||||
"--control" => {
|
||||
i += 1;
|
||||
parsed.control_port = args.get(i).and_then(|p| p.parse().ok());
|
||||
}
|
||||
"--control-token" => {
|
||||
i += 1;
|
||||
parsed.control_token = args.get(i).cloned();
|
||||
}
|
||||
"--sample" => {
|
||||
i += 1;
|
||||
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
|
||||
}
|
||||
a if a.starts_with("-psn_") => {}
|
||||
a => parsed.files.push(a.to_string()),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
/// A nightly owns no control channel, and only options count: everything after `--` is a file, so a
|
||||
/// document named `--control` is opened rather than read as a flag.
|
||||
fn nightly_control_refused(nightly: bool, args: &[String]) -> bool {
|
||||
let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len());
|
||||
nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token")
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
// A confined launcher run (`gridcraft_sandbox::launch_command`) comes before everything else:
|
||||
// it opens no window, writes no log, and becomes the program it confines.
|
||||
// A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from
|
||||
// this same executable) comes before everything else: it opens no window, writes no log, and
|
||||
// becomes the program it confines. It must stay ahead of the launch profile, or a nightly build
|
||||
// would refuse its own sandbox helper.
|
||||
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
|
||||
std::process::exit(code);
|
||||
}
|
||||
// Then the Launcher protocol and the version query (see `prepare_launch`).
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
// A nightly profile owns its control tokens as well, so even a nightly build that is asked
|
||||
// for a control server can never write the stable app's token file.
|
||||
if let Some(root) = launch_profile::current().root() {
|
||||
match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
// First, so the panic hook and every start-up warning are recorded (`logging`).
|
||||
let logger = logging::install();
|
||||
// Commands catch their panics (`Session::execute`), but the default hook only prints to
|
||||
@@ -268,43 +436,34 @@ fn main() -> eframe::Result<()> {
|
||||
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("gridcraft: {report}\n"));
|
||||
}
|
||||
}));
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let args: Vec<String> = arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect();
|
||||
let nightly = gridcraft_ui_egui::channel::current() == gridcraft_ui_egui::channel::Channel::NightlyV1;
|
||||
// The restart helper a self-update spawns: it finishes the swap and relaunches, then exits.
|
||||
if let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
// A nightly has no updater, so it never runs this and never inherits a stable swap.
|
||||
if !nightly
|
||||
&& let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
{
|
||||
if let Err(e) = done {
|
||||
eprintln!("GridCraft update helper failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if args.iter().any(|a| a == "--version" || a == "-V") {
|
||||
println!("GridCraft {}", env!("CARGO_PKG_VERSION"));
|
||||
// Before `--` only: everything after it is a file, even one named `--version`.
|
||||
if arguments.iter().take_while(|a| *a != "--").any(|a| a == "--version" || a == "-V") {
|
||||
println!("GridCraft {}", gridcraft_ui_egui::channel::version());
|
||||
return Ok(());
|
||||
}
|
||||
let mut control_port: Option<u16> = std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
|
||||
let mut control_token: Option<String> = std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok();
|
||||
let mut sample: Option<String> = None;
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--control" => {
|
||||
i += 1;
|
||||
control_port = args.get(i).and_then(|p| p.parse().ok());
|
||||
}
|
||||
"--control-token" => {
|
||||
i += 1;
|
||||
control_token = args.get(i).cloned();
|
||||
}
|
||||
"--sample" => {
|
||||
i += 1;
|
||||
sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
|
||||
}
|
||||
a if a.starts_with("-psn_") => {}
|
||||
a => files.push(a.to_string()),
|
||||
}
|
||||
i += 1;
|
||||
// The control channel is a stable-only service: a nightly window owns no port, writes no
|
||||
// token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`.
|
||||
if nightly_control_refused(nightly, &args) {
|
||||
eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
|
||||
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
|
||||
let parsed = desktop_args(&args, control_port, control_token);
|
||||
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
|
||||
// The log file lives in the settings folder, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
// first. Runs without preferences (agents' test runs) log to standard error only, so they
|
||||
@@ -312,7 +471,9 @@ fn main() -> eframe::Result<()> {
|
||||
if let Some(logger) = logger {
|
||||
match log_dir().filter(|_| prefs_enabled()) {
|
||||
Some(dir) => match logger.attach_dir(&dir) {
|
||||
Ok(path) => log::info!("GridCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()),
|
||||
Ok(path) => {
|
||||
log::info!("{} {}, log file {}", gridcraft_ui_egui::channel::name(), gridcraft_ui_egui::channel::version(), path.display())
|
||||
}
|
||||
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
|
||||
Err(e) => log::warn!("no log file: {e}"),
|
||||
},
|
||||
@@ -327,14 +488,41 @@ fn main() -> eframe::Result<()> {
|
||||
}
|
||||
let mut app = SheetApp::new(session, services());
|
||||
app.watch_desktop_theme();
|
||||
app.start_update_check();
|
||||
let control_port = control_port;
|
||||
// The updater is a stable-only service: a nightly is installed, replaced and updated by the
|
||||
// Launcher, so it never checks for one, never prompts and never writes craft-update's state.
|
||||
if !nightly {
|
||||
app.start_update_check();
|
||||
}
|
||||
load_prefs(&mut app);
|
||||
// Stamp the startup workbook's author from the persisted user name.
|
||||
if app.session.documents().is_empty() {
|
||||
app.session.new_workbook();
|
||||
}
|
||||
app.after_engine(); // Show warnings from the sample.
|
||||
// Nightly session health: the record is written before the window exists and finished by
|
||||
// `on_exit`. A record left by an interrupted run is reported once, then cleared on the next
|
||||
// clean quit.
|
||||
let session_watch = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let mut nightly_notice_shown = false;
|
||||
match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("GRIDCRAFT_BUILT_VERSION")) {
|
||||
Ok((watch, unavailable)) => {
|
||||
if let Some(watch) = &watch
|
||||
&& watch.previous_unclean()
|
||||
{
|
||||
app.notice = Some(gridcraft_ui_egui::Notice {
|
||||
text: "The last GridCraft Nightly session did not finish cleanly. Your saved workbooks are as you left them; only unsaved changes are affected.".into(),
|
||||
kind: gridcraft_ui_egui::NoticeKind::Warning,
|
||||
action: None,
|
||||
});
|
||||
nightly_notice_shown = true;
|
||||
}
|
||||
if unavailable {
|
||||
log::warn!("this window shares a GridCraft Nightly profile another window owns; its exit is not recorded");
|
||||
}
|
||||
*session_watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = watch;
|
||||
}
|
||||
Err(error) => log::warn!("Nightly session state was not written: {error}"),
|
||||
}
|
||||
// Files named on the command line (a double-click on Windows and Linux) open as File › Open
|
||||
// opens them: a password-protected one asks for its password, and errors are shown, not
|
||||
// only logged. Each replaces the untouched blank Book1, as a file opened from Finder does.
|
||||
@@ -344,11 +532,16 @@ fn main() -> eframe::Result<()> {
|
||||
// Linux/BSD: Excel's layout — no window-manager title bar above ours; our title bar carries the
|
||||
// window controls. `GRIDCRAFT_SYSTEM_TITLEBAR=1` keeps the system frame.
|
||||
app.window_controls = cfg!(not(any(target_os = "macos", target_os = "windows"))) && std::env::var_os("GRIDCRAFT_SYSTEM_TITLEBAR").is_none();
|
||||
// The window carries its channel's name and OS app id: a nightly window is never mistaken for
|
||||
// the stable one by a dock, a window manager rule or the taskbar (Windows AUMID above). A
|
||||
// Flatpak package carries its own id instead, which is what its .desktop file and portal name.
|
||||
let window_app_id =
|
||||
std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| gridcraft_ui_egui::channel::app_id().to_string());
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_title("GridCraft")
|
||||
.with_title(gridcraft_ui_egui::channel::default_title())
|
||||
.with_inner_size([1440.0, 900.0])
|
||||
.with_min_inner_size([640.0, 420.0])
|
||||
.with_app_id("ai.storyteller.gridcraft")
|
||||
.with_app_id(window_app_id)
|
||||
.with_drag_and_drop(true)
|
||||
.with_decorations(!app.window_controls);
|
||||
if cfg!(target_os = "macos") {
|
||||
@@ -387,12 +580,13 @@ fn main() -> eframe::Result<()> {
|
||||
let pending = std::cell::Cell::new(Some(app));
|
||||
let run = |options: eframe::NativeOptions| {
|
||||
eframe::run_native(
|
||||
"GridCraft",
|
||||
gridcraft_ui_egui::channel::name(),
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
let Some(mut app) = pending.take() else {
|
||||
return Err("the app was already created".into());
|
||||
};
|
||||
gridcraft_ui_egui::framework::install(&cc.egui_ctx)?;
|
||||
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
|
||||
if let Some(port) = control_port {
|
||||
match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) {
|
||||
@@ -401,14 +595,16 @@ fn main() -> eframe::Result<()> {
|
||||
}
|
||||
}
|
||||
let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window());
|
||||
Ok(Box::new(App(
|
||||
Ok(Box::new(App {
|
||||
app,
|
||||
windows,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
menu: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events.connect(&cc.egui_ctx),
|
||||
)))
|
||||
apple_events: apple_events.connect(&cc.egui_ctx),
|
||||
nightly: session_watch.clone(),
|
||||
nightly_notice_shown,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
};
|
||||
@@ -416,7 +612,7 @@ fn main() -> eframe::Result<()> {
|
||||
// A graphics error before the app existed: start once more with the other backend (eframe
|
||||
// reuses its event loop for the second run). Errors after that, or from winit, are returned.
|
||||
#[cfg(target_os = "windows")]
|
||||
if let Err(eframe::Error::Wgpu(e)) = &result
|
||||
let result = if let Err(eframe::Error::Wgpu(e)) = &result
|
||||
&& let Some(app) = pending.take()
|
||||
&& let Some(backends) = graphics::fallback_backends(backend_override, first_backends)
|
||||
{
|
||||
@@ -424,8 +620,14 @@ fn main() -> eframe::Result<()> {
|
||||
pending.set(Some(app));
|
||||
let mut options = retry_options;
|
||||
graphics::configure_backends(&mut options, backends);
|
||||
return run(options);
|
||||
}
|
||||
run(options)
|
||||
} else {
|
||||
result
|
||||
};
|
||||
// A start that failed before the app existed never reached `on_exit`, and on the platforms
|
||||
// where the event loop returns this is also the end of a clean exit. `finish_once` makes the
|
||||
// second of the two calls a no-op, so a successor's record is never touched.
|
||||
nightly_session::finish_once(&session_watch, nightly_notice_shown);
|
||||
result
|
||||
}
|
||||
|
||||
@@ -457,3 +659,85 @@ mod packaging_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod launch_separator_tests {
|
||||
use super::*;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
|
||||
/// `craft_nightly::validate_and_prepare_root` refuses a root that is relative there, and a
|
||||
/// POSIX path has no drive or UNC prefix, so it is not absolute on Windows - where CI runs
|
||||
/// these tests too.
|
||||
fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
|
||||
}
|
||||
|
||||
/// The argv the Launcher starts a nightly with, extended by `tail`, as the start then reads it.
|
||||
fn launcher_argv(tail: &[&str]) -> Vec<String> {
|
||||
let mut argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
let launch = craft_nightly::parse_startup(
|
||||
BuildFlavor::NightlyV1,
|
||||
&profile_root::app_spec(),
|
||||
argv.iter().cloned(),
|
||||
&craft_nightly::StartupOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
launch_profile::restore_launcher_separator(&argv, launch.passthrough_args).iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_platforms_root_spelling_is_refused_as_relative() {
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
|
||||
let result = craft_nightly::validate_and_prepare_root(std::path::Path::new(foreign), &profile_root::app_spec());
|
||||
assert!(
|
||||
matches!(result, Err(craft_nightly::ProfileError::RelativeProfileRoot(_))),
|
||||
"a root that is not absolute on this platform must be refused"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launchers_separator_is_never_a_file() {
|
||||
let parsed = desktop_args(&launcher_argv(&[]), None, None);
|
||||
assert_eq!(parsed, DesktopArgs::default(), "the separator must not reach the file list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_after_the_separator_are_opened_in_order() {
|
||||
assert_eq!(desktop_args(&launcher_argv(&["a.file"]), None, None).files, ["a.file"]);
|
||||
let parsed = desktop_args(&launcher_argv(&["a.file", "--version", "--sample"]), None, None);
|
||||
assert_eq!(parsed.files, ["a.file", "--version", "--sample"], "after -- every word is a file");
|
||||
assert_eq!((parsed.sample, parsed.control_port), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_flag_after_the_separator_is_a_file_not_a_refusal() {
|
||||
let argv = launcher_argv(&["--control"]);
|
||||
assert!(!nightly_control_refused(true, &argv), "a document named --control must open, not refuse");
|
||||
let parsed = desktop_args(&argv, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_flag_before_the_separator_still_names_the_port() {
|
||||
let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()];
|
||||
assert!(nightly_control_refused(true, &with_file));
|
||||
let parsed = desktop_args(&with_file, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (Some(7979), vec!["a.file".to_string()]));
|
||||
let plain = vec!["--control".to_string(), "7979".to_string()];
|
||||
assert!(nightly_control_refused(true, &plain));
|
||||
let parsed = desktop_args(&plain, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (Some(7979), Vec::<String>::new()));
|
||||
assert!(!nightly_control_refused(false, &plain), "the stable app keeps its control channel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
//! App-private Nightly session health, not telemetry and not a Launcher protocol.
|
||||
//!
|
||||
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
|
||||
//! Dropping the guard does not clear the marker: only the app's controlled return path does, and
|
||||
//! on macOS that path is `on_exit` (a ⌘Q ends the process inside AppKit's terminate, after
|
||||
//! `on_exit`, so nothing after `eframe::run_native` runs there).
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const RECORD: &str = "nightly-session.json";
|
||||
const LEASE: &str = "nightly-session.lock";
|
||||
const MAX_METADATA_BYTES: usize = 256;
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace `path` with `bytes` without following a link at the destination: the temporary file is
|
||||
/// created exclusively beside it and renamed over it, so a planted link is replaced, not written
|
||||
/// through. `gridcraft_engine::io::write_file` does the same for workbooks; the session record is
|
||||
/// the app's own file and must not depend on the engine's script sandbox policy.
|
||||
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no file name"))?;
|
||||
let mut tmp_name = std::ffi::OsString::from(".");
|
||||
tmp_name.push(name);
|
||||
tmp_name.push(".new");
|
||||
let tmp = path.with_file_name(tmp_name);
|
||||
match std::fs::remove_file(&tmp) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let write = (|| -> io::Result<()> {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(&tmp)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
std::fs::rename(&tmp, path)
|
||||
})();
|
||||
if write.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
write
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook and the return path.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
|
||||
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
|
||||
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
if let Some(watch) = watch
|
||||
&& let Err(error) = watch.finish(unclean_notice_shown)
|
||||
{
|
||||
log::warn!("Nightly session state was left intact: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The warning belongs to this window: a busy secondary has no health-record coverage, while
|
||||
/// Stable and a lease-owning Nightly window preserve their existing result.
|
||||
pub fn begin_with_health(root: Option<&Path>, version: &str) -> io::Result<(Option<Self>, bool)> {
|
||||
let watch = Self::begin(root, version)?;
|
||||
let unavailable = root.is_some() && watch.is_none();
|
||||
Ok((watch, unavailable))
|
||||
}
|
||||
|
||||
/// `None` is stable, or another owner of this profile. Neither case touches the record.
|
||||
/// The supplied root must already be the validated private Nightly profile.
|
||||
pub fn begin(root: Option<&Path>, version: &str) -> io::Result<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
// The commit is read back from the version (`…g<sha12>`), never invented here.
|
||||
let commit = gridcraft_ui_egui::channel::commit_for(version);
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit,
|
||||
}))?;
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed it
|
||||
/// yet (a failed start before the app existed), the record is left for the next owner.
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// Clear the record this owner wrote, and only that one. An unwind, abort, forced exit or killed
|
||||
/// process never calls this.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("gridcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn version() -> &'static str {
|
||||
"0.19.1-nightly.20261124.7.1.gabcdef012345"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable").unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), version()).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unfinished = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
assert!(!unfinished.previous_unclean());
|
||||
drop(unfinished); // Abnormal-path ownership release, not a controlled completion.
|
||||
let next = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
|
||||
let fixture = Fixture::new();
|
||||
drop(Session::begin(Some(&fixture.0), version()).unwrap().unwrap());
|
||||
// The renderer failed before the app existed: no notice was shown.
|
||||
let failed = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The retry (or the next start) still sees the interruption and shows it.
|
||||
let retry = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
assert!(retry.previous_unclean());
|
||||
retry.finish(true).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
|
||||
let clean = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
assert!(!clean.previous_unclean());
|
||||
clean.finish(false).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
|
||||
let fixture = Fixture::new();
|
||||
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), version()).unwrap()));
|
||||
// The exit hook (macOS quit: the only path that runs there).
|
||||
finish_once(&shared, false);
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
|
||||
let successor = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
assert!(!successor.previous_unclean());
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
finish_once(&shared, false);
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
|
||||
successor.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
|
||||
assert!(watch.complete().is_err());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
|
||||
let fixture = Fixture::new();
|
||||
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1)).is_err());
|
||||
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
|
||||
assert!(Session::begin(None, "").unwrap().is_none(), "stable has no session-health side effects");
|
||||
let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(fields, ["channel", "commit", "schema_version", "version"].into_iter().collect());
|
||||
assert_eq!(data["commit"], "abcdef012345", "the commit comes from the version, not the environment");
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_without_a_commit_does_not_invent_one() {
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), "0.19.1").unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
assert!(data["commit"].is_null());
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn reserved_state_aliases_do_not_modify_external_files() {
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
for name in [LEASE, RECORD] {
|
||||
let alias = fixture.0.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), version()).is_err());
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn replacing_a_planted_record_link_writes_our_own_file_only() {
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap();
|
||||
// regular_or_missing refuses an alias outright; the temporary writer is what a first write
|
||||
// uses, and it never follows one either.
|
||||
assert!(Session::begin(Some(&fixture.0), version()).is_err());
|
||||
// The link is at RECORD itself: writing there must replace the alias, not follow it.
|
||||
atomic_write_no_follow(&fixture.0.join(RECORD), b"ours").unwrap();
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"ours");
|
||||
assert!(!fixture.0.join(RECORD).is_symlink(), "the alias must be replaced, not written through");
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
assert!(!fixture.0.join(".nightly-session.json.new").exists());
|
||||
}
|
||||
}
|
||||
+12
-10
@@ -1,15 +1,12 @@
|
||||
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
|
||||
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
|
||||
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
|
||||
|
||||
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
|
||||
pub fn discover() -> Discover {
|
||||
Box::new(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
|
||||
let printers = craft_print::printers()
|
||||
.into_iter()
|
||||
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
|
||||
.collect();
|
||||
let printers = craft_print::printers().into_iter().map(Printer::from).collect();
|
||||
let _ = sender.send(printers);
|
||||
});
|
||||
receiver
|
||||
@@ -34,12 +31,17 @@ pub fn submit() -> Submit {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
|
||||
let job = craft_print::Job {
|
||||
printer: Some(settings.printer),
|
||||
printer: match settings.destination {
|
||||
Destination::Printer(name) => Some(name),
|
||||
_ => None,
|
||||
},
|
||||
copies: settings.copies.clamp(1, 999),
|
||||
duplex: settings.duplex.map(|value| match value {
|
||||
Duplex::LongEdge => craft_print::Duplex::LongEdge,
|
||||
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
|
||||
Duplex::Off => craft_print::Duplex::Off,
|
||||
collate: settings.collate,
|
||||
duplex: settings.duplex.and_then(|value| match value {
|
||||
Duplex::LongEdge => Some(craft_print::Duplex::LongEdge),
|
||||
Duplex::ShortEdge => Some(craft_print::Duplex::ShortEdge),
|
||||
Duplex::Off => Some(craft_print::Duplex::Off),
|
||||
_ => None,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Set the immutable nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so the MSI's
|
||||
//! advertised shortcuts keep matching it.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct IdentityError(String);
|
||||
|
||||
impl std::fmt::Display for IdentityError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentityError {}
|
||||
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
|
||||
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_nightly_build_never_reaches_the_windows_api() {
|
||||
assert!(initialize(false, "nightly-id").is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! GridCraft's nightly profile specification and control-directory boundary, backed by
|
||||
//! `craft-nightly`. Every stable place a GridCraft build keeps user state or installs is fenced off
|
||||
//! so the two channels can never share a file.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
|
||||
pub const CONTROL_DIR: &str = "Control";
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 2] = [CONTROL_DIR, "logs"];
|
||||
|
||||
/// Returns GridCraft's `craft-nightly` isolation specification, preserving every stable data,
|
||||
/// token, Flatpak, and installer boundary.
|
||||
pub fn app_spec() -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: "gridcraft",
|
||||
display_name: "GridCraft",
|
||||
stable_dir_names: &["gridcraft", "GridCraft"],
|
||||
stable_package_id: gridcraft_ui_egui::channel::APP_ID,
|
||||
nightly_package_id: gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: &[],
|
||||
portable_markers: &[],
|
||||
folder_only_entries: &PROFILE_FOLDERS,
|
||||
extra_forbidden_roots: extra_forbidden_roots(|key| std::env::var_os(key)),
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
if path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir)) { Some(path) } else { None }
|
||||
}
|
||||
|
||||
/// Platform-specific stable install, token, Flatpak, and macOS state paths beyond the standard OS
|
||||
/// config/data/cache directories already fenced by `craft-nightly`.
|
||||
fn extra_forbidden_roots(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// `gridcraft_mcp`'s control-channel token folder and both MSI install folders
|
||||
// (`install-policy.wxi`).
|
||||
let mut roots = Vec::new();
|
||||
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
if let Some(profile) = non_empty_abs(&env, "USERPROFILE") {
|
||||
roots.push(profile.join(".gridcraft"));
|
||||
}
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let mut roots: Vec<PathBuf> = ["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].into_iter().map(PathBuf::from).collect();
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.gridcraft"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/Applications/GridCraft.app")];
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/ai.storyteller.gridcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.gridcraft.savedState"));
|
||||
roots.push(home.join("Applications/GridCraft.app"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
{
|
||||
let _ = env;
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible
|
||||
/// ancestor is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
match std::fs::symlink_metadata(&child) {
|
||||
Ok(metadata) if !metadata.file_type().is_dir() => {
|
||||
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
|
||||
/// `gridcraft_mcp` if a control server is ever started. Resolving it never creates anything.
|
||||
pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
|
||||
private_subdirectory(root, CONTROL_DIR, "control folder")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
|
||||
use super::{CONTROL_DIR, PROFILE_FOLDERS, app_spec, control_directory, extra_forbidden_roots};
|
||||
|
||||
struct TempDir {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("gridcraft-profile-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
Self { root }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_profile_preparation_does_not_start_with_stable() {
|
||||
let tmp = TempDir::new("file-root");
|
||||
let root = tmp.path().join("not-a-directory");
|
||||
std::fs::write(&root, b"an ordinary file").unwrap();
|
||||
let argv = craft_nightly::launch_arguments(&root, &[]);
|
||||
let result =
|
||||
craft_nightly::prepare_launch(craft_nightly::BuildFlavor::NightlyV1, &app_spec(), argv, &craft_nightly::StartupOptions::default());
|
||||
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
|
||||
assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_spec_preserves_gridcraft_identifiers_and_folder_entries() {
|
||||
let spec = app_spec();
|
||||
assert_eq!(spec.app_id, "gridcraft");
|
||||
assert_eq!(spec.display_name, "GridCraft");
|
||||
assert_eq!(spec.stable_dir_names, &["gridcraft", "GridCraft"]);
|
||||
assert_eq!(spec.stable_package_id, gridcraft_ui_egui::channel::APP_ID);
|
||||
assert_eq!(spec.nightly_package_id, gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert!(spec.forbidden_env_vars.is_empty());
|
||||
assert!(spec.portable_markers.is_empty());
|
||||
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_forbidden_roots_include_platform_install_and_state_paths() {
|
||||
let tmp = TempDir::new("extra-roots");
|
||||
let home = tmp.path().join("home");
|
||||
let local = tmp.path().join("local");
|
||||
let program_files = tmp.path().join("program-files");
|
||||
let env: BTreeMap<&str, OsString> = [
|
||||
("HOME", home.clone().into_os_string()),
|
||||
("USERPROFILE", home.clone().into_os_string()),
|
||||
("LOCALAPPDATA", local.clone().into_os_string()),
|
||||
("ProgramFiles", program_files.clone().into_os_string()),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let roots = extra_forbidden_roots(|key| env.get(key).cloned());
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(roots.contains(&local.join("Programs").join("ArtCraft").join("GridCraft")));
|
||||
assert!(roots.contains(&home.join(".gridcraft")));
|
||||
assert!(roots.contains(&program_files.join("ArtCraft").join("GridCraft")));
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/gridcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/gridcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/gridcraft")));
|
||||
assert!(roots.contains(&home.join(".var/app/ai.storyteller.gridcraft")));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.gridcraft.plist")));
|
||||
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.gridcraft.savedState")));
|
||||
assert!(roots.contains(&home.join("Applications/GridCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/GridCraft.app")));
|
||||
}
|
||||
let _ = (&local, &program_files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_entries() {
|
||||
let tmp = TempDir::new("reopen");
|
||||
let private = tmp.path().join("nightly-profile");
|
||||
let spec = app_spec();
|
||||
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
|
||||
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(
|
||||
matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
|
||||
"{name} must stay a directory"
|
||||
);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_forbidden_root_overlap_and_traversal_are_refused() {
|
||||
let tmp = TempDir::new("forbidden");
|
||||
let forbidden = tmp.path().join("stable-boundary");
|
||||
let mut spec = app_spec();
|
||||
spec.extra_forbidden_roots.push(forbidden.clone());
|
||||
|
||||
assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
assert!(matches!(validate_and_prepare_root(&forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
assert!(!forbidden.exists());
|
||||
|
||||
assert!(matches!(validate_and_prepare_root(Path::new("relative/profile"), &spec), Err(ProfileError::RelativeProfileRoot(_))));
|
||||
assert!(matches!(validate_and_prepare_root(&tmp.path().join("a/../b"), &spec), Err(ProfileError::ParentTraversalInProfileRoot(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_folder_is_a_private_lazy_subfolder() {
|
||||
let tmp = TempDir::new("control");
|
||||
let private = validate_and_prepare_root(&tmp.path().join("nightly-profile"), &app_spec()).unwrap();
|
||||
let control = control_directory(&private).unwrap();
|
||||
assert!(control.starts_with(&private) && control != private);
|
||||
assert!(!control.exists(), "resolving it must not create it");
|
||||
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
|
||||
let tmp = TempDir::new("control-symlink");
|
||||
let outside = tmp.path().join("shared-tokens");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let private = tmp.path().join("nightly-control");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
|
||||
|
||||
assert!(control_directory(&private).is_err());
|
||||
assert!(matches!(validate_and_prepare_root(&private, &app_spec()), Err(ProfileError::SymlinkEntry(_))));
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -50,3 +50,16 @@ ID and `packaging/linux/ai.storyteller.gridcraft.desktop`.
|
||||
|
||||
Edit `gridcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, and `iconutil` for the
|
||||
`.icns` (macOS only). It packs the `.ico` with `cargo xtask ico`.
|
||||
|
||||
## Nightly channel
|
||||
|
||||
The nightly (`nightly-v1`) derivatives keep the artwork, geometry and the Mac padding unchanged and
|
||||
change only the field colour: `#1f9d55` in the stable icon, `#14532d` in
|
||||
`gridcraft-nightly.svg`. There is no letter, badge or crescent; the app and the Launcher name the
|
||||
channel in text (`GridCraft Nightly`, the `ai.storyteller.gridcraft.nightly-v1` window id).
|
||||
|
||||
`gridcraft-nightly.svg` is the vector master. `packaging/nightly-icons.py` renders every frame from
|
||||
it at its own size (never an upscale) and packs the nine-frame ICO and the eleven-slot ICNS; it
|
||||
uses `resvg` when present, else a headless Chrome. Each output's SHA-256, the palette and the
|
||||
method are recorded in [`nightly-provenance.json`](nightly-provenance.json), and
|
||||
`python3 packaging/nightly-icons.py --check` verifies the committed files still match it.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 60 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,30 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<!-- GridCraft Nightly (nightly-v1) icon: the stable artwork with only its background contribution
|
||||
deepened. Foreground, geometry and alpha are unchanged; no badge, letter or crescent, so the
|
||||
channel reads from the app and the Launcher in text.
|
||||
Palette: ink #0b0b0c, paper #efe9dc, stable field #1f9d55
|
||||
(proposed), nightly field #14532d. -->
|
||||
<defs>
|
||||
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#tile)">
|
||||
<rect width="512" height="512" fill="#14532d"/>
|
||||
<g transform="rotate(-6 256 268)" stroke="#0b0b0c" stroke-linejoin="round" stroke-linecap="round">
|
||||
<!-- page with a folded top-right corner -->
|
||||
<path d="M112 76 H336 L404 144 V440 H112 Z" fill="#efe9dc" stroke-width="14"/>
|
||||
<path d="M336 76 V144 H404" fill="none" stroke-width="12"/>
|
||||
<!-- title lines -->
|
||||
<path d="M146 106 H272 M146 130 H232" stroke-width="12"/>
|
||||
<!-- header row and row-number column, in the app colour -->
|
||||
<path d="M112 164 H404 V204 H164 V440 H112 Z" fill="#14532d" stroke="none"/>
|
||||
<!-- grid -->
|
||||
<path d="M112 164 H404 M112 204 H404 M112 250 H404 M112 296 H404 M112 342 H404 M112 388 H404
|
||||
M164 164 V440 M244 164 V440 M324 164 V440" fill="none" stroke-width="8"/>
|
||||
<!-- the selected cell and its fill handle -->
|
||||
<rect x="244" y="250" width="80" height="46" fill="none" stroke-width="16"/>
|
||||
<rect x="312" y="284" width="24" height="24" fill="#0b0b0c" stroke="#efe9dc" stroke-width="5"/>
|
||||
<!-- double rule under the total -->
|
||||
<path d="M252 410 H316 M252 424 H316" stroke-width="7"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"title": "GridCraft nightly deep-background icons",
|
||||
"author": "@skylartaylor",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"inputs": [
|
||||
{
|
||||
"path": "assets/app-icon/gridcraft-nightly.svg",
|
||||
"sha256": "671748d45b785a840cf6ad062024c008e4704edc8925bed986dac2558438516b",
|
||||
"purpose": "vector master for every frame"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/gridcraft.svg",
|
||||
"sha256": "a4c55f2f52893b319862b610c006af83da9f097a4112b5a982b8ba95f43d2850",
|
||||
"purpose": "stable artwork this is derived from"
|
||||
}
|
||||
],
|
||||
"method": {
|
||||
"kind": "vector render of the project-owned artwork with only its field colour deepened",
|
||||
"stable_field": "#1f9d55",
|
||||
"nightly_field": "#14532d",
|
||||
"unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding",
|
||||
"sizes": "each frame rendered at its own size, never upscaled",
|
||||
"renderer": "chrome",
|
||||
"generator": "packaging/nightly-icons.py"
|
||||
},
|
||||
"outputs": {
|
||||
"gridcraft-nightly.png": "f06a2507dbd07c307d3b3e46eb2b7d849c29cc51f56114d61091d68d9d59e0d0",
|
||||
"gridcraft-nightly-1024.png": "914314b91dd214132bc017503d88197ca1537fab0de144a59cc65e03a03be400",
|
||||
"gridcraft-nightly.ico": "20cdb98a65c157f1db67800d439730b2c5dd564722d615d2b9483dc948f6e751",
|
||||
"gridcraft-nightly.icns": "e8fb90269660151b8ab1370bbd7194f5bae29888aa44959cf4c48110dcdebe9a"
|
||||
},
|
||||
"ico_frame_sizes": [
|
||||
16,
|
||||
20,
|
||||
24,
|
||||
32,
|
||||
40,
|
||||
48,
|
||||
64,
|
||||
128,
|
||||
256
|
||||
],
|
||||
"icns_png_slots": {
|
||||
"icp4": 16,
|
||||
"icp5": 32,
|
||||
"ic11": 32,
|
||||
"icp6": 64,
|
||||
"ic12": 64,
|
||||
"ic07": 128,
|
||||
"ic08": 256,
|
||||
"ic13": 256,
|
||||
"ic09": 512,
|
||||
"ic14": 512,
|
||||
"ic10": 1024
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,4 @@ disallowed-methods = [
|
||||
{ path = "std::time::SystemTime::now", reason = "traps on wasm; read the clock only off wasm" },
|
||||
]
|
||||
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -118,3 +118,9 @@ sync_github_name = true
|
||||
|
||||
[people.RockerHX]
|
||||
sync_github_name = true
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
|
||||
[people.alosslessdev]
|
||||
real_name = "Francisco Herrera"
|
||||
|
||||
+71
-8
@@ -18,7 +18,7 @@ mod lambda;
|
||||
mod reference_fns;
|
||||
mod special;
|
||||
|
||||
use array::map_unary;
|
||||
use array::{binary_scalar_snapped, map_unary};
|
||||
pub use array::{binary_values, zip2};
|
||||
pub use format::r1c1_to_a1;
|
||||
pub use special::{SPECIAL_FUNCTIONS, is_known_function, precedents, resized_sum_range};
|
||||
@@ -62,6 +62,28 @@ pub struct Lambda {
|
||||
pub env: Vec<(String, Ev)>,
|
||||
}
|
||||
|
||||
/// What the tail of a LAMBDA body came to.
|
||||
enum Tail {
|
||||
Done(Ev),
|
||||
/// A call to make in place of the current one, its arguments evaluated.
|
||||
Call(Arc<Lambda>, Vec<(String, Ev)>),
|
||||
}
|
||||
|
||||
/// A tail call can pass a closure that captures the previous one, thousands deep. Releasing the
|
||||
/// chain is a loop, not a recursion, so it cannot overflow the native stack.
|
||||
impl Drop for Lambda {
|
||||
fn drop(&mut self) {
|
||||
let mut pending = std::mem::take(&mut self.env);
|
||||
while let Some((_, ev)) = pending.pop() {
|
||||
if let Ev::L(l) = ev
|
||||
&& let Ok(mut inner) = Arc::try_unwrap(l)
|
||||
{
|
||||
pending.append(&mut inner.env);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Ev {
|
||||
V(Value),
|
||||
@@ -84,6 +106,11 @@ fn err(e: CellError) -> Ev {
|
||||
/// calls in progress, so it still runs.
|
||||
const MAX_LAMBDA_CALLS: usize = 140;
|
||||
|
||||
/// Tail calls one LAMBDA call may chain. They run in a loop on one native frame, so this only keeps
|
||||
/// an endless tail recursion finite. Excel computes a tail countdown to 5,459 and answers `#NUM!`
|
||||
/// for 5,460, which is 5,460 invocations in the chain.
|
||||
const MAX_TAIL_CALLS: usize = 5460;
|
||||
|
||||
/// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it,
|
||||
/// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames
|
||||
/// above the formula. A cell that another cell's formula computes on demand shares the budget of the
|
||||
@@ -305,6 +332,27 @@ impl<'h> Evaluator<'h> {
|
||||
self.deref(ev)
|
||||
}
|
||||
|
||||
/// Evaluates the root of a formula. Excel snaps a near-cancelling add or subtract to exactly 0
|
||||
/// only here (and in the last addition of a `SUM`), never inside parentheses, unary signs,
|
||||
/// `IF` branches or an inner step: `=A1-B1` is 0 over two numbers one ulp apart, `=(A1-B1)` is not.
|
||||
pub fn value_root(&mut self, e: &Expr) -> Value {
|
||||
match e {
|
||||
Expr::Binary(op @ (BinOp::Add | BinOp::Sub), a, b) => {
|
||||
// The root skips `eval`, so it must pass `eval`'s guards itself: a name that refers to
|
||||
// itself (directly or through cells) is bounded only by them.
|
||||
if let Err(x) = self.enter() {
|
||||
return Value::Error(x);
|
||||
}
|
||||
let x = self.value(a);
|
||||
let y = self.value(b);
|
||||
self.depth -= 1;
|
||||
let sys = self.host.workbook().date_system;
|
||||
zip2(&x, &y, |l, r| binary_scalar_snapped(*op, l, r, sys))
|
||||
}
|
||||
_ => self.value(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_sheet(&self, s: &SheetSel) -> Result<Vec<usize>, CellError> {
|
||||
let wb = self.host.workbook();
|
||||
match s {
|
||||
@@ -391,25 +439,34 @@ impl<'h> Evaluator<'h> {
|
||||
}
|
||||
|
||||
pub fn eval(&mut self, e: &Expr) -> Ev {
|
||||
if let Err(x) = self.enter() {
|
||||
return err(x);
|
||||
}
|
||||
let r = self.eval_inner(e);
|
||||
self.depth -= 1;
|
||||
r
|
||||
}
|
||||
|
||||
/// `eval`'s guards, shared with [`Self::value_root`]: the stack budget and the nesting depth.
|
||||
/// On `Ok` the depth is one level deeper, and the caller steps it back.
|
||||
fn enter(&mut self) -> Result<(), CellError> {
|
||||
let here = stack_position();
|
||||
if self.depth == 0 {
|
||||
self.stack_top = self.host.stack_top().unwrap_or(here);
|
||||
}
|
||||
if self.stack_top.abs_diff(here) > STACK_BUDGET {
|
||||
self.host.stack_exhausted();
|
||||
return err(CellError::Num);
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
if !self.spend(1) {
|
||||
return err(CellError::Calc);
|
||||
return Err(CellError::Calc);
|
||||
}
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
self.depth -= 1;
|
||||
return err(CellError::Num);
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let r = self.eval_inner(e);
|
||||
self.depth -= 1;
|
||||
r
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn eval_inner(&mut self, e: &Expr) -> Ev {
|
||||
@@ -491,7 +548,13 @@ impl<'h> Evaluator<'h> {
|
||||
let saved = self.sheet;
|
||||
// Unqualified references in a name refer to the scope sheet.
|
||||
self.sheet = scope;
|
||||
let r = self.eval(&expr);
|
||||
// A name's body is a formula of its own, so Excel snaps it by the root rule wherever
|
||||
// the name is used (name probe, observed on Windows Excel 16.0.20430). Only a
|
||||
// value-producing add or subtract needs it; any other body, a range included, stays as it is.
|
||||
let r = match &expr {
|
||||
Expr::Binary(BinOp::Add | BinOp::Sub, ..) => Ev::V(self.value_root(&expr)),
|
||||
_ => self.eval(&expr),
|
||||
};
|
||||
self.sheet = saved;
|
||||
r
|
||||
}
|
||||
|
||||
@@ -22,17 +22,32 @@ impl Agg {
|
||||
/// What a folded aggregate carries from one value to the next.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Acc {
|
||||
pub(super) sum: f64,
|
||||
/// The sum of every number but the last, left to right.
|
||||
sum: f64,
|
||||
/// The last number seen: `SUM` snaps only its last addition (see `gridcraft_core::arith::sum_snapped`).
|
||||
last: Option<f64>,
|
||||
pub(super) count: u64,
|
||||
}
|
||||
|
||||
impl Acc {
|
||||
pub(super) fn add(&mut self, n: f64) {
|
||||
if let Some(prev) = self.last.replace(n) {
|
||||
self.sum += prev;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold a precomputed range sum into an empty accumulator.
|
||||
pub(super) fn add_range_sum(&mut self, sum: f64, count: u64) {
|
||||
self.sum = sum;
|
||||
self.count = self.count.saturating_add(count);
|
||||
}
|
||||
|
||||
/// Takes a value found inside a reference: only numbers count. `Err` is an error value that
|
||||
/// ends `SUM` and `AVERAGE`; `COUNT` skips errors.
|
||||
pub(super) fn add_cell(&mut self, kind: Agg, v: &Value) -> Result<(), CellError> {
|
||||
match v {
|
||||
Value::Number(n) => {
|
||||
self.sum += n;
|
||||
self.add(*n);
|
||||
self.count = self.count.saturating_add(1);
|
||||
Ok(())
|
||||
}
|
||||
@@ -42,11 +57,12 @@ impl Acc {
|
||||
}
|
||||
|
||||
pub(super) fn finish(&self, kind: Agg) -> Value {
|
||||
let plain = self.sum + self.last.unwrap_or(0.0);
|
||||
match kind {
|
||||
Agg::Sum => Value::number(self.sum),
|
||||
Agg::Sum => Value::number(self.last.map_or(self.sum, |l| gridcraft_core::arith::snap_add(self.sum, l))),
|
||||
Agg::Count => Value::number(self.count as f64),
|
||||
Agg::Average if self.count == 0 => Value::Error(CellError::Div0),
|
||||
Agg::Average => Value::number(self.sum / self.count as f64),
|
||||
Agg::Average => Value::number(plain / self.count as f64),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,6 +188,17 @@ pub fn binary_values(op: BinOp, x: &Value, y: &Value, sys: gridcraft_core::DateS
|
||||
zip2(x, y, |a, b| binary_scalar(op, a, b, sys))
|
||||
}
|
||||
|
||||
/// `a + b` or `a - b` with Excel's snap to zero (see [`super::Evaluator::value_root`]).
|
||||
pub(super) fn binary_scalar_snapped(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSystem) -> Value {
|
||||
match (a, b) {
|
||||
(Value::Error(_), _) | (_, Value::Error(_)) => binary_scalar(op, a, b, sys),
|
||||
_ => match (a.to_number_in(sys), b.to_number_in(sys)) {
|
||||
(Ok(x), Ok(y)) => Value::number(gridcraft_core::arith::snap_add(x, if op == BinOp::Sub { -y } else { y })),
|
||||
(Err(e), _) | (_, Err(e)) => Value::Error(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `x & y` with at least one array operand, giving `#NUM!` once the texts built so far pass `budget`
|
||||
/// bytes.
|
||||
fn concat_arrays(x: &Value, y: &Value, sys: gridcraft_core::DateSystem, budget: usize) -> Value {
|
||||
@@ -216,13 +243,7 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste
|
||||
}
|
||||
}),
|
||||
BinOp::Concat => match (a.to_text(), b.to_text()) {
|
||||
(Ok(x), Ok(y)) => {
|
||||
if x.len() + y.len() > 32767 * 4 {
|
||||
Value::Error(CellError::Value)
|
||||
} else {
|
||||
Value::text(x + &y)
|
||||
}
|
||||
}
|
||||
(Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)),
|
||||
(Err(e), _) | (_, Err(e)) => Value::Error(e),
|
||||
},
|
||||
BinOp::Eq => Value::Bool(compare(a, b) == Equal),
|
||||
|
||||
@@ -5,6 +5,17 @@ use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, Lambda, Pip
|
||||
use std::sync::Arc;
|
||||
|
||||
impl<'h> Evaluator<'h> {
|
||||
/// `IF` with an array condition: element-wise.
|
||||
pub(super) fn if_elementwise(&mut self, arr: &Array, args: &[Expr]) -> Ev {
|
||||
let t = self.arg_val(args, 1).unwrap_or(Value::Bool(true));
|
||||
let f = if args.len() > 2 { self.arg_val(args, 2).unwrap_or(Value::Bool(false)) } else { Value::Bool(false) };
|
||||
Ev::V(zip3(arr, &t, &f, |c, t, f| match c.to_bool() {
|
||||
Ok(true) => t.clone(),
|
||||
Ok(false) => f.clone(),
|
||||
Err(e) => Value::Error(e),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn call(&mut self, name: &str, args: &[Expr]) -> Ev {
|
||||
match name {
|
||||
"IF" => self.if_call(args),
|
||||
@@ -402,13 +413,13 @@ impl<'h> Evaluator<'h> {
|
||||
/// Adds one area to `acc`; `Err` is the result the function ends with.
|
||||
fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> {
|
||||
if !a.range.is_single() {
|
||||
// Adding the block's remembered sum to anything but +0.0 would add in another order.
|
||||
// COUNT never reads the sum, so it may reuse every block.
|
||||
if (kind == Agg::Count || acc.sum.to_bits() == 0)
|
||||
&& let Some((sum, count)) = self.host.range_sum(a.sheet, a.range)
|
||||
// COUNT never reads the sum, so it may reuse every block's remembered count.
|
||||
// SUM and AVERAGE must walk so SUM can snap only its last addition (the remembered
|
||||
// block sum does not keep that last add).
|
||||
if kind == Agg::Count
|
||||
&& let Some((_sum, count)) = self.host.range_sum(a.sheet, a.range)
|
||||
{
|
||||
acc.sum = sum;
|
||||
acc.count = acc.count.saturating_add(count);
|
||||
acc.add_range_sum(0.0, count);
|
||||
return Ok(());
|
||||
}
|
||||
// Folded without building an array, but still walked: the part inside the used
|
||||
@@ -433,20 +444,21 @@ impl<'h> Evaluator<'h> {
|
||||
self.aggregate_value(kind, value, true, acc)
|
||||
}
|
||||
|
||||
/// Adds one argument's value by calling `SUM` and `COUNT` on it, so coercion and error rules
|
||||
/// stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`).
|
||||
/// Adds one argument's value with `SUM`'s numbers and a call to `COUNT`, so coercion and error
|
||||
/// rules stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`). The numbers
|
||||
/// are added one by one so `SUM` can snap only its last addition.
|
||||
fn aggregate_value(&mut self, kind: Agg, value: Value, from_ref: bool, acc: &mut Acc) -> Result<(), Ev> {
|
||||
if !from_ref && !self.spend_on(&value) {
|
||||
return Err(err(CellError::Calc));
|
||||
}
|
||||
let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), gridcraft_functions::lookup("COUNT")) else {
|
||||
let Some(count) = gridcraft_functions::lookup("COUNT") else {
|
||||
return Err(err(CellError::Name));
|
||||
};
|
||||
let args = [Arg { value, from_ref, blank_value: false }];
|
||||
if kind != Agg::Count {
|
||||
match gridcraft_functions::call(sum, &args, &mut FnCtx { ev: self, criteria: None, lambda: None }) {
|
||||
Value::Number(n) => acc.sum += n,
|
||||
other => return Err(Ev::V(other)),
|
||||
match gridcraft_functions::numbers(&args) {
|
||||
Ok(ns) => ns.into_iter().for_each(|n| acc.add(n)),
|
||||
Err(e) => return Err(err(e)),
|
||||
}
|
||||
}
|
||||
if kind != Agg::Sum {
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
use super::MAX_LAMBDA_CALLS;
|
||||
use super::array::{broadcast_len, single};
|
||||
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, Value, err};
|
||||
use super::special::is_special;
|
||||
use super::{Array, BinOp, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
|
||||
use std::sync::Arc;
|
||||
|
||||
impl<'h> Evaluator<'h> {
|
||||
pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev {
|
||||
match self.bind_args(l, args) {
|
||||
Ok(bound) => self.call_lambda_values(l, bound),
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments of a call to `l`, evaluated in the current scope.
|
||||
fn bind_args(&mut self, l: &Lambda, args: &[Expr]) -> Result<Vec<(String, Ev)>, Ev> {
|
||||
// Too many or too few argument positions is #VALUE!. An explicitly empty position, as in
|
||||
// `(1,)`, is `Expr::Missing` and still counts as a position (it binds as omitted). `f()`
|
||||
// parses to no arguments, which for a one-parameter lambda can also be read as one empty
|
||||
// position, so that call still binds the parameter as omitted.
|
||||
let positions_ok = args.len() == l.params.len() || (args.is_empty() && l.params.len() == 1);
|
||||
if !positions_ok {
|
||||
return err(CellError::Value);
|
||||
return Err(err(CellError::Value));
|
||||
}
|
||||
let mut bound = Vec::with_capacity(l.params.len());
|
||||
for (i, p) in l.params.iter().enumerate() {
|
||||
@@ -21,7 +30,56 @@ impl<'h> Evaluator<'h> {
|
||||
};
|
||||
bound.push((p.clone(), v));
|
||||
}
|
||||
self.call_lambda_values(l, bound)
|
||||
Ok(bound)
|
||||
}
|
||||
|
||||
/// Follows `e` through the positions whose value is the value of a LAMBDA call (`IF` branches,
|
||||
/// parentheses), and returns the call with its arguments evaluated instead of making it, so
|
||||
/// that `call_lambda_values` can loop. Anything else is evaluated here.
|
||||
fn tail_step(&mut self, e: &Expr) -> Tail {
|
||||
match e {
|
||||
Expr::Paren(x) => self.tail_step(x),
|
||||
Expr::Call(name, args) if name == "IF" && (2..=3).contains(&args.len()) => {
|
||||
let c = self.arg_val(args, 0).unwrap_or_default();
|
||||
if let Value::Array(arr) = &c {
|
||||
return Tail::Done(self.if_elementwise(arr, args));
|
||||
}
|
||||
match c.to_bool() {
|
||||
Ok(true) => self.tail_step_branch(args.get(1)),
|
||||
Ok(false) => match args.get(2) {
|
||||
Some(_) => self.tail_step_branch(args.get(2)),
|
||||
None => Tail::Done(Ev::V(Value::Bool(false))),
|
||||
},
|
||||
Err(x) => Tail::Done(err(x)),
|
||||
}
|
||||
}
|
||||
Expr::Call(name, args) if gridcraft_functions::lookup(name).is_none() && !is_special(name) => match self.name(name) {
|
||||
Ev::L(l) => self.tail_call(l, args),
|
||||
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
|
||||
_ => Tail::Done(err(CellError::Name)),
|
||||
},
|
||||
Expr::Invoke(callee, args) => match self.eval(callee) {
|
||||
Ev::L(l) => self.tail_call(l, args),
|
||||
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
|
||||
_ => Tail::Done(err(CellError::Value)),
|
||||
},
|
||||
_ => Tail::Done(self.eval(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// An `IF` branch; an omitted one (`IF(c,,1)`) is 0.
|
||||
fn tail_step_branch(&mut self, branch: Option<&Expr>) -> Tail {
|
||||
match branch {
|
||||
Some(Expr::Missing) | None => Tail::Done(Ev::V(Value::Number(0.0))),
|
||||
Some(b) => self.tail_step(b),
|
||||
}
|
||||
}
|
||||
|
||||
fn tail_call(&mut self, l: Arc<Lambda>, args: &[Expr]) -> Tail {
|
||||
match self.bind_args(&l, args) {
|
||||
Ok(bound) => Tail::Call(l, bound),
|
||||
Err(e) => Tail::Done(e),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev {
|
||||
@@ -38,7 +96,33 @@ impl<'h> Evaluator<'h> {
|
||||
self.calls += 1;
|
||||
let saved = std::mem::replace(&mut self.env, l.env.clone());
|
||||
self.env.extend(bound);
|
||||
let r = self.eval(&l.body);
|
||||
// A LAMBDA body is a formula of its own, so Excel snaps it by the root rule in every context
|
||||
// (named, inline, LET-bound, MAP, REDUCE, SCAN, MAKEARRAY, BYROW, BYCOL; LAMBDA probe, observed
|
||||
// on Windows Excel 16.0.20430). A LET, IF, parenthesis or unary sign at the root of the body does not.
|
||||
// A call in tail position replaces this one instead of nesting under it, so a tail recursion
|
||||
// uses no more native stack at 5,000 deep than at 5. Each link still spends fuel.
|
||||
let snap_root = |body: &Expr| matches!(body, Expr::Binary(BinOp::Add | BinOp::Sub, ..));
|
||||
let mut tails = 0;
|
||||
let mut step = if snap_root(&l.body) { Tail::Done(Ev::V(self.value_root(&l.body))) } else { self.tail_step(&l.body) };
|
||||
let r = loop {
|
||||
match step {
|
||||
Tail::Done(v) => break v,
|
||||
Tail::Call(next, bound) => {
|
||||
tails += 1;
|
||||
if tails >= MAX_TAIL_CALLS {
|
||||
break err(CellError::Num);
|
||||
}
|
||||
self.fuel = match self.fuel.checked_sub(1) {
|
||||
Some(f) => f,
|
||||
None => break err(CellError::Calc),
|
||||
};
|
||||
self.env.clear();
|
||||
self.env.extend(next.env.iter().cloned());
|
||||
self.env.extend(bound);
|
||||
step = if snap_root(&next.body) { Tail::Done(Ev::V(self.value_root(&next.body))) } else { self.tail_step(&next.body) };
|
||||
}
|
||||
}
|
||||
};
|
||||
self.env = saved;
|
||||
self.calls -= 1;
|
||||
r
|
||||
|
||||
@@ -195,7 +195,7 @@ impl Precedents<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_special(n: &str) -> bool {
|
||||
pub(super) fn is_special(n: &str) -> bool {
|
||||
matches!(
|
||||
n,
|
||||
"IF" | "IFS"
|
||||
|
||||
@@ -12,7 +12,7 @@ mod trimrange;
|
||||
|
||||
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
|
||||
pub use precision::DisplayedPrecision;
|
||||
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial};
|
||||
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, evaluate_expr, now_serial};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -718,7 +718,7 @@ impl Calc {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
|
||||
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing, array.data.len());
|
||||
if !blocked {
|
||||
for (o, r) in outranked {
|
||||
for c in r.iter() {
|
||||
@@ -785,6 +785,7 @@ fn spill_is_blocked(
|
||||
range: RangeRef,
|
||||
end: CellRef,
|
||||
standing: &Standing,
|
||||
array_len: usize,
|
||||
) -> bool {
|
||||
let outranked = |cell: CellRef| {
|
||||
sheet
|
||||
@@ -796,7 +797,7 @@ fn spill_is_blocked(
|
||||
|| end.col >= gridcraft_core::MAX_COLS
|
||||
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
|
||||
|| sheet.merges.iter().any(|merge| merge.intersects(&range))
|
||||
|| sheet.tables.iter().any(|table| table.range.contains(anchor.1))
|
||||
|| (array_len > 1 && sheet.tables.iter().any(|table| table.range.contains(anchor.1)))
|
||||
}
|
||||
|
||||
fn fill_spill(sheet: &mut gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, array: &Array) {
|
||||
@@ -824,11 +825,21 @@ pub fn evaluate(wb: &Workbook, sheet: usize, at: CellRef, formula: &str) -> Valu
|
||||
}
|
||||
|
||||
pub fn evaluate_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> Value {
|
||||
evaluate_expr_at(wb, sheet, at, expr, true)
|
||||
}
|
||||
|
||||
/// Like [`evaluate_expr`] for a sub-expression of a larger formula (Evaluate Formula's steps): Excel's
|
||||
/// snap to zero applies at a formula's root only, so an inner `A1-B1` keeps its IEEE residue.
|
||||
pub fn evaluate_inner_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> Value {
|
||||
evaluate_expr_at(wb, sheet, at, expr, false)
|
||||
}
|
||||
|
||||
fn evaluate_expr_at(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr, root: bool) -> Value {
|
||||
let exprs = HashMap::default();
|
||||
let mut rng = 0x1234_5678_9ABC_DEF0u64;
|
||||
let mut host = PassHost::new(wb, &exprs, &mut rng, now_serial());
|
||||
let mut ev = Evaluator::new(&mut host, sheet, at);
|
||||
ev.value(expr)
|
||||
if root { ev.value_root(expr) } else { ev.value(expr) }
|
||||
}
|
||||
|
||||
/// What [`evaluate_bounded`] found: the formula's reference (not read), its value, or that it ran
|
||||
|
||||
@@ -162,7 +162,8 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
|
||||
/// Whether an array result at `k` can't spill: it is in a table (a one-value result is shown
|
||||
/// there, as in Excel), or its area runs off the sheet,
|
||||
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
|
||||
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
|
||||
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
|
||||
@@ -188,7 +189,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
|
||||
end.row >= gridcraft_core::MAX_ROWS
|
||||
|| end.col >= gridcraft_core::MAX_COLS
|
||||
|| sh.merges.iter().any(|m| m.intersects(&range))
|
||||
|| sh.tables.iter().any(|t| t.range.contains(anchor))
|
||||
|| (a.data.len() > 1 && sh.tables.iter().any(|t| t.range.contains(anchor)))
|
||||
|| sh.cells.iter_range(range).any(|(c, cell)| c != anchor && (!cell.value.is_empty() || cell.formula.is_some()))
|
||||
|| sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c) && spilled_over(*c))
|
||||
}
|
||||
@@ -200,7 +201,7 @@ pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef,
|
||||
CellRef::new(anchor.row.saturating_add((arr.rows as u32).saturating_sub(1)), anchor.col.saturating_add((arr.cols as u32).saturating_sub(1)));
|
||||
RangeRef::new(anchor, end) == range
|
||||
&& !sheet.merges.iter().any(|m| m.intersects(&range))
|
||||
&& !sheet.tables.iter().any(|t| t.range.contains(anchor))
|
||||
&& (arr.data.len() <= 1 || !sheet.tables.iter().any(|t| t.range.contains(anchor)))
|
||||
&& range
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -331,7 +332,7 @@ impl PassHost<'_> {
|
||||
let outer_out_of_stack = std::mem::replace(&mut self.out_of_stack, false);
|
||||
let v = {
|
||||
let mut ev = Evaluator::new(self, k.0, k.1);
|
||||
ev.value(&expr)
|
||||
ev.value_root(&expr)
|
||||
};
|
||||
let out_of_stack = std::mem::replace(&mut self.out_of_stack, outer_out_of_stack);
|
||||
if out_of_stack && self.depth > 1 && self.suspend.is_none() {
|
||||
|
||||
+644
-7
@@ -820,6 +820,42 @@ fn arrays_do_not_spill_in_tables() {
|
||||
assert_eq!(t.num("E4"), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_value_array_in_a_table_is_not_a_spill() {
|
||||
// Excel shows a one-value dynamic-array result in a table column; two or more is #SPILL! (#2335).
|
||||
let table = |range: &str| gridcraft_model::Table {
|
||||
id: 1,
|
||||
name: "Table1".into(),
|
||||
range: gridcraft_core::RangeRef::parse(range).unwrap(),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![],
|
||||
style: String::new(),
|
||||
banded_rows: false,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: false,
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
};
|
||||
let mut t = T::new();
|
||||
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
|
||||
t.set("A1", "7");
|
||||
t.set("A2", "8");
|
||||
t.set("C4", "=FILTER(A1:A2,A1:A2>7)");
|
||||
t.set("C5", "=FILTER(A1:A2,A1:A2>0)");
|
||||
t.set("H4", "=FILTER(A1:A2,A1:A2>7)");
|
||||
t.set("D4", "=ROWS(C4#)");
|
||||
assert_eq!((t.num("C4"), t.num("H4"), t.num("D4")), (8.0, 8.0, 1.0));
|
||||
assert_eq!(t.get("C5"), Value::Error(CellError::Spill));
|
||||
// Recalculating again keeps the one-value result.
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.num("C4"), 8.0);
|
||||
assert_eq!(t.num("D4"), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ifs_and_lazy() {
|
||||
let mut t = T::new();
|
||||
@@ -1181,17 +1217,67 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() {
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
// F(F,n) has n + 1 calls in progress at its deepest; W adds one more call per step.
|
||||
// W's call to `f` is a tail call, so a wrapped call level costs one call in progress, not two. A tail call reuses its frame, so the tail chain is bounded by `MAX_TAIL_CALLS`, as in Excel
|
||||
// (5,459 ok, 5,460 #NUM!). F(F,n) otherwise has n + 1 calls in progress at its deepest; W adds
|
||||
// one more call per step.
|
||||
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
|
||||
let wrapped = |n: u32| format!("=LET(W,LAMBDA(f,k,f(f,k)),F,LAMBDA(me,n,IF(n<=0,0,1+W(me,n-1))),F(F,{n}))");
|
||||
[tail(139), tail(140), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
|
||||
[tail(5459), tail(5460), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("recursion must not overflow the stack")
|
||||
};
|
||||
let small = run(1 << 20);
|
||||
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]);
|
||||
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Number(70.0), Value::Number(131.0)]);
|
||||
assert_eq!(run(64 << 20), small);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tail_recursive_lambda_reaches_excels_depth_on_a_small_stack() {
|
||||
// Excel (measured): a tail countdown is 0 at 5,000 and 5,459 and #NUM! at 5,460 and 10,000.
|
||||
let run = |stack: usize| {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(stack)
|
||||
.spawn(|| {
|
||||
let mut wb = Workbook::new();
|
||||
wb.names.push(gridcraft_model::DefinedName {
|
||||
name: "TAILN".into(),
|
||||
scope: None,
|
||||
formula: "LAMBDA(n,IF(n=0,0,TAILN(n-1)))".into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
|
||||
// The same chain through parentheses and an applied lambda, and one that returns the base case's value.
|
||||
let paren = "=LET(F,LAMBDA(me,n,IF(n=0,7,(me(me,n-1)))),F(F,5000))".to_string();
|
||||
let invoke = "=LET(F,LAMBDA(me,n,IF(n=0,7,LAMBDA(a,b,me(me,a))(n-1,0))),F(F,2000))".to_string();
|
||||
let endless = "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))".to_string();
|
||||
// Each call passes a closure that captures the last, 5,000 deep: releasing them must not recurse.
|
||||
let closures = "=LET(F,LAMBDA(me,n,acc,IF(n=0,0,me(me,n-1,LAMBDA(x,acc)))),F(F,5000,0))".to_string();
|
||||
[tail(5000), tail(5459), tail(5460), tail(10000), paren, invoke, endless, "=TAILN(5000)".to_string(), closures]
|
||||
.map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("tail recursion must not overflow the stack")
|
||||
};
|
||||
let num = Value::Error(CellError::Num);
|
||||
let small = run(1 << 20);
|
||||
assert_eq!(
|
||||
small,
|
||||
[
|
||||
Value::Number(0.0),
|
||||
Value::Number(0.0),
|
||||
num.clone(),
|
||||
num.clone(),
|
||||
Value::Number(7.0),
|
||||
Value::Number(7.0),
|
||||
num,
|
||||
Value::Number(0.0),
|
||||
Value::Number(0.0)
|
||||
]
|
||||
);
|
||||
assert_eq!(run(64 << 20), small);
|
||||
}
|
||||
|
||||
@@ -1632,6 +1718,478 @@ fn sumif_resized_sum_range_on_another_sheet_and_through_a_name() {
|
||||
assert_eq!(t.num("C2"), 5.0);
|
||||
}
|
||||
|
||||
// ---- Excel's snap to zero (observed on Windows Excel 16.0.20430; suite rows cancel-ulps, cancel-band, decimal-sum, excel-probe) ----
|
||||
|
||||
impl T {
|
||||
/// Stores an exact double, bypassing input parsing.
|
||||
fn put(&mut self, at: &str, x: f64) {
|
||||
self.wb.sheet_mut(0).unwrap().cells.set(c(at), Cell::value(Value::Number(x)));
|
||||
self.calc.cells_changed(&mut self.wb, &[(0, c(at))]);
|
||||
}
|
||||
}
|
||||
|
||||
const ULP1: f64 = f64::EPSILON; // the spacing of doubles just above 1.0
|
||||
|
||||
#[test]
|
||||
fn a_bare_root_add_or_sub_snaps_a_near_cancellation_to_zero() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1); // one ulp apart: Excel shows 0, not -2.22e-16
|
||||
t.set("C1", "=A1-B1");
|
||||
t.set("C2", "=B1-A1");
|
||||
t.set("C3", "=A1+-B1");
|
||||
t.set("C4", "=0+A1-B1"); // the end of =0+A-B snaps too
|
||||
t.set("C5", "=SUM(A1,-B1)*1"); // the last addition of a SUM snaps even when SUM isn't the root
|
||||
t.put("D1", -(1.0 + ULP1));
|
||||
t.set("C6", "=SUM(A1,D1)");
|
||||
t.set("C7", "=A1+D1");
|
||||
for at in ["C1", "C2", "C3", "C4", "C5", "C6", "C7"] {
|
||||
assert_eq!(t.get(at), Value::Number(0.0), "{at}");
|
||||
}
|
||||
// The classic: 0.1+0.2-0.3 is 0 in Excel (5.55e-17 in IEEE).
|
||||
t.put("E1", 0.1);
|
||||
t.put("E2", 0.2);
|
||||
t.put("E3", 0.3);
|
||||
t.set("E4", "=E1+E2-E3");
|
||||
assert_eq!(t.get("E4"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_snaps_its_last_addition_when_it_folds_a_range_in_place() {
|
||||
// SUM, COUNT and AVERAGE fold ranges over the stored cells instead of calling SUM; the fold must
|
||||
// keep SUM's rule: only the last number added snaps, and a blank cell adds no number.
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("A2", -(1.0 + ULP1));
|
||||
t.set("C1", "=SUM(A1:A2)");
|
||||
t.set("C2", "=SUM(A1:A2,Z9)");
|
||||
t.set("C3", "=SUM(A1:A2,0)"); // the last addition is residue + 0: no snap
|
||||
t.set("C4", "=AVERAGE(A1:A2)"); // AVERAGE does not snap
|
||||
assert_eq!(t.get("C1"), Value::Number(0.0));
|
||||
assert_eq!(t.get("C2"), Value::Number(0.0));
|
||||
assert_eq!(t.get("C3"), Value::Number(-ULP1));
|
||||
assert_eq!(t.get("C4"), Value::Number(-ULP1 / 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_threshold_is_two_to_the_e_minus_49_of_the_left_operand() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
// 7 ulps below the threshold of 8 ulps (2^-49): snaps. Exactly 8: does not.
|
||||
t.put("B1", 1.0 + 7.0 * ULP1);
|
||||
t.put("B2", 1.0 + 8.0 * ULP1);
|
||||
t.set("C1", "=A1-B1");
|
||||
t.set("C2", "=A1-B2");
|
||||
assert_eq!(t.get("C1"), Value::Number(0.0));
|
||||
assert_eq!(t.get("C2"), Value::Number(-8.0 * ULP1));
|
||||
// The binade is the LEFT operand's (observed on Windows Excel 16.0.20430, excel-probe-4.00044 to 00046).
|
||||
t.put("A3", 0.4999999999999998);
|
||||
t.put("B3", 0.5000000000000002);
|
||||
t.set("C3", "=A3-B3");
|
||||
t.set("C4", "=B3-A3");
|
||||
assert_eq!(t.get("C3"), Value::Number(-4.440892098500626e-16));
|
||||
assert_eq!(t.get("C4"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_does_not_apply_inside_parentheses_unary_if_or_inner_steps() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
let residue = 1.0 - (1.0 + ULP1);
|
||||
for (at, f) in [
|
||||
("C1", "=(A1-B1)"),
|
||||
("C2", "=+(A1-B1)"),
|
||||
("C3", "=-(B1-A1)"),
|
||||
("C4", "=IF(TRUE,A1-B1)"),
|
||||
("C5", "=A1-B1+0"), // the root is the +0; the inner subtraction is not a root
|
||||
("C6", "=SUM(A1,-B1,0)"), // the last addition is residue+0
|
||||
] {
|
||||
t.set(at, f);
|
||||
assert_eq!(t.get(at), Value::Number(residue), "{f}");
|
||||
}
|
||||
// Observed on Windows Excel 16.0.20430: =SUM(A-B) does not snap (the subtraction is an inner step, the SUM's
|
||||
// last addition is residue + 0), and neither does a root that adds a zero.
|
||||
t.set("C7", "=SUM(A1-B1)");
|
||||
t.set("C8", "=A1-B1-0");
|
||||
assert_eq!(t.get("C7"), Value::Number(residue));
|
||||
assert_eq!(t.get("C8"), Value::Number(residue));
|
||||
// Only the LAST addition of a SUM snaps: 3+1e16-1e16 is 4, not 0.
|
||||
t.put("D1", 3.0);
|
||||
t.put("D2", 1e16);
|
||||
t.put("D3", -1e16);
|
||||
t.put("D4", 0.0);
|
||||
t.set("E1", "=SUM(D1:D4)");
|
||||
assert_eq!(t.get("E1"), Value::Number(4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_sign_and_exact_arithmetic_never_snap() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1e-20);
|
||||
t.put("B1", 2e-20);
|
||||
t.set("C1", "=A1+B1"); // a tiny sum of small numbers is not a cancellation
|
||||
t.set("C2", "=A1-B1");
|
||||
t.put("A2", 3.0);
|
||||
t.put("B2", 2.0);
|
||||
t.set("C3", "=A2-B2");
|
||||
assert_eq!(t.num("C1"), 1e-20 + 2e-20);
|
||||
assert_eq!(t.num("C2"), 1e-20 - 2e-20);
|
||||
assert_eq!(t.num("C3"), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_threshold_follows_the_left_operand_across_a_binade_boundary() {
|
||||
// Observed on Windows Excel 16.0.20430, snap probe rows 226, 231 and 236 (=A-B, A just below 1.0): the
|
||||
// threshold is 2^-50 (A's binade), not 2^-49 (B's), so 7.8e-16 snaps and 9.99e-16 does not.
|
||||
let mut t = T::new();
|
||||
t.put("A1", 0.9999999999999999);
|
||||
t.put("B1", 1.0000000000000004);
|
||||
t.put("B2", 1.0000000000000007);
|
||||
t.put("B3", 1.0000000000000009);
|
||||
t.set("D1", "=A1-B1");
|
||||
t.set("D2", "=A1-B2");
|
||||
t.set("D3", "=A1-B3");
|
||||
assert_eq!(t.get("D1"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D2"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D3"), Value::Number(-9.992007221626409e-16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_leaves_error_and_text_operands_alone() {
|
||||
let mut t = T::new();
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
t.set("A1", "=1/0");
|
||||
t.set("C1", "=A1-B1");
|
||||
assert_eq!(t.get("C1"), Value::Error(CellError::Div0));
|
||||
t.set("A2", "abc");
|
||||
t.set("C2", "=A2-B1");
|
||||
assert_eq!(t.get("C2"), Value::Error(CellError::Value));
|
||||
t.set("A3", "1"); // numeric text still converts, then the subtraction snaps like any other
|
||||
t.put("B3", 1.0);
|
||||
t.set("C3", "=A3-B3");
|
||||
assert_eq!(t.get("C3"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
// ---- the snap in a defined name's body (observed on Windows Excel 16.0.20430, name probe: 8 bodies x 12 positions) ----
|
||||
|
||||
impl T {
|
||||
fn name(&mut self, name: &str, body: &str) {
|
||||
self.wb.names.push(gridcraft_model::DefinedName {
|
||||
name: name.into(),
|
||||
scope: None,
|
||||
formula: body.into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_defined_name_is_a_formula_of_its_own_so_its_body_snaps_wherever_it_is_used() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
// (body, does Excel snap it?) Only the shape of the BODY matters, not where the name is used.
|
||||
let bodies = [
|
||||
("N_sub", "Sheet1!$A$1-Sheet1!$B$1", true),
|
||||
("N_par", "(Sheet1!$A$1-Sheet1!$B$1)", false),
|
||||
("N_plus0", "Sheet1!$A$1-Sheet1!$B$1+0", false),
|
||||
("N_sum", "SUM(Sheet1!$A$1,-Sheet1!$B$1)", true),
|
||||
("N_neg", "-(Sheet1!$B$1-Sheet1!$A$1)", false),
|
||||
("N_ref", "N_sub", true), // a name that is a name inherits it
|
||||
("N_if", "IF(TRUE,Sheet1!$A$1-Sheet1!$B$1)", false),
|
||||
("N_sumsub", "SUM(Sheet1!$A$1-Sheet1!$B$1)", false),
|
||||
];
|
||||
for (name, body, _) in bodies {
|
||||
t.name(name, body);
|
||||
}
|
||||
// All 12 positions of the Excel probe.
|
||||
let uses = ["{n}", "{n}*1", "{n}+0", "0+{n}", "({n})", "-{n}", "+{n}", "SUM({n})", "IF(TRUE,{n})", "ABS({n})", "1*{n}", "{n}-0"];
|
||||
let mut row = 2;
|
||||
for (name, body, snaps) in bodies {
|
||||
for u in uses {
|
||||
let at = format!("D{row}");
|
||||
t.set(&at, &format!("={}", u.replace("{n}", name)));
|
||||
// Every body is -1 ulp (A1-B1) or exactly 0; a minus sign or ABS flips the residue.
|
||||
let flips = u.starts_with('-') || u.starts_with("ABS");
|
||||
let want = if snaps {
|
||||
0.0
|
||||
} else if flips {
|
||||
ULP1
|
||||
} else {
|
||||
-ULP1
|
||||
};
|
||||
assert_eq!(t.get(&at), Value::Number(want), "{u} over {name} = {body}");
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excels_own_gap_shapes_from_lookup_shapes_xlsx() {
|
||||
// excel-evidence/request-3/files/lookup-shapes.xlsx, Sheet1!H15:H26: the gaps of 1, 4 and 7 ulps
|
||||
// snap to 0 as =Gap, =Gap*1 and =Gap+0; the gap of 8 ulps keeps its residue.
|
||||
let mut t = T::new();
|
||||
for (cell, v) in [("A1", 1.0000000000000002), ("A2", 1.0000000000000009), ("A3", 1.0000000000000016), ("A4", 1.0000000000000018)] {
|
||||
t.put(cell, v);
|
||||
}
|
||||
for (cell, v) in [("B1", 1.0), ("B2", 1.0), ("B3", 1.0), ("B4", 1.0)] {
|
||||
t.put(cell, v);
|
||||
}
|
||||
for (name, row) in [("Gap_1", 1), ("Gap_4", 2), ("Gap_7", 3), ("Gap_8", 4)] {
|
||||
t.name(name, &format!("Sheet1!$A${row}-Sheet1!$B${row}"));
|
||||
}
|
||||
let mut r = 10;
|
||||
for (name, residue) in [("Gap_1", 0.0), ("Gap_4", 0.0), ("Gap_7", 0.0), ("Gap_8", 1.7763568394002505e-15)] {
|
||||
for f in ["{n}", "{n}*1", "{n}+0"] {
|
||||
let at = format!("F{r}");
|
||||
t.set(&at, &format!("={}", f.replace("{n}", name)));
|
||||
assert_eq!(t.get(&at), Value::Number(residue), "{f} over {name}");
|
||||
r += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_refers_to_a_range_still_refers_to_it() {
|
||||
// Only a reference answers these: ISREF, ROW and OFFSET over a name. Wrapping every name
|
||||
// body in value_root would turn the range into an array and fail all three.
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("A2", 2.0);
|
||||
t.put("B1", 3.0);
|
||||
t.put("B2", 4.0);
|
||||
t.name("Block", "Sheet1!$A$1:$B$2");
|
||||
t.set("D1", "=ISREF(Block)");
|
||||
t.set("D2", "=MIN(ROW(Block))");
|
||||
t.set("D3", "=SUM(OFFSET(Block,0,1))");
|
||||
assert_eq!(t.get("D1"), Value::Bool(true));
|
||||
assert_eq!(t.num("D2"), 1.0);
|
||||
assert_eq!(t.num("D3"), 7.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_whose_body_is_an_array_difference_snaps_element_wise() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): INDEX(Arr,1)*1 and INDEX(Arr,2)*1 are 0 for Arr = A1:A2-B1:B2.
|
||||
let mut t = T::new();
|
||||
for (a, b) in [("A1", "B1"), ("A2", "B2")] {
|
||||
t.put(a, 1.0);
|
||||
t.put(b, 1.0 + ULP1);
|
||||
}
|
||||
t.name("Arr", "Sheet1!$A$1:$A$2-Sheet1!$B$1:$B$2");
|
||||
t.set("D1", "=INDEX(Arr,1)*1");
|
||||
t.set("D2", "=INDEX(Arr,2)*1");
|
||||
t.set("D3", "=SUM(Arr)");
|
||||
assert_eq!((t.get("D1"), t.get("D2")), (Value::Number(0.0), Value::Number(0.0)));
|
||||
assert_eq!(t.get("D3"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_scoped_name_snaps_on_its_own_sheet() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): a sheet-scoped Loc = S2!$A$1-S2!$B$1 gives 0 as =S2!Loc*1.
|
||||
let mut t = T::new();
|
||||
t.wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("S2")));
|
||||
t.wb.sheet_mut(1).unwrap().cells.set(c("A1"), Cell::value(Value::Number(1.0)));
|
||||
t.wb.sheet_mut(1).unwrap().cells.set(c("B1"), Cell::value(Value::Number(1.0 + ULP1)));
|
||||
t.wb.names.push(gridcraft_model::DefinedName {
|
||||
name: "Loc".into(),
|
||||
scope: Some(1),
|
||||
formula: "S2!$A$1-S2!$B$1".into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
t.set("D1", "=S2!Loc*1");
|
||||
t.set("D2", "=S2!Loc");
|
||||
assert_eq!((t.get("D1"), t.get("D2")), (Value::Number(0.0), Value::Number(0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_names_stay_bounded_and_cost_the_same_depth_as_before_the_snap() {
|
||||
let mut t = T::new();
|
||||
// A name that refers to itself ends in the depth limit's #NUM!, not a stack overflow.
|
||||
t.name("Rec", "Rec-1");
|
||||
t.set("A1", "=Rec");
|
||||
assert_eq!(t.get("A1"), Value::Error(CellError::Num));
|
||||
// A long chain of names, each one `-0` over the last, runs out of depth at the same place as it did
|
||||
// before names were snapped (value_root must charge its own level, or each link would be cheaper
|
||||
// and a chain through cells could overflow the stack).
|
||||
t.name("Nm_0", "1");
|
||||
for i in 1..=250 {
|
||||
t.name(&format!("Nm_{i}"), &format!("Nm_{}-0", i - 1));
|
||||
}
|
||||
t.set("A2", "=Nm_250");
|
||||
assert_eq!(t.get("A2"), Value::Error(CellError::Num));
|
||||
t.set("A3", "=Nm_20");
|
||||
assert_eq!(t.get("A3"), Value::Number(1.0));
|
||||
}
|
||||
|
||||
// ---- the snap in a LAMBDA body (observed on Windows Excel 16.0.20430, LAMBDA probe: 126 formulas) ----
|
||||
// A LAMBDA body is a formula of its own, like a defined name's: Excel snaps it by the root rule in every
|
||||
// context (named, inline, LET-bound, and under MAP, REDUCE, SCAN, MAKEARRAY, BYROW and BYCOL).
|
||||
|
||||
fn lambda_t() -> T {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
t.put("A2", 1.0 + ULP1);
|
||||
t.put("B2", 1.0 + ULP1);
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_body_snaps_by_its_own_root_wherever_the_lambda_is_called() {
|
||||
let mut t = lambda_t();
|
||||
// (name, body, does Excel snap it?)
|
||||
let lambdas = [
|
||||
("L_sub", "LAMBDA(x,y,x-y)", true),
|
||||
("L_par", "LAMBDA(x,y,(x-y))", false),
|
||||
("L_plus0", "LAMBDA(x,y,x-y+0)", false),
|
||||
("L_sum", "LAMBDA(x,y,SUM(x,-y))", true),
|
||||
("L_neg", "LAMBDA(x,y,-(y-x))", false),
|
||||
("L_if", "LAMBDA(x,y,IF(TRUE,x-y))", false),
|
||||
("L_sumsub", "LAMBDA(x,y,SUM(x-y))", false),
|
||||
("L_let", "LAMBDA(x,y,LET(d,x-y,d))", false), // a LET inside the body does not snap
|
||||
("L_letroot", "LAMBDA(x,y,LET(a,x,a-y))", false),
|
||||
("L_ref", "LAMBDA(x,y,L_sub(x,y))", true), // a lambda that calls one inherits it
|
||||
];
|
||||
for (name, body, _) in lambdas {
|
||||
t.name(name, body);
|
||||
}
|
||||
let uses = ["{c}", "{c}*1", "{c}+0", "0+{c}", "({c})", "-{c}", "SUM({c})", "IF(TRUE,{c})", "ABS({c})"];
|
||||
let mut row = 5;
|
||||
for (name, body, snaps) in lambdas {
|
||||
for u in uses {
|
||||
let at = format!("D{row}");
|
||||
t.set(&at, &format!("={}", u.replace("{c}", &format!("{name}(Sheet1!$A$1,Sheet1!$B$1)"))));
|
||||
let flips = u.starts_with('-') || u.starts_with("ABS");
|
||||
let want = if snaps {
|
||||
0.0
|
||||
} else if flips {
|
||||
ULP1
|
||||
} else {
|
||||
-ULP1
|
||||
};
|
||||
assert_eq!(t.get(&at), Value::Number(want), "{u} over {name} = {body}");
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_and_let_bound_lambdas_snap_the_same_way() {
|
||||
let mut t = lambda_t();
|
||||
for (i, (f, snaps)) in [
|
||||
("LAMBDA(x,y,x-y)(Sheet1!$A$1,Sheet1!$B$1)", true),
|
||||
("LAMBDA(x,y,x-y)(Sheet1!$A$1,Sheet1!$B$1)*1", true),
|
||||
("LAMBDA(x,y,(x-y))(Sheet1!$A$1,Sheet1!$B$1)", false),
|
||||
("LAMBDA(x,y,x-y+0)(Sheet1!$A$1,Sheet1!$B$1)", false),
|
||||
("LAMBDA(x,y,SUM(x,-y))(Sheet1!$A$1,Sheet1!$B$1)", true),
|
||||
("LET(f,LAMBDA(x,y,x-y),f(Sheet1!$A$1,Sheet1!$B$1))", true),
|
||||
("LET(f,LAMBDA(x,y,x-y),f(Sheet1!$A$1,Sheet1!$B$1))*1", true),
|
||||
("LET(f,LAMBDA(x,y,(x-y)),f(Sheet1!$A$1,Sheet1!$B$1))", false),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let at = format!("D{}", i + 5);
|
||||
t.set(&at, &format!("={f}"));
|
||||
assert_eq!(t.get(&at), Value::Number(if snaps { 0.0 } else { -ULP1 }), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_order_functions_snap_their_lambda_body() {
|
||||
let mut t = lambda_t();
|
||||
// The cell is INDEX(<result>,1,1), bare and times 1. A is (1, 1+ulp), B is (1+ulp, 1+ulp).
|
||||
let cases = [
|
||||
("MAP(Sheet1!$A$1:$A$2,Sheet1!$B$1:$B$2,LAMBDA(x,y,{b}))", "x-y"),
|
||||
("REDUCE(Sheet1!$A$1,Sheet1!$B$1,LAMBDA(x,y,{b}))", "x-y"),
|
||||
("SCAN(Sheet1!$A$1,Sheet1!$B$1:$B$2,LAMBDA(x,y,{b}))", "x-y"),
|
||||
("MAKEARRAY(1,1,LAMBDA(x,y,{b}))", "Sheet1!$A$1-Sheet1!$B$1"),
|
||||
("BYROW(Sheet1!$A$1:$B$2,LAMBDA(r,{b}))", "INDEX(r,1,1)-INDEX(r,1,2)"),
|
||||
("BYCOL(Sheet1!$A$1:$B$2,LAMBDA(r,{b}))", "INDEX(r,1,1)-INDEX(r,2,1)"),
|
||||
];
|
||||
let mut row = 5;
|
||||
for (f, bare) in cases {
|
||||
for (b, snaps) in [(bare.to_string(), true), (format!("({bare})"), false)] {
|
||||
for u in ["INDEX({c},1,1)", "INDEX({c},1,1)*1"] {
|
||||
let at = format!("D{row}");
|
||||
let formula = u.replace("{c}", &f.replace("{b}", &b));
|
||||
t.set(&at, &format!("={formula}"));
|
||||
assert_eq!(t.get(&at), Value::Number(if snaps { 0.0 } else { -ULP1 }), "{formula}");
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_body_that_returns_a_reference_still_returns_one() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): a body that returns a reference is still a reference, so only an
|
||||
// add or subtract root takes the snapping path. ISREF and OFFSET need the reference; wrapping every
|
||||
// body in value_root would turn it into a value.
|
||||
let mut t = lambda_t();
|
||||
t.set("D5", "=ISREF(LAMBDA(x,x)(Sheet1!$A$1))");
|
||||
t.set("D6", "=ISREF(LAMBDA(x,IF(TRUE,x))(Sheet1!$A$1))");
|
||||
t.set("D7", "=ROW(LAMBDA(x,OFFSET(x,1,0))(Sheet1!$A$1))");
|
||||
assert_eq!(t.get("D5"), Value::Bool(true));
|
||||
assert_eq!(t.get("D6"), Value::Bool(true));
|
||||
assert_eq!(t.num("D7"), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_curried_and_closed_over_lambda_bodies_snap_by_the_root_of_the_inner_body() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): each of these is exactly 0.
|
||||
let mut t = lambda_t();
|
||||
for (i, f) in [
|
||||
"LAMBDA(x,LAMBDA(y,x-y))(Sheet1!$A$1)(Sheet1!$B$1)", // curried
|
||||
"LAMBDA(x,y,LAMBDA(p,q,p-q)(x,y))(Sheet1!$A$1,Sheet1!$B$1)", // a body that calls an inner lambda
|
||||
"LAMBDA(x,y,0+x-y)(Sheet1!$A$1,Sheet1!$B$1)", // the end of 0+x-y snaps like =0+A-B
|
||||
"LET(a,Sheet1!$A$1,LAMBDA(y,a-y)(Sheet1!$B$1))", // a closure over a LET variable
|
||||
"LAMBDA(x,y,x-y)(Sheet1!$A$1+0,Sheet1!$B$1+0)",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let at = format!("D{}", i + 5);
|
||||
t.set(&at, &format!("={f}"));
|
||||
assert_eq!(t.get(&at), Value::Number(0.0), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_body_uses_the_same_threshold_and_snaps_array_arguments_element_wise() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): 7 ulps snap, 8 ulps keep the residue, inside a body as in a cell.
|
||||
let mut t = lambda_t();
|
||||
t.put("G1", 1.0);
|
||||
t.put("G2", 1.0 + 7.0 * ULP1);
|
||||
t.put("G3", 1.0 + 8.0 * ULP1);
|
||||
t.set("D5", "=LAMBDA(x,y,x-y)(Sheet1!$G$1,Sheet1!$G$2)");
|
||||
t.set("D6", "=LAMBDA(x,y,x-y)(Sheet1!$G$1,Sheet1!$G$3)");
|
||||
assert_eq!(t.get("D5"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D6"), Value::Number(-8.0 * ULP1));
|
||||
// Array arguments: each element snaps by its own left operand (1 and 3 are different binades).
|
||||
t.put("E1", 1.0);
|
||||
t.put("E2", 3.0);
|
||||
t.put("F1", 1.0 + ULP1);
|
||||
t.put("F2", 3.0 + 2.0 * ULP1);
|
||||
t.set("D8", "=INDEX(LAMBDA(x,y,x-y)(Sheet1!$E$1:$E$2,Sheet1!$F$1:$F$2),1,1)");
|
||||
t.set("D9", "=INDEX(LAMBDA(x,y,x-y)(Sheet1!$E$1:$E$2,Sheet1!$F$1:$F$2),2,1)");
|
||||
assert_eq!(t.get("D8"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D9"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_that_calls_itself_ends_in_an_error_not_a_crash() {
|
||||
// Which error depends on where the depth runs out first (#CALC! or #NAME?); what matters is that
|
||||
// it ends. A recursion through cells is a separate, existing limit.
|
||||
let mut t = lambda_t();
|
||||
t.name("Loop", "LAMBDA(x,Loop(x)-1)");
|
||||
t.set("D5", "=Loop(1)");
|
||||
assert!(matches!(t.get("D5"), Value::Error(_)), "{:?}", t.get("D5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimrange() {
|
||||
let mut t = T::new();
|
||||
@@ -2035,6 +2593,65 @@ fn offset_extreme_arguments_return_ref() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorting and ranking compare numbers exactly while `=` and COUNTIF compare them at 15
|
||||
/// significant digits. Every expectation was observed in Excel 365 with these fixtures
|
||||
/// (`=0.1+0.2` is 0.30000000000000004): 0.3 sorts first whatever the input order.
|
||||
#[test]
|
||||
fn sorts_and_ranks_compare_numbers_exactly() {
|
||||
let mut t = T::new();
|
||||
for (at, input) in [
|
||||
// The noisy value first, then the exact one first.
|
||||
("A1", "=0.1+0.2"),
|
||||
("B1", "e"),
|
||||
("A2", "0.3"),
|
||||
("B2", "t"),
|
||||
("D1", "0.3"),
|
||||
("E1", "t"),
|
||||
("D2", "=0.1+0.2"),
|
||||
("E2", "e"),
|
||||
("G1", "=100+1E-14"),
|
||||
("H1", "e"),
|
||||
("G2", "100"),
|
||||
("H2", "t"),
|
||||
] {
|
||||
t.set(at, input);
|
||||
}
|
||||
let e = 0.1 + 0.2;
|
||||
let n = Value::Number;
|
||||
let s = |x: &str| Value::from(x);
|
||||
let cases: Vec<(&str, Value)> = vec![
|
||||
("=A1=A2", Value::Bool(true)),
|
||||
("=COUNTIF(A1:A2,0.3)", n(2.0)),
|
||||
("=INDEX(SORT(A1:B2),1,2)", s("t")),
|
||||
("=INDEX(SORT(D1:E2),1,2)", s("t")),
|
||||
("=INDEX(SORT(A1:B2,1,-1),1,2)", s("e")),
|
||||
("=INDEX(SORT(D1:E2,1,-1),1,2)", s("e")),
|
||||
("=INDEX(SORT(G1:H2),1,2)", s("t")),
|
||||
("=INDEX(SORT(G1:H2,1,-1),1,2)", s("e")),
|
||||
("=INDEX(SORTBY(B1:B2,A1:A2),1,1)", s("t")),
|
||||
("=INDEX(SORTBY(E1:E2,D1:D2),1,1)", s("t")),
|
||||
("=INDEX(SORTBY(B1:B2,A1:A2,-1),1,1)", s("e")),
|
||||
("=INDEX(SORTBY(E1:E2,D1:D2,-1),1,1)", s("e")),
|
||||
// Already exact: UNIQUE, RANK, LARGE/SMALL, MODE.
|
||||
("=ROWS(UNIQUE(A1:A2))", n(2.0)),
|
||||
("=RANK.EQ(0.3,A1:A2)", n(2.0)),
|
||||
("=RANK.EQ(0.3,A1:A2,1)", n(1.0)),
|
||||
("=RANK.AVG(0.3,A1:A2)", n(2.0)),
|
||||
("=RANK.EQ(0.3,A1)", Value::Error(CellError::NA)),
|
||||
("=LARGE(A1:A2,1)", n(e)),
|
||||
("=SMALL(A1:A2,1)", n(0.3)),
|
||||
("=MODE.SNGL(A1:A2,5)", Value::Error(CellError::NA)),
|
||||
];
|
||||
let mut wrong = Vec::new();
|
||||
for (formula, expected) in cases {
|
||||
let got = crate::evaluate(&t.wb, 0, c("Z1"), formula);
|
||||
if got != expected {
|
||||
wrong.push(format!("{formula}: got {got:?}, Excel {expected:?}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
|
||||
}
|
||||
|
||||
/// `@` intersects a reference with the formula's row (a column range) or column (a row range);
|
||||
/// a 2D range both (circular when it includes the formula's cell); a range the formula does not
|
||||
/// line up with gives #VALUE!. An array gives its top-left value. Legacy formulas read from files use it where Excel intersects implicitly.
|
||||
@@ -2617,6 +3234,19 @@ fn loan_schedule_residue_keeps_excels_sign() {
|
||||
assert_eq!(t.get("P7"), Value::Text("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concat_operator_cuts_at_the_cell_limit() {
|
||||
// Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))");
|
||||
t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")");
|
||||
t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))");
|
||||
t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")");
|
||||
t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))");
|
||||
assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0));
|
||||
assert_eq!(t.get("A5"), Value::Error(CellError::Value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() {
|
||||
let mut t = T::new();
|
||||
@@ -2880,13 +3510,17 @@ fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() {
|
||||
let check = |wb: &Workbook, when: &str| {
|
||||
let sh = wb.sheet(0).unwrap();
|
||||
for (cell, f, lead, blocks) in &oracle {
|
||||
let (mut sum, mut count, mut error) = (lead.unwrap_or(0.0), u64::from(lead.is_some()), None);
|
||||
let (mut nums, mut count, mut error) = (Vec::new(), 0u64, None);
|
||||
if let Some(l) = *lead {
|
||||
nums.push(l);
|
||||
count += 1;
|
||||
}
|
||||
for &(r0, c0, r1, c1) in blocks {
|
||||
for r in r0..=r1 {
|
||||
for col in c0..=c1 {
|
||||
match sh.value(CellRef::new(r, col)) {
|
||||
Value::Number(n) => {
|
||||
sum += n;
|
||||
nums.push(n);
|
||||
count += 1;
|
||||
}
|
||||
Value::Error(e) if *f != "COUNT" => error = error.or(Some(e)),
|
||||
@@ -2895,12 +3529,15 @@ fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// SUM snaps only its last addition, matching Acc::finish. AVERAGE and the
|
||||
// running total use the unsapped left-to-right fold.
|
||||
let plain = nums.iter().fold(0.0, |a, n| a + n);
|
||||
let want = match (error, *f) {
|
||||
(Some(e), _) => Value::Error(e),
|
||||
(_, "SUM") => Value::number(sum),
|
||||
(_, "SUM") => Value::number(gridcraft_core::arith::sum_snapped(&nums)),
|
||||
(_, "COUNT") => Value::number(count as f64),
|
||||
(_, _) if count == 0 => Value::Error(CellError::Div0),
|
||||
_ => Value::number(sum / count as f64),
|
||||
_ => Value::number(plain / count as f64),
|
||||
};
|
||||
let got = sh.value(*cell);
|
||||
let same = match (&got, &want) {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use gridcraft_calc::is_known_function;
|
||||
use gridcraft_formula::FormulaLocale;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn every_polish_name_belongs_to_a_known_function() {
|
||||
let names = FormulaLocale::Pl.aliases();
|
||||
assert!(names.len() > 400, "{}", names.len());
|
||||
let mut seen = HashSet::new();
|
||||
for (en, pl) in names {
|
||||
assert!(is_known_function(en), "{en} is not a GridCraft function");
|
||||
assert_ne!(en, pl, "{en} needs no alias");
|
||||
// A Polish name that is another function's English name would call the wrong function.
|
||||
assert!(!is_known_function(pl), "{pl} ({en}) shadows an English function");
|
||||
assert!(seen.insert(pl.to_uppercase()), "{pl} is listed twice");
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ enum Fam {
|
||||
Col100,
|
||||
Line,
|
||||
LineStack,
|
||||
Line100,
|
||||
Area,
|
||||
AreaStack,
|
||||
Area100,
|
||||
@@ -31,6 +32,7 @@ fn family(k: ChartKind) -> Fam {
|
||||
ColumnStacked100 | BarStacked100 => Fam::Col100,
|
||||
Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line,
|
||||
LineStacked => Fam::LineStack,
|
||||
LineStacked100 | LineStacked100Markers => Fam::Line100,
|
||||
Area => Fam::Area,
|
||||
AreaStacked => Fam::AreaStack,
|
||||
AreaStacked100 => Fam::Area100,
|
||||
@@ -40,7 +42,7 @@ fn family(k: ChartKind) -> Fam {
|
||||
|
||||
/// Families stacked to 100%: each category's values are shares of its total.
|
||||
fn is_100(f: Fam) -> bool {
|
||||
matches!(f, Fam::Col100 | Fam::Area100)
|
||||
matches!(f, Fam::Col100 | Fam::Line100 | Fam::Area100)
|
||||
}
|
||||
|
||||
fn is_col(f: Fam) -> bool {
|
||||
@@ -48,7 +50,21 @@ fn is_col(f: Fam) -> bool {
|
||||
}
|
||||
|
||||
fn is_line(f: Fam) -> bool {
|
||||
matches!(f, Fam::Line | Fam::LineStack)
|
||||
matches!(f, Fam::Line | Fam::LineStack | Fam::Line100)
|
||||
}
|
||||
|
||||
/// Line kinds that draw a marker at each point.
|
||||
fn has_markers(k: ChartKind) -> bool {
|
||||
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
|
||||
}
|
||||
|
||||
/// Stroke widths for explicitly selected Excel chart styles.
|
||||
fn line_style_width(style: u32) -> f32 {
|
||||
match style {
|
||||
1 => 3.0,
|
||||
9 => 5.0,
|
||||
_ => 2.25,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
|
||||
@@ -64,6 +80,7 @@ struct BarRun {
|
||||
}
|
||||
|
||||
impl BarRun {
|
||||
/// Starts a single-bar run at `pos` spanning `lo..hi`.
|
||||
fn new(pos: f32, lo: f32, hi: f32) -> Self {
|
||||
BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi, merged: false }
|
||||
}
|
||||
@@ -71,6 +88,7 @@ impl BarRun {
|
||||
fn touches(&self, lo: f32, hi: f32) -> bool {
|
||||
lo <= self.hi && hi >= self.lo
|
||||
}
|
||||
/// Extends the merged run to cover `pos` and `lo..hi`.
|
||||
fn add(&mut self, pos: f32, lo: f32, hi: f32) {
|
||||
self.merged = true;
|
||||
self.a0 = self.a0.min(pos);
|
||||
@@ -105,13 +123,15 @@ struct BarSink {
|
||||
bw: f32,
|
||||
horizontal: bool,
|
||||
color: Rgba,
|
||||
stroke: Option<(Rgba, f32)>,
|
||||
nslots: f32,
|
||||
k: f32,
|
||||
}
|
||||
|
||||
impl BarSink {
|
||||
fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self {
|
||||
BarSink { run: None, bw, horizontal, color, nslots, k }
|
||||
/// Creates a bar emitter for series slot `k` of `nslots`.
|
||||
fn new(bw: f32, horizontal: bool, color: Rgba, stroke: Option<(Rgba, f32)>, nslots: f32, k: f32) -> Self {
|
||||
BarSink { run: None, bw, horizontal, color, stroke, nslots, k }
|
||||
}
|
||||
/// Start of this series' slot along the category axis, for the category centered at `c`.
|
||||
fn pos(&self, c: f32) -> f32 {
|
||||
@@ -131,11 +151,10 @@ impl BarSink {
|
||||
let pos = self.pos(c);
|
||||
let band = self.band();
|
||||
if !merge {
|
||||
if self.horizontal {
|
||||
ctx.rect(lo, pos, len, self.bw, self.color, None);
|
||||
} else {
|
||||
ctx.rect(pos, lo, self.bw, len, self.color, None);
|
||||
}
|
||||
let (x, y, w, h) = if self.horizontal { (lo, pos, len, self.bw) } else { (pos, lo, self.bw, len) };
|
||||
// Omit the outline when a bar is no wider/taller than the stroke, so the inner fill never disappears.
|
||||
let stroke = self.stroke.filter(|(_, sw)| w > *sw && h > *sw);
|
||||
ctx.rect(x, y, w, h, self.color, stroke);
|
||||
return;
|
||||
}
|
||||
match &mut self.run {
|
||||
@@ -147,6 +166,7 @@ impl BarSink {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Flushes any pending hairline bar run at the end of the series.
|
||||
fn finish(self, ctx: &mut Ctx) {
|
||||
let band = self.band();
|
||||
if let Some(m) = self.run {
|
||||
@@ -156,7 +176,7 @@ impl BarSink {
|
||||
}
|
||||
|
||||
fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec<Vec<Option<(f64, f64)>>> {
|
||||
// Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart).
|
||||
// Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart).
|
||||
let mut totals: Vec<((bool, Fam), Vec<f64>)> = Vec::new();
|
||||
for (i, s) in data.series.iter().enumerate() {
|
||||
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
|
||||
@@ -187,7 +207,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
|
||||
for (i, s) in data.series.iter().enumerate() {
|
||||
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
|
||||
let a = sec.get(i).copied().unwrap_or(false);
|
||||
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100);
|
||||
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::Line100 | Fam::AreaStack | Fam::Area100);
|
||||
let key = (a, fam);
|
||||
let si = if stacked {
|
||||
match stacks.iter().position(|(k, _, _)| *k == key) {
|
||||
@@ -216,7 +236,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
|
||||
}),
|
||||
(Some((_, pos, _)), _) => {
|
||||
let v = v.unwrap_or(0.0);
|
||||
let v = if fam == Fam::Area100 { share(key, j, v) } else { v };
|
||||
let v = if is_100(fam) { share(key, j, v) } else { v };
|
||||
pos.get_mut(j).map(|acc| {
|
||||
let base = *acc;
|
||||
*acc = clean(*acc + v);
|
||||
@@ -287,6 +307,12 @@ fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec<usize>, f32) {
|
||||
(slot_of, slot_keys.len().max(1) as f32)
|
||||
}
|
||||
|
||||
/// Renders Cartesian column, bar, line, area, and combination charts.
|
||||
///
|
||||
/// Resolves series families and their axes, calculates stacking and
|
||||
/// category positions, and draws the corresponding primitives.
|
||||
/// Explicit chart style 9 adds white outlines to column and bar
|
||||
/// rectangles, including stacked and 100%-stacked variants.
|
||||
pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) {
|
||||
let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS);
|
||||
if ncat == 0 {
|
||||
@@ -385,7 +411,8 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
let k = slot_of.get(i).copied().unwrap_or(0) as f32;
|
||||
// Hairline bars are merged per pixel column (their envelope is what shows).
|
||||
let cull = merge_hairlines(bw, labels_on);
|
||||
let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k);
|
||||
let stroke = (chart.style == 9).then_some((WHITE, 1.0));
|
||||
let mut sink = BarSink::new(bw, horizontal, s.color, stroke, nslots, k);
|
||||
for (j, sp) in row.iter().enumerate() {
|
||||
let Some((b, t)) = sp else { continue };
|
||||
let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc));
|
||||
@@ -422,9 +449,9 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
}
|
||||
_ => {
|
||||
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
|
||||
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
|
||||
draw_runs(ctx, &pts, s.color, line_style_width(chart.style), s.smooth.then_some(plot));
|
||||
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
|
||||
if k == ChartKind::LineMarkers && cw >= 3.0 {
|
||||
if has_markers(k) && cw >= 3.0 {
|
||||
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
|
||||
}
|
||||
if labels_on {
|
||||
|
||||
@@ -57,8 +57,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
|
||||
.clone()
|
||||
.map(|s| {
|
||||
let sw = match s.kind {
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
|
||||
ChartKind::LineMarkers => Swatch::LineMarker,
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => {
|
||||
Swatch::Line
|
||||
}
|
||||
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
|
||||
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
|
||||
_ => Swatch::Box,
|
||||
};
|
||||
|
||||
@@ -71,8 +71,8 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay
|
||||
let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 };
|
||||
if settings.show_keys {
|
||||
let swatch = match series.kind {
|
||||
ChartKind::Line | ChartKind::LineStacked => Swatch::Line,
|
||||
ChartKind::LineMarkers => Swatch::LineMarker,
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 => Swatch::Line,
|
||||
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
|
||||
_ => Swatch::Box,
|
||||
};
|
||||
draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color);
|
||||
|
||||
+90
-11
@@ -39,6 +39,28 @@ pub fn series_color(theme: &Theme, i: usize) -> Rgba {
|
||||
[r, g, b, 0xFF]
|
||||
}
|
||||
|
||||
/// Excel reference colours for explicit styles 1 and 9.
|
||||
///
|
||||
/// These palettes cover measured default-theme examples.
|
||||
/// Other counts still use the existing theme-based fallback.
|
||||
fn chart_style_series_color(theme: &Theme, style: u32, index: usize, count: usize) -> Rgba {
|
||||
if !matches!(style, 1 | 9) {
|
||||
return series_color(theme, index);
|
||||
}
|
||||
|
||||
const SMALL: [u8; 4] = [0x61, 0xB3, 0x81, 0x50];
|
||||
const MEDIUM: [u8; 8] = [0x55, 0x9E, 0x72, 0x46, 0x83, 0xC1, 0x9A, 0xC8];
|
||||
const LARGE: [u8; 16] = [0x4F, 0x93, 0x6A, 0x40, 0x7A, 0xB4, 0x61, 0xB3, 0x81, 0x50, 0x95, 0xDA, 0xAF, 0xD2, 0xBA, 0xAA];
|
||||
|
||||
let shades: &[u8] = match count {
|
||||
1..=4 => &SMALL,
|
||||
5..=8 => &MEDIUM,
|
||||
9..=16 => &LARGE,
|
||||
_ => return series_color(theme, index),
|
||||
};
|
||||
|
||||
shades.get(index).map_or_else(|| series_color(theme, index), |shade| [*shade, *shade, *shade, 0xFF])
|
||||
}
|
||||
/// The first `n` series colours for `theme`.
|
||||
pub fn default_palette(theme: &Theme, n: usize) -> Vec<Rgba> {
|
||||
(0..n.min(4096)).map(|i| series_color(theme, i)).collect()
|
||||
@@ -360,7 +382,7 @@ fn category_label(wb: &Workbook, src: Option<(&gridcraft_model::Sheet, RangeRef)
|
||||
/// the outer levels of a multi-level axis: a category range wider than a column of values (or
|
||||
/// taller than a row of values) groups its innermost labels, year beside month. Each outer level
|
||||
/// has one entry per category, non-empty where a group starts, as the cells are.
|
||||
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize) -> (Vec<String>, Vec<Vec<String>>) {
|
||||
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize, innermost: bool) -> (Vec<String>, Vec<Vec<String>>) {
|
||||
let cells: Option<(usize, RangeRef)> = parse_ref(wb, sheet, formula);
|
||||
let value_range = parse_ref(wb, sheet, values).map(|(_, r)| r);
|
||||
// Bound the category dimension by `limit` and read only the cells the levels use (the
|
||||
@@ -419,12 +441,21 @@ fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limi
|
||||
let at = |row: usize, col: usize| texts.get(row * w + col).cloned().unwrap_or_default();
|
||||
let column = |c: usize| (0..h).map(|row| at(row, c)).collect::<Vec<String>>();
|
||||
let row = |rr: usize| (0..w).map(|c| at(rr, c)).collect::<Vec<String>>();
|
||||
let outer = levels.outer as usize;
|
||||
if levels.by_columns {
|
||||
let value_count = eval_list_in(wb, sheet, values, limit, 0).len();
|
||||
let by_columns = if value_count == h && w > 1 && h != w {
|
||||
true
|
||||
} else if value_count == w && h > 1 && h != w {
|
||||
false
|
||||
} else {
|
||||
levels.by_columns
|
||||
};
|
||||
let outer = if by_columns { w.saturating_sub(1).min(3) } else { h.saturating_sub(1).min(3) };
|
||||
let result = if by_columns {
|
||||
(column(w - 1), (1..=outer).filter_map(|k| (w - 1).checked_sub(k)).map(column).collect())
|
||||
} else {
|
||||
(row(h - 1), (1..=outer).filter_map(|k| (h - 1).checked_sub(k)).map(row).collect())
|
||||
}
|
||||
};
|
||||
if innermost { (result.0, vec![]) } else { result }
|
||||
}
|
||||
|
||||
/// Whether `t` names a defined name seen from `sheet` (`Name`, or `Sheet1!Name` looked up on
|
||||
@@ -461,8 +492,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() {
|
||||
let values = nums(wb, sheet, &s.values, limit);
|
||||
let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1));
|
||||
let color =
|
||||
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
|
||||
let color = s
|
||||
.color
|
||||
.as_ref()
|
||||
.and_then(|c| c.resolve(&wb.theme))
|
||||
.map(|[r, g, b]| [r, g, b, 0xFF])
|
||||
.unwrap_or_else(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES)));
|
||||
let kind = chart.series_kind(i);
|
||||
let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) {
|
||||
// X values with text in them (labels) are ignored: the points are numbered 1..n.
|
||||
@@ -474,7 +509,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
if categories.is_none()
|
||||
&& let Some(f) = &s.categories
|
||||
{
|
||||
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit);
|
||||
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit, s.innermost_categories);
|
||||
c.truncate(limit);
|
||||
if !c.is_empty() {
|
||||
categories = Some(c);
|
||||
@@ -502,15 +537,59 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
secondary: s.secondary,
|
||||
smooth: s.smooth,
|
||||
trendlines,
|
||||
number_format: ref_format(wb, sheet, &s.values),
|
||||
number_format: match &s.number_format {
|
||||
Some(code) if s.values.trim_start().starts_with('{') => code.clone(),
|
||||
_ => ref_format(wb, sheet, &s.values),
|
||||
},
|
||||
});
|
||||
}
|
||||
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
|
||||
let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect());
|
||||
let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE));
|
||||
let palette = if matches!(chart.style, 1 | 9) {
|
||||
(0..n.min(PALETTE_CYCLE)).map(|i| chart_style_series_color(&wb.theme, chart.style, i, n)).collect()
|
||||
} else {
|
||||
default_palette(&wb.theme, n.min(PALETTE_CYCLE))
|
||||
};
|
||||
ChartData { categories, category_levels, series, palette }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod explicit_style_palette_tests {
|
||||
use super::*;
|
||||
|
||||
/// Verifies grayscale palette selection and fallback boundaries for explicit styles 1 and 9.
|
||||
#[test]
|
||||
fn explicit_style_palette_boundaries() {
|
||||
let theme = Workbook::default().theme;
|
||||
|
||||
for style in [1, 9] {
|
||||
for count in [0, 17, 255] {
|
||||
for index in [0, 1, 4, 8, 16] {
|
||||
assert_eq!(chart_style_series_color(&theme, style, index, count), series_color(&theme, index));
|
||||
}
|
||||
}
|
||||
|
||||
for (count, expected_first) in [(1, 0x61), (4, 0x61), (5, 0x55), (8, 0x55), (9, 0x4F), (16, 0x4F)] {
|
||||
assert_eq!(
|
||||
chart_style_series_color(&theme, style, 0, count),
|
||||
[expected_first, expected_first, expected_first, 255],
|
||||
"style {style}, count {count}",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
chart_style_series_color(&theme, style, 16, count),
|
||||
series_color(&theme, 16),
|
||||
"out-of-range index for style {style}, count {count}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for style in [0, 2, 10, 48] {
|
||||
assert_eq!(chart_style_series_color(&theme, style, 0, 4), series_color(&theme, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod label_budget_tests {
|
||||
use gridcraft_model::Workbook;
|
||||
@@ -521,7 +600,7 @@ mod label_budget_tests {
|
||||
#[test]
|
||||
fn category_labels_share_one_byte_budget() {
|
||||
let wb = Workbook::new();
|
||||
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS);
|
||||
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS, false);
|
||||
assert_eq!(texts.len(), 100_000);
|
||||
assert_eq!(texts.first().map(String::len), Some(super::MAX_LABEL_CHARS));
|
||||
assert!(texts.iter().map(String::len).sum::<usize>() <= super::MAX_CATEGORY_BYTES);
|
||||
@@ -544,7 +623,7 @@ mod label_budget_tests {
|
||||
}
|
||||
}
|
||||
// Five columns: column A is a fourth outer level and is discarded.
|
||||
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS);
|
||||
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS, false);
|
||||
assert_eq!(outer.len(), 3);
|
||||
assert_eq!(inner.last().map(String::len), Some(super::MAX_LABEL_CHARS));
|
||||
assert_eq!(outer.first().and_then(|l| l.last()).map(String::len), Some(super::MAX_LABEL_CHARS));
|
||||
|
||||
+345
-1
@@ -8,7 +8,7 @@ use crate::*;
|
||||
mod budget;
|
||||
mod data_table;
|
||||
|
||||
const ALL_KINDS: [ChartKind; 26] = [
|
||||
const ALL_KINDS: [ChartKind; 28] = [
|
||||
ChartKind::ColumnClustered,
|
||||
ChartKind::ColumnStacked,
|
||||
ChartKind::ColumnStacked100,
|
||||
@@ -18,6 +18,8 @@ const ALL_KINDS: [ChartKind; 26] = [
|
||||
ChartKind::Line,
|
||||
ChartKind::LineMarkers,
|
||||
ChartKind::LineStacked,
|
||||
ChartKind::LineStacked100,
|
||||
ChartKind::LineStacked100Markers,
|
||||
ChartKind::Pie,
|
||||
ChartKind::Doughnut,
|
||||
ChartKind::Area,
|
||||
@@ -549,6 +551,9 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
// References use their cells' format, whatever the series says.
|
||||
number_format: Some("0%".into()),
|
||||
innermost_categories: false,
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -561,6 +566,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
},
|
||||
Series {
|
||||
name: Some("Literal".into()),
|
||||
@@ -573,6 +580,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: Some("0.0%".into()),
|
||||
innermost_categories: false,
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -592,6 +601,7 @@ fn resolve_from_workbook() {
|
||||
assert!(s1.secondary);
|
||||
assert_eq!(d.series[2].name, "Literal");
|
||||
assert_eq!(d.series[2].values.len(), 4);
|
||||
assert_eq!(d.series[2].number_format, "0.0%");
|
||||
|
||||
// Default categories.
|
||||
c.series.remove(0);
|
||||
@@ -612,6 +622,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -624,6 +636,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -641,6 +655,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
|
||||
@@ -659,6 +675,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
}];
|
||||
let d = resolve(&wb, 7, &c);
|
||||
assert_eq!(d.series.len(), 1);
|
||||
@@ -1364,6 +1382,8 @@ fn pie_points_follow_workbook_theme() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
let expected = vec![series_color(&wb.theme, 0), series_color(&wb.theme, 1)];
|
||||
@@ -1419,6 +1439,47 @@ fn area_charts_draw_source_value_labels_only_when_enabled() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_level_category_block_draws_its_innermost_level() {
|
||||
// A PivotChart's two levels of row labels in A1:B4, the outer one (country) on the left:
|
||||
// one label per point, from the innermost column.
|
||||
let mut wb = Workbook::new();
|
||||
{
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
s.name = "Graph".into();
|
||||
for (r, (outer, inner)) in [("Canada", "Ottawa"), ("", "Toronto"), ("USA", "Boston"), ("", "NYC")].iter().enumerate() {
|
||||
if !outer.is_empty() {
|
||||
s.set_value(CellRef::new(r as u32, 0), Value::from(*outer));
|
||||
}
|
||||
s.set_value(CellRef::new(r as u32, 1), Value::from(*inner));
|
||||
s.set_value(CellRef::new(r as u32, 2), Value::Number(r as f64 + 1.0));
|
||||
s.set_value(CellRef::new(5, r as u32), Value::from(*inner));
|
||||
s.set_value(CellRef::new(6, r as u32), Value::from(*outer));
|
||||
}
|
||||
}
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.series = vec![Series {
|
||||
categories: Some("Graph!$A$1:$B$4".into()),
|
||||
values: "Graph!$C$1:$C$4".into(),
|
||||
innermost_categories: true,
|
||||
..Series::default()
|
||||
}];
|
||||
let data = resolve(&wb, 0, &c);
|
||||
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
|
||||
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
|
||||
// A block with a column per point: its last row is the innermost level.
|
||||
c.series[0].categories = Some("Graph!$A$6:$D$7".into());
|
||||
let data = resolve(&wb, 0, &c);
|
||||
assert_eq!(data.categories, vec!["Canada", "", "USA", ""]);
|
||||
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
|
||||
// Without the flag, every cell is a label, as for any other chart.
|
||||
c.series[0].categories = Some("Graph!$A$1:$B$4".into());
|
||||
c.series[0].innermost_categories = false;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
|
||||
assert_eq!(data.category_levels, vec![vec!["Canada", "", "USA", ""]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_and_resolving_agree_on_the_combo_plot_kind() {
|
||||
// Resolved series carry `Chart::series_kind`, the kind drawing uses: for every chart kind,
|
||||
@@ -1491,6 +1552,62 @@ fn hundred_percent_stacked_areas_fill_each_category_to_its_total() {
|
||||
assert!(frac(top(south, 2)).abs() < 1e-3, "Q3: South reaches {}", frac(top(south, 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hundred_percent_stacked_lines_end_each_category_at_its_total() {
|
||||
let (north_color, south_color) = ([20, 96, 130, 255], [25, 107, 36, 255]);
|
||||
for kind in [ChartKind::LineStacked100, ChartKind::LineStacked100Markers] {
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"].iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("North", &[10.0, 30.0, 0.0, 5.0], north_color, kind), series("South", &[30.0, 10.0, 0.0, 15.0], south_color, kind)],
|
||||
};
|
||||
let mut c = chart(kind);
|
||||
c.data_labels = false;
|
||||
let p = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
let t = texts(&p);
|
||||
assert!(t.contains(&"100%") && t.contains(&"0%"), "{kind:?}: {t:?}");
|
||||
assert!(!t.contains(&"40"), "{kind:?}: {t:?}");
|
||||
// The value axis labels sit on their gridlines.
|
||||
let label_y = |s: &str| {
|
||||
p.iter()
|
||||
.find_map(|p| match p {
|
||||
Prim::Text { text, y, .. } if text == s => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(f32::NAN)
|
||||
};
|
||||
let (y0, y100) = (label_y("0%"), label_y("100%"));
|
||||
assert!(y0 > y100, "{kind:?}: {y0} {y100}");
|
||||
let frac = |y: f32| (y0 - y) / (y0 - y100);
|
||||
let line = |color: Rgba| {
|
||||
p.iter()
|
||||
.find_map(|p| match p {
|
||||
// The series line is 2.25 wide; its legend swatch is 2.0.
|
||||
Prim::Line { pts, color: c, width, .. } if *c == color && *width > 2.1 => {
|
||||
Some(pts.iter().map(|q| frac(q[1])).collect::<Vec<f32>>())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let (north, south) = (line(north_color), line(south_color));
|
||||
assert_eq!((north.len(), south.len()), (4, 4), "{kind:?}: {north:?} {south:?}");
|
||||
// A category whose total is zero stays on the baseline.
|
||||
for (j, (n, s)) in [(0.25, 1.0), (0.75, 1.0), (0.0, 0.0), (0.25, 1.0)].into_iter().enumerate() {
|
||||
assert!((north[j] - n).abs() < 1e-3 && (south[j] - s).abs() < 1e-3, "{kind:?} Q{}: {} {}", j + 1, north[j], south[j]);
|
||||
}
|
||||
// Point markers have a white outline; the legend's marker swatches have none.
|
||||
let circles = |outlined: bool| {
|
||||
p.iter()
|
||||
.filter(|p| matches!(p, Prim::Circle { fill: Some(f), stroke, .. } if (*f == north_color || *f == south_color) && stroke.is_some() == outlined))
|
||||
.count()
|
||||
};
|
||||
let with_markers = kind == ChartKind::LineStacked100Markers;
|
||||
assert_eq!((circles(true), circles(false)), if with_markers { (8, 2) } else { (0, 0) }, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_level_categories_resolve_and_draw() {
|
||||
let years = ["2023", "", "", "2024", "", ""];
|
||||
@@ -1565,6 +1682,22 @@ fn two_level_categories_resolve_and_draw() {
|
||||
assert!(d.category_levels.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn square_category_blocks_keep_their_declared_orientation_on_ties() {
|
||||
let mut wb = Workbook::new();
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
s.name = "Data".into();
|
||||
for (i, value) in ["A1", "B1", "A2", "B2", "A3", "B3"].iter().enumerate() {
|
||||
s.set_value(CellRef::parse(value).unwrap(), Value::from(*value));
|
||||
s.set_value(CellRef::new(3, i as u32), Value::Number(i as f64 + 1.0));
|
||||
}
|
||||
let mut c = chart(ChartKind::Line);
|
||||
c.series = vec![Series { categories: Some("Data!$A$1:$B$2".into()), values: "Data!$A$3:$B$3".into(), ..Series::default() }];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.categories, vec!["A2", "B2"]);
|
||||
assert_eq!(d.category_levels, vec![vec!["A1", "B1"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_trendline_forecast_does_not_collapse_the_columns() {
|
||||
let m = ApproxMeasure;
|
||||
@@ -1610,6 +1743,7 @@ fn box_whisker_draws_each_series_quartile_method() {
|
||||
assert!((heights[0] / heights[1] - 1.4).abs() < 0.001);
|
||||
}
|
||||
|
||||
/// Defined-name series titles on sheets with apostrophes resolve properly.
|
||||
#[test]
|
||||
fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
|
||||
// #2012: `'Bob''s'!Title` kept the doubled quote, so the sheet wasn't found and the series
|
||||
@@ -1641,11 +1775,13 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
..Series::default()
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
|
||||
}
|
||||
|
||||
/// Defined-name series titles on sheets whose names contain `!` resolve properly.
|
||||
#[test]
|
||||
fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
|
||||
// `'a!b'!Title`: the sheet name holds a `!`, so the evaluator must split the parsed name at
|
||||
@@ -1677,11 +1813,13 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
..Series::default()
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
|
||||
}
|
||||
|
||||
/// Volatile functions in series values or names mark the chart as volatile.
|
||||
#[test]
|
||||
fn volatile_series_formulas_are_detected() {
|
||||
let wb = Workbook::new();
|
||||
@@ -1698,6 +1836,8 @@ fn volatile_series_formulas_are_detected() {
|
||||
smooth: false,
|
||||
quartiles: Default::default(),
|
||||
trendlines: vec![],
|
||||
innermost_categories: false,
|
||||
number_format: None,
|
||||
});
|
||||
c
|
||||
};
|
||||
@@ -1712,6 +1852,7 @@ fn volatile_series_formulas_are_detected() {
|
||||
assert!(!has_volatile_series(&wb, 0, &chart(ChartKind::Line)));
|
||||
}
|
||||
|
||||
/// Defined names referenced by series formulas are followed for volatility checks.
|
||||
#[test]
|
||||
fn volatile_defined_names_are_followed() {
|
||||
let with = |values: &str| {
|
||||
@@ -1727,6 +1868,8 @@ fn volatile_defined_names_are_followed() {
|
||||
smooth: false,
|
||||
quartiles: Default::default(),
|
||||
trendlines: vec![],
|
||||
innermost_categories: false,
|
||||
number_format: None,
|
||||
});
|
||||
c
|
||||
};
|
||||
@@ -1774,3 +1917,204 @@ fn volatile_defined_names_are_followed() {
|
||||
assert!(!has_volatile_series(&wb, 1, &with("=Dice")));
|
||||
assert!(has_volatile_series(&wb, 1, &with("=FreshClock")));
|
||||
}
|
||||
|
||||
/// Explicit Excel chart styles should affect default series colours,
|
||||
/// without changing the workbook theme.
|
||||
#[test]
|
||||
fn explicit_chart_styles_use_distinct_default_colors() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.series.push(Series { values: "{10,20,30}".into(), ..Series::default() });
|
||||
|
||||
c.style = 2;
|
||||
let style2 = resolve(&wb, 0, &c).series[0].color;
|
||||
assert_eq!(style2, series_color(&wb.theme, 0));
|
||||
|
||||
c.style = 1;
|
||||
let style1 = resolve(&wb, 0, &c).series[0].color;
|
||||
|
||||
c.style = 9;
|
||||
let style9 = resolve(&wb, 0, &c).series[0].color;
|
||||
|
||||
assert_ne!(style1, style2, "style 1 should differ from style 2");
|
||||
assert_ne!(style9, style2, "style 9 should differ from style 2");
|
||||
}
|
||||
|
||||
/// Excel chart styles must not override explicitly assigned series colours.
|
||||
#[test]
|
||||
fn explicit_chart_styles_preserve_custom_series_colors() {
|
||||
let wb = Workbook::default();
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
|
||||
c.series.push(Series { values: "{10,20,30}".into(), color: Some(Color::rgb(12, 34, 56)), ..Series::default() });
|
||||
|
||||
for style in [1, 2, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(data.series[0].color, [12, 34, 56, 255], "explicit series colour changed under chart style {style}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the first four point colours measured in Excel for styles 1 and 9.
|
||||
#[test]
|
||||
fn excel_chart_styles_use_measured_point_palette() {
|
||||
let wb = Workbook::default();
|
||||
let mut c = chart(ChartKind::Pie);
|
||||
|
||||
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
|
||||
|
||||
let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]];
|
||||
|
||||
for style in [1, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(&data.palette[..4], &expected);
|
||||
assert_eq!(data.series[0].color, expected[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Excel's default-theme chart colours depend on the total series count.
|
||||
#[test]
|
||||
fn excel_chart_styles_depend_on_series_count() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
let base_series = Series { values: "{10,20,30,40}".into(), ..Series::default() };
|
||||
|
||||
let cases: &[(usize, [[u8; 4]; 3])] = &[
|
||||
(6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]),
|
||||
(12, [[0x4F, 0x4F, 0x4F, 0xFF], [0x93, 0x93, 0x93, 0xFF], [0x6A, 0x6A, 0x6A, 0xFF]]),
|
||||
];
|
||||
|
||||
for (count, expected) in cases {
|
||||
for style in [1, 9] {
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.style = style;
|
||||
c.series = vec![base_series.clone(); *count];
|
||||
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(data.series.len(), *count);
|
||||
|
||||
for (i, color) in expected.iter().enumerate() {
|
||||
assert_eq!(data.series[i].color, *color, "style {style}, {count} series, index {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Style 9 uses white outlines on column and bar data rectangles.
|
||||
#[test]
|
||||
fn explicit_style_nine_draws_white_column_outlines() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
for kind in [
|
||||
ChartKind::ColumnClustered,
|
||||
ChartKind::BarClustered,
|
||||
ChartKind::ColumnStacked,
|
||||
ChartKind::BarStacked,
|
||||
ChartKind::ColumnStacked100,
|
||||
ChartKind::BarStacked100,
|
||||
] {
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
|
||||
|
||||
for style in [1, 2, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
let color = data.series[0].color;
|
||||
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
|
||||
|
||||
let outlines: Vec<_> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Rect { fill: Some(fill), stroke, .. } if *fill == color => Some(*stroke),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert!(!outlines.is_empty(), "No data rectangles for {kind:?}, style {style}");
|
||||
|
||||
let expected = if style == 9 { Some(([255, 255, 255, 255], 1.0)) } else { None };
|
||||
|
||||
assert!(outlines.iter().all(|stroke| *stroke == expected), "Unexpected outline for {kind:?}, style {style}: {outlines:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Excel's default line weights are 3 pt for style 1 and 5 pt for style 9.
|
||||
/// Other styles retain GridCraft's existing stroke width.
|
||||
#[test]
|
||||
fn explicit_excel_styles_set_line_stroke_width() {
|
||||
let color: Rgba = [17, 73, 131, 255];
|
||||
|
||||
for kind in [ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked] {
|
||||
let data = ChartData {
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"].map(String::from).to_vec(),
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
series: vec![series("North", &[12.0, 19.0, 25.0, 30.0], color, kind)],
|
||||
};
|
||||
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
|
||||
for (style, expected_width) in [(0, 2.25_f32), (1, 3.0), (2, 2.25), (9, 5.0), (48, 2.25)] {
|
||||
c.style = style;
|
||||
|
||||
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
|
||||
|
||||
let widths: Vec<f32> = prims
|
||||
.iter()
|
||||
.filter_map(|primitive| match primitive {
|
||||
Prim::Line { color: line_color, width, .. } if *line_color == color => Some(*width),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(widths, vec![expected_width], "Unexpected stroke width for {kind:?}, style {style}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrow style 9 bars (at or below the 1 px outline width) omit the white stroke so their gray fill stays visible.
|
||||
#[test]
|
||||
fn narrow_style_9_bars_retain_visible_fill() {
|
||||
let fill_color: Rgba = [0x61, 0x61, 0x61, 0xFF];
|
||||
// Stay within MAX_LABELS (200) so data labels remain active on the direct unmerged path,
|
||||
// while keeping each single-series slot <= 0.88 px inside the 220 px chart.
|
||||
let count = 100usize;
|
||||
let categories: Vec<String> = (0..count).map(|i| format!("C{i}")).collect();
|
||||
let values = vec![50.0; count];
|
||||
|
||||
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] {
|
||||
let data = ChartData {
|
||||
categories: categories.clone(),
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
series: vec![series("S1", &values, fill_color, kind)],
|
||||
};
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
// Data labels keep bars on the unmerged direct path even when narrower than 1 px.
|
||||
c.data_labels = true;
|
||||
c.gridlines = false;
|
||||
c.style = 9;
|
||||
|
||||
let prims = render(&c, &data, 220.0, 220.0, &ApproxMeasure);
|
||||
let narrow_bars: Vec<_> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Rect { w, h, fill: Some(fill), stroke, .. } if *fill == fill_color && (*w <= 1.0 || *h <= 1.0) => Some(*stroke),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(narrow_bars.len(), count, "Direct unmerged path must emit all {count} bars individually for {kind:?}");
|
||||
assert!(narrow_bars.iter().all(Option::is_none), "Narrow style 9 bars must omit the 1 px white outline: {narrow_bars:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,3 +148,32 @@ fn dense_and_tiny_tables_are_bounded_and_explicit() {
|
||||
assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_keys_for_100_percent_stacked_lines_use_line_swatches() {
|
||||
for (kind, marker) in [(ChartKind::LineStacked100, false), (ChartKind::LineStacked100Markers, true)] {
|
||||
let mut c = chart(kind);
|
||||
c.title = Some(String::new());
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.data_table = Some(ChartDataTable::default());
|
||||
let color = [1, 2, 3, 255];
|
||||
let d = ChartData {
|
||||
categories: ["Jan", "Feb"].map(String::from).to_vec(),
|
||||
series: vec![series("Rate", &[1.0, 3.0], color, kind)],
|
||||
..Default::default()
|
||||
};
|
||||
let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure);
|
||||
let header_y = p
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
Prim::Text { text, y, .. } if text == "Jan" => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let key_circles = p.iter().filter(|p| matches!(p, Prim::Circle { cy, fill: Some(f), .. } if *f == color && *cy > header_y)).count();
|
||||
assert_eq!(key_circles, usize::from(marker), "{kind:?}");
|
||||
let key_box = p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y));
|
||||
assert!(!key_box, "{kind:?} key is a line swatch");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,11 +123,27 @@ pub fn letters_to_col(s: &str) -> Option<u32> {
|
||||
|
||||
/// A rectangular block of cells, inclusive on both ends. Always normalised (`start <= end`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(from = "RangeRefFields")]
|
||||
pub struct RangeRef {
|
||||
pub start: CellRef,
|
||||
pub end: CellRef,
|
||||
}
|
||||
|
||||
/// A range as stored (`{start, end}`). A file may hold any numbers there, so loading puts the
|
||||
/// corners in order and on the sheet: `height()` and `width()` subtract them unchecked (#2160).
|
||||
#[derive(Deserialize)]
|
||||
struct RangeRefFields {
|
||||
start: CellRef,
|
||||
end: CellRef,
|
||||
}
|
||||
|
||||
impl From<RangeRefFields> for RangeRef {
|
||||
fn from(r: RangeRefFields) -> Self {
|
||||
let on_sheet = |c: CellRef| CellRef::new(c.row.min(MAX_ROWS - 1), c.col.min(MAX_COLS - 1));
|
||||
RangeRef::new(on_sheet(r.start), on_sheet(r.end))
|
||||
}
|
||||
}
|
||||
|
||||
impl RangeRef {
|
||||
pub fn new(a: CellRef, b: CellRef) -> Self {
|
||||
RangeRef { start: CellRef::new(a.row.min(b.row), a.col.min(b.col)), end: CellRef::new(a.row.max(b.row), a.col.max(b.col)) }
|
||||
@@ -337,6 +353,19 @@ mod tests {
|
||||
assert_eq!(split_areas(""), [""]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loaded_range_is_ordered_and_on_the_sheet() {
|
||||
// #2160: a file can hold any corners; `height()` subtracts them unchecked.
|
||||
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":4000000000,"col":5},"end":{"row":2,"col":1}}"#).unwrap();
|
||||
assert_eq!(r, RangeRef::new(CellRef::new(2, 1), CellRef::new(MAX_ROWS - 1, 5)));
|
||||
assert_eq!((r.height(), r.width()), (MAX_ROWS - 2, 5));
|
||||
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":9,"col":99999},"end":{"row":3,"col":0}}"#).unwrap();
|
||||
assert_eq!(r, RangeRef::new(CellRef::new(3, 0), CellRef::new(9, MAX_COLS - 1)));
|
||||
// What is saved loads back unchanged.
|
||||
let ok = RangeRef::new(CellRef::new(1, 2), CellRef::new(7, 3));
|
||||
assert_eq!(serde_json::from_str::<RangeRef>(&serde_json::to_string(&ok).unwrap()).unwrap(), ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_parse_rejects_signed_rows() -> Result<(), std::io::Error> {
|
||||
assert!(RangeRef::parse("+1:+3").is_none());
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Arithmetic that follows Excel's bits rather than IEEE's: the snap to zero.
|
||||
|
||||
/// 2^-49: the snap threshold is this fraction of the left operand's binade.
|
||||
const SNAP: f64 = 1.0 / 562_949_953_421_312.0;
|
||||
|
||||
/// The power of two at the bottom of `x`'s binade (`x` with its mantissa cleared); 0 for zero,
|
||||
/// subnormal and non-finite values.
|
||||
fn binade(x: f64) -> f64 {
|
||||
if x.is_finite() { f64::from_bits(x.to_bits() & 0x7FF0_0000_0000_0000) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// `x + y` as Excel computes it at the root of a formula or as the last addition of a `SUM`:
|
||||
/// when the operands have opposite signs and `|x + y| < 2^(e-49)`, `e` the binary exponent of
|
||||
/// the LEFT operand `x`, the result is exactly 0. A subtraction passes `-y`.
|
||||
///
|
||||
/// Excel does this only at those places, not at every add or subtract (observed on Windows Excel 16.0.20430; see
|
||||
/// `EXCEL-BEHAVIOUR.md` of the Spreadsheet Accuracy Suite, "The snap to zero").
|
||||
pub fn snap_add(x: f64, y: f64) -> f64 {
|
||||
let s = x + y;
|
||||
let opposite = (x > 0.0 && y < 0.0) || (x < 0.0 && y > 0.0);
|
||||
if opposite && s.abs() < binade(x) * SNAP { 0.0 } else { s }
|
||||
}
|
||||
|
||||
/// The sum of `values` left to right, each addition rounded, with the LAST addition snapped.
|
||||
/// This is `SUM`'s arithmetic: `SUM(a, -b)` is 0 for a near-cancellation, but `SUM(a, -b, 0)` keeps
|
||||
/// the residue because its last addition is residue + 0.
|
||||
pub fn sum_snapped(values: &[f64]) -> f64 {
|
||||
let Some((last, head)) = values.split_last() else { return 0.0 };
|
||||
snap_add(head.iter().fold(0.0, |acc, v| acc + v), *last)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ULP1: f64 = f64::EPSILON;
|
||||
|
||||
#[test]
|
||||
fn snaps_below_two_to_the_e_minus_49_of_the_left_operand() {
|
||||
assert_eq!(snap_add(1.0, -(1.0 + ULP1)), 0.0);
|
||||
assert_eq!(snap_add(1.0, -(1.0 + 7.0 * ULP1)), 0.0);
|
||||
// Exactly 2^-49 (8 ulps of 1.0) does not snap.
|
||||
assert_eq!(snap_add(1.0, -(1.0 + 8.0 * ULP1)), -8.0 * ULP1);
|
||||
// The left operand's binade decides (observed on Windows Excel 16.0.20430, excel-probe-4.00044 to 00046):
|
||||
// 0.4999999999999998 - 0.5000000000000002 keeps -4.44e-16 (threshold 2^-51 is not beaten),
|
||||
// the other way round it is 0 (threshold 2^-50).
|
||||
assert_eq!(snap_add(0.4999999999999998, -0.5000000000000002), -4.440892098500626e-16);
|
||||
assert_eq!(snap_add(0.5000000000000002, -0.4999999999999998), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_snaps_same_sign_zero_or_hostile_operands() {
|
||||
assert_eq!(snap_add(1e-20, 2e-20), 1e-20 + 2e-20);
|
||||
assert_eq!(snap_add(3.0, 0.0), 3.0);
|
||||
assert_eq!(snap_add(0.0, -1e-300), -1e-300);
|
||||
// A subnormal left operand has no binade to measure against: it never snaps.
|
||||
assert_eq!(snap_add(5e-324, -1e-323), -5e-324);
|
||||
assert!(snap_add(f64::INFINITY, -f64::INFINITY).is_nan());
|
||||
assert_eq!(snap_add(-1.0, 1.0 + ULP1), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_snaps_only_its_last_addition() {
|
||||
assert_eq!(sum_snapped(&[]), 0.0);
|
||||
assert_eq!(sum_snapped(&[1.0, -(1.0 + ULP1)]), 0.0);
|
||||
assert_eq!(sum_snapped(&[1.0, -(1.0 + ULP1), 0.0]), 1.0 - (1.0 + ULP1));
|
||||
assert_eq!(sum_snapped(&[3.0, 1e16, -1e16, 0.0]), 4.0);
|
||||
// Left to right, each addition rounded: ten 0.1s do not make 1.
|
||||
assert_eq!(sum_snapped(&[0.1; 10]), 0.999_999_999_999_999_9);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,43 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
|
||||
Some(serial as f64)
|
||||
}
|
||||
|
||||
/// The calendar date a pivot cache's ISO 8601 date items (`<d>`, `minDate`, `startDate`…) give
|
||||
/// a date of a date system's calendar, as [`datetime_from_serial`] returns it. Those dates count
|
||||
/// real days: from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to
|
||||
/// February 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious
|
||||
/// 1900-02-29, runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30,
|
||||
/// serial 1 is 1899-12-31 and serial 60 is 1900-02-28. Excel writes its caches that way.
|
||||
pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) {
|
||||
if sys == DateSystem::D1900 && year == 1900 && month <= 2 {
|
||||
let serial = if month <= 1 { day } else { 31 + day };
|
||||
return civil_from_days(i64::from(serial) + UNIX_1899_12_30);
|
||||
}
|
||||
(year, month, day)
|
||||
}
|
||||
|
||||
/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`]
|
||||
/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid.
|
||||
/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the
|
||||
/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date,
|
||||
/// or one before the epoch or after 9999-12-31.
|
||||
pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option<f64> {
|
||||
let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?);
|
||||
match (sys, y, m, d) {
|
||||
(DateSystem::D1900, 1900, 2, 29) => return Some(60.0),
|
||||
(DateSystem::D1904, 1899, 12, 30) => return Some(0.0),
|
||||
_ => {}
|
||||
}
|
||||
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) {
|
||||
return None;
|
||||
}
|
||||
let base = match sys {
|
||||
DateSystem::D1900 => UNIX_1899_12_30,
|
||||
DateSystem::D1904 => UNIX_1904_01_01,
|
||||
};
|
||||
let serial = days_from_civil(y, m, d) - base;
|
||||
(0..=max_serial(sys)).contains(&serial).then_some(serial as f64)
|
||||
}
|
||||
|
||||
/// Date/time from a serial. `None` for negative or too-large serials.
|
||||
pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option<DateTime> {
|
||||
if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) {
|
||||
@@ -384,4 +421,32 @@ mod tests {
|
||||
assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_dates_count_real_days() {
|
||||
let s = DateSystem::D1900;
|
||||
// Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31.
|
||||
for (serial, ymd) in
|
||||
[(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))]
|
||||
{
|
||||
let d = datetime_from_serial(s, serial as f64).unwrap();
|
||||
assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}");
|
||||
assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}");
|
||||
}
|
||||
assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None);
|
||||
// The 1904 system has no offset; 1899-12-30 stands for a time's date part there too.
|
||||
let s = DateSystem::D1904;
|
||||
let d = datetime_from_serial(s, 0.5).unwrap();
|
||||
assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod addr;
|
||||
pub mod arith;
|
||||
pub mod color;
|
||||
pub mod date;
|
||||
pub mod parse;
|
||||
@@ -16,4 +17,4 @@ pub use addr::{
|
||||
};
|
||||
pub use date::DateSystem;
|
||||
pub use region::Region;
|
||||
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
|
||||
pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
|
||||
|
||||
@@ -49,6 +49,19 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option<f64> {
|
||||
parse_numeric(s.trim(), sys).map(|(n, _)| n)
|
||||
}
|
||||
|
||||
/// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users
|
||||
/// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5,
|
||||
/// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse
|
||||
/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. So does `+`
|
||||
/// before a time (`+1:30`), while `-1:30` is a formula (rows 1 to 30), as Excel for the web does.
|
||||
pub fn starts_formula(input: &str) -> bool {
|
||||
input.starts_with('=')
|
||||
|| (input.len() > 1
|
||||
&& input.starts_with(['+', '-'])
|
||||
&& parse_number_text(input).is_none()
|
||||
&& !input.strip_prefix('+').is_some_and(|time| time.contains(':') && parse_number_text(time).is_some()))
|
||||
}
|
||||
|
||||
/// Text that Excel's "Number Stored as Text" check flags: it would be a number if typed (signs,
|
||||
/// thousands separators, currency, percent, exponent, a parenthesised negative). Dates, times and
|
||||
/// fractions kept as text are not flagged, as in Excel.
|
||||
@@ -577,6 +590,19 @@ mod tests {
|
||||
assert_eq!(p("1.2.3.4").value, Value::text("1.2.3.4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() {
|
||||
// #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did.
|
||||
for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--", "-1:30", "+1/30", "-1/30"] {
|
||||
assert!(starts_formula(s), "{s}");
|
||||
}
|
||||
// Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or
|
||||
// apostrophe, `+` before a time and other text stay text.
|
||||
for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b", "+1:30", "+0:30:15"] {
|
||||
assert!(!starts_formula(s), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_and_times() {
|
||||
assert_eq!(p("10/7/2026").value, Value::Number(46302.0));
|
||||
|
||||
@@ -103,6 +103,10 @@ impl fmt::Display for CellError {
|
||||
}
|
||||
|
||||
/// A 2-D array of values (row-major). Always at least 1×1.
|
||||
///
|
||||
/// Indexing assumes `data` holds `rows × cols` values. Loading doesn't check that (the fields are
|
||||
/// public, so a file can say anything): whoever loads values from a file checks them with
|
||||
/// [`Value::is_well_formed`] and repairs what fails (#2160).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Array {
|
||||
pub rows: usize,
|
||||
@@ -208,6 +212,23 @@ impl From<Array> for Value {
|
||||
}
|
||||
|
||||
impl Value {
|
||||
/// Whether every array in this value, including arrays nested in another array's values, is
|
||||
/// at least 1×1 and holds exactly `rows × cols` values, as indexing assumes. Values built in
|
||||
/// code always are; values loaded from a file may not be (#2160). Walks without recursion,
|
||||
/// so a deeply nested value can't overflow the stack.
|
||||
pub fn is_well_formed(&self) -> bool {
|
||||
let mut pending = vec![self];
|
||||
while let Some(v) = pending.pop() {
|
||||
if let Value::Array(a) = v {
|
||||
if a.rows == 0 || a.cols == 0 || a.rows.checked_mul(a.cols) != Some(a.data.len()) {
|
||||
return false;
|
||||
}
|
||||
pending.extend(a.data.iter().filter(|x| matches!(x, Value::Array(_))));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A number, or `#NUM!` when it is NaN or infinite (Excel never stores those).
|
||||
pub fn number(v: f64) -> Value {
|
||||
if v.is_finite() { Value::Number(if v == 0.0 { 0.0 } else { v }) } else { Value::Error(CellError::Num) }
|
||||
@@ -434,12 +455,16 @@ fn secondary_weights(s: &str) -> impl Iterator<Item = u16> + '_ {
|
||||
}
|
||||
|
||||
/// Sorting order used by Sort (ascending): numbers, text, booleans, errors, then blanks last.
|
||||
/// Numbers compare exactly, not at the 15 digits of [`compare`]. Observed in Excel 365: SORT,
|
||||
/// SORTBY, Data > Sort, the AutoFilter sort and table sort all put 0.3 before `=0.1+0.2`
|
||||
/// (0.30000000000000004) ascending and after it descending, whatever the input order.
|
||||
pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
|
||||
match (a, b) {
|
||||
(Value::Empty, Value::Empty) => Ordering::Equal,
|
||||
(Value::Empty, _) => Ordering::Greater,
|
||||
(_, Value::Empty) => Ordering::Less,
|
||||
(Value::Error(_), Value::Error(_)) => Ordering::Equal,
|
||||
(Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
_ => compare(a, b),
|
||||
}
|
||||
}
|
||||
@@ -497,10 +522,56 @@ pub fn sci_text(n: f64, sig: usize) -> String {
|
||||
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
|
||||
}
|
||||
|
||||
/// Longest text a cell can hold, in UTF-16 code units.
|
||||
pub const MAX_TEXT_CHARS: usize = 32_767;
|
||||
|
||||
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
|
||||
pub fn cap_text(mut s: String) -> String {
|
||||
if s.len() > MAX_TEXT_CHARS {
|
||||
let mut units = 0;
|
||||
if let Some((i, _)) = s.char_indices().find(|(_, c)| {
|
||||
units += c.len_utf16();
|
||||
units > MAX_TEXT_CHARS
|
||||
}) {
|
||||
s.truncate(i);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through.
|
||||
pub fn cap_value(v: Value) -> Value {
|
||||
match v {
|
||||
Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())),
|
||||
v => v,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_loaded_array_is_checked_by_is_well_formed() {
|
||||
// #2160: indexing assumes `data.len() == rows * cols`. A file can say otherwise; loading
|
||||
// keeps what it says and `is_well_formed` tells the loader to repair it.
|
||||
let number = |n: f64| Value::Number(n);
|
||||
let loaded = |json: &str| serde_json::from_str::<Value>(json).unwrap();
|
||||
for bad in [
|
||||
r#"{"t":"Array","v":{"rows":3,"cols":2,"data":[{"t":"Number","v":1.0}]}}"#,
|
||||
r#"{"t":"Array","v":{"rows":0,"cols":1,"data":[]}}"#,
|
||||
r#"{"t":"Array","v":{"rows":18446744073709551615,"cols":2,"data":[]}}"#,
|
||||
// Nested in a well-formed array.
|
||||
r#"{"t":"Array","v":{"rows":1,"cols":2,"data":[{"t":"Number","v":1.0},{"t":"Array","v":{"rows":2,"cols":2,"data":[]}}]}}"#,
|
||||
] {
|
||||
assert!(!loaded(bad).is_well_formed(), "{bad}");
|
||||
}
|
||||
let ok = Value::from(Array::new(1, 2, vec![number(1.0), Value::from(Array::scalar(number(2.0)))]).unwrap());
|
||||
let back = loaded(&serde_json::to_string(&ok).unwrap());
|
||||
assert_eq!(back, ok, "what is saved loads back unchanged");
|
||||
assert!(back.is_well_formed() && number(1.0).is_well_formed() && Value::Empty.is_well_formed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_text() {
|
||||
assert_eq!(number_to_text(1.0), "1");
|
||||
@@ -580,6 +651,16 @@ mod tests {
|
||||
assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() {
|
||||
let face = "😀";
|
||||
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS));
|
||||
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS));
|
||||
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face));
|
||||
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1));
|
||||
assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arabic_diacritics_sort_with_their_base_letter() {
|
||||
assert_eq!(compare_text("بَاب", "بيت"), Ordering::Less);
|
||||
@@ -775,6 +856,19 @@ mod tests {
|
||||
assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_orders_numbers_exactly() {
|
||||
let num = Value::Number;
|
||||
let e = 0.1 + 0.2;
|
||||
assert_eq!(sort_compare(&num(0.3), &num(e)), Ordering::Less);
|
||||
assert_eq!(sort_compare(&num(e), &num(0.3)), Ordering::Greater);
|
||||
assert_eq!(sort_compare(&num(100.0), &num(100.0 + 1e-14)), Ordering::Less);
|
||||
assert_eq!(sort_compare(&num(0.0), &num(-0.0)), Ordering::Equal);
|
||||
assert_eq!(sort_compare(&num(1.0), &Value::from("a")), Ordering::Less);
|
||||
// `=` keeps its 15-digit comparison.
|
||||
assert_eq!(compare(&num(0.3), &num(e)), Ordering::Equal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrays() -> Result<(), std::io::Error> {
|
||||
let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).ok_or_else(|| std::io::Error::other("valid array"))?;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "gridcraft-dax"
|
||||
# A first release of this crate, not the workspace release line: nothing depends on a published
|
||||
# version of it yet, and 0.1.0 says what it is — new.
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "GridCraft DAX language: lexer, Pratt parser, syntax tree and canonical printer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
# Calendar arithmetic (date serials, month lengths, leap years) goes through chrono on every
|
||||
# target, as AGENTS.md requires. The web build has no clock and uses the fixed fallback in
|
||||
# `eval/support.rs`, but the date types it needs build for wasm too (`gridcraft-core` does the
|
||||
# same with the same workspace dependency).
|
||||
chrono = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# The browser clock for NOW/TODAY under wasm, the same dependency `crates/core` uses: the standard
|
||||
# library clock traps there, and `eval/support.rs` would otherwise freeze at 1970.
|
||||
js-sys = "0.3"
|
||||
|
||||
[[example]]
|
||||
name = "parse"
|
||||
# Cargo does not test examples by default; this one carries assertions on the query-to-expression
|
||||
# fallback, so it has to run under `cargo test`.
|
||||
test = true
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,430 @@
|
||||
# gridcraft-dax
|
||||
|
||||
The DAX language for GridCraft: a tokenizer, a Pratt parser, a syntax tree, a canonical printer,
|
||||
the function catalog for every dax.guide category with static call validation, the static type surface (types,
|
||||
literals, inference and operator result tables), the full DAX statement/query grammar, a model
|
||||
evaluator, a columnar model store and a model-backed PivotTable renderer. It has no dependency on
|
||||
the GridCraft engine.
|
||||
|
||||
```rust
|
||||
use gridcraft_dax::{ParseError, parse_expression, print_expression};
|
||||
|
||||
fn main() -> Result<(), ParseError> {
|
||||
let expr = parse_expression("1 + 2 * 3")?;
|
||||
assert_eq!(print_expression(&expr), "1 + 2 * 3");
|
||||
|
||||
let query = gridcraft_dax::parse_query(
|
||||
"DEFINE MEASURE Sales[Margin] = [Sales Amount] - [Total Cost] EVALUATE Sales ORDER BY [Margin] DESC",
|
||||
)?;
|
||||
assert!(gridcraft_dax::print_query(&query).starts_with("DEFINE\n MEASURE Sales[Margin] ="));
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Public API
|
||||
|
||||
| Item | Meaning |
|
||||
| --- | --- |
|
||||
| `parse_expression(&str) -> Result<Expr, ParseError>` | Parse one expression. One leading `=` (as typed in some editors) is accepted and ignored. |
|
||||
| `print_expression(&Expr) -> String` | Canonical text. |
|
||||
| `parse_query(&str) -> Result<Query, ParseError>` | Parse a query: optional `DEFINE`, then one or more `EVALUATE` statements. `EVALUATE <expr>` alone keeps working. |
|
||||
| `print_query(&Query) -> String` | Canonical multi-line query text. |
|
||||
| `tokenize(&str) -> Result<Vec<Token>, LexError>` | Tokens with byte spans, including `Eof`. |
|
||||
| `ParseError { message, span }` / `LexError { message, span }` | `Display + std::error::Error`; the lexer error converts with `From`. |
|
||||
| `ast::{Expr, ExprKind, Literal, DateTimeLiteral, Name, NameRef, NameStyle, Call, UnaryOp, BinaryOp, Span}` | Expression syntax tree. |
|
||||
| `ast::{Query, Define, Definition, MeasureDef, ColumnDef, TableDef, VarDef, FunctionDef, MParameterDef}` | Query/`DEFINE` tree. |
|
||||
| `ast::{Evaluate, OrderItem, StartValue, SortDirection}` | `EVALUATE`, `ORDER BY` and `START AT`. |
|
||||
| `ast::{FunctionParam, ParameterType, ParameterSubtype, PassingMode}` | `FUNCTION` parameters and annotations. |
|
||||
| `ast::{VisualShape, Axis, AxisKind, AxisGroup, AxisOrderItem}` | `WITH VISUAL SHAPE`, `AXIS`, `GROUP`, `TOTAL`. |
|
||||
| `functions::{catalog, lookup}` | Every catalogued function, looked up case-insensitively. |
|
||||
| `functions::{FunctionSpec, FunctionCategory, ParamKind, ReturnType, BlankPolicy, FunctionFlags, Parameter, Overload}` | Catalog record types. |
|
||||
| `validate_call(&Call) -> Vec<ValidationError>` | Arity/kind checks for one call; empty for valid or unknown functions. |
|
||||
| `validate_expression(&Expr) -> Vec<ValidationError>` | Walks the tree and reports every invalid known-function call with its span. |
|
||||
| `types::{DataType, PseudoType, InferredType, TypeMetadata, TypeError}` | The eight DAX types, the BLANK/Table pseudo-types, inference results and static type errors. |
|
||||
| `types::{literal_type, infer_type, unary_type, binary_type, arithmetic_type, comparison_coercion, comparison_compatible, comparison_type}` | Literal classification, static inference and the documented operator/coercion tables. |
|
||||
| `model::{DataModel, ModelTable, ModelColumn, Measure, Relationship, parse_measure}` | Metadata + inline-row model, formula parsing and name validation. |
|
||||
| `binder::{Binder, BoundExpr, BoundMeasure, bind_formula}` | Name/measure/column resolution, dependency graph and cycle rejection. |
|
||||
| `eval::{Evaluator, FilterContext}` | Expression/measure evaluator over `DataModel`; a catalogued function whose family is not linked reports "not implemented". |
|
||||
| `pivot::{pivot, pivot_cross, pivot_fields}` | Row/column grouping helpers. |
|
||||
| `pivot_table::PivotTable` | Power Pivot-style row/column/filter/value layout with subtotals and grand totals. |
|
||||
| `storage::{ModelStorage, TableStorage, ColumnStorage, ColumnData}` | Columnar, dictionary-encoded model store with filter/aggregate/relationship indexes. |
|
||||
| `MAX_INPUT_LEN` (8192 bytes, expressions) / `MAX_QUERY_LEN` (1 MiB, queries) / `MAX_DEPTH` (256) | Limits enforced with errors. |
|
||||
|
||||
### Syntax tree
|
||||
|
||||
```text
|
||||
Expr { kind: ExprKind, span: Span }
|
||||
ExprKind =
|
||||
Literal(Literal) Integer(i64) | Decimal(f64)
|
||||
| DateTime(DateTimeLiteral)
|
||||
| String(String) | Boolean(bool)
|
||||
| Name(NameRef) table: Option<Name>, name: Name
|
||||
| Call(Call) name: Name, args: Vec<Expr>
|
||||
| Unary { op, expr } op: UnaryOp (Plus | Neg | Not)
|
||||
| Binary { op, left, right } op: BinaryOp
|
||||
| Table(Vec<Expr>) { value, ... }
|
||||
| Tuple(Vec<Expr>) (value, ...)
|
||||
| VarReturn { vars, body } VAR a = 1 ... RETURN body
|
||||
|
||||
Query { define: Option<Define>, evaluates: Vec<Evaluate> }
|
||||
Define { items: Vec<Definition> }
|
||||
Definition =
|
||||
Measure(MeasureDef) name: NameRef, expr: Expr
|
||||
| Column(ColumnDef) name: NameRef, expr: Expr
|
||||
| Table(TableDef) name: Name, expr: Expr, visual_shape: Option<VisualShape>
|
||||
| Var(VarDef) name: Name, expr: Expr
|
||||
| Function(FunctionDef) name: Name, params: Vec<FunctionParam>, body: Expr
|
||||
| MParameter(MParameterDef) name: Name, expr: Expr
|
||||
|
||||
Evaluate { table: Expr, order_by: Vec<OrderItem>, start_at: Vec<StartValue> }
|
||||
OrderItem { expr: Expr, direction: SortDirection }
|
||||
StartValue = Literal(Literal) | Parameter(Name) -- @name
|
||||
FunctionParam { name, ty, subtype, passing, default }
|
||||
VisualShape { axes: Vec<Axis>, densify: Option<String> }
|
||||
Axis { kind: AxisKind (Rows | Columns), groups: Vec<AxisGroup>, order_by: Vec<AxisOrderItem> }
|
||||
AxisGroup { columns: Vec<NameRef>, total: NameRef }
|
||||
AxisOrderItem { column: NameRef, direction: SortDirection }
|
||||
```
|
||||
|
||||
`Span` is a half-open byte range into the source. `Expr::walk` visits nodes depth-first with an
|
||||
explicit stack. `Expr` equality compares `ExprKind` only: spans are ignored, so
|
||||
`parse(print(e)) == e` for every expression the parser produces.
|
||||
|
||||
`Name` keeps the source spelling and quoting style (`Bare`, `Quoted`, `Bracketed`); the printer
|
||||
reproduces that style. A `NameRef` is a table-qualified reference (`'Sales'[Amount]`) or an
|
||||
unqualified name (`[Amount]`, `Total`, `'Sales'`). `Call` also keeps the spelling (`Sum` stays
|
||||
`Sum`).
|
||||
|
||||
Parentheses are grouping, not AST nodes. A parenthesised comma list is a `Tuple`; inside
|
||||
`{ ... }` those tuples are the rows of a `Table`.
|
||||
|
||||
## Grammar
|
||||
|
||||
```text
|
||||
expression := prefix (binary_operator prefix)* -- precedence-climbing, see the table
|
||||
prefix := "+" prefix | "-" prefix | NOT prefix | primary
|
||||
primary := INTEGER | DECIMAL | STRING | TRUE | FALSE
|
||||
| dt STRING -- validated date/time literal
|
||||
| name
|
||||
| name "(" [ expression ("," expression)* ] ")"
|
||||
| table-qualified-name
|
||||
| "(" expression ")"
|
||||
| "(" expression "," expression ("," expression)* ")"
|
||||
| "{" [ expression ("," expression)* ] "}"
|
||||
| VAR var_name "=" expression { VAR var_name "=" expression } RETURN expression
|
||||
name := IDENT | "[" column "]" | "'" table "'"
|
||||
qualified := (IDENT | "'" table "'") "[" column "]"
|
||||
|
||||
query := [ define ] evaluate { evaluate } [ ";" ]
|
||||
define := DEFINE definition { definition }
|
||||
definition := MEASURE table '[' name ']' "=" expression
|
||||
| COLUMN table '[' name ']' "=" expression
|
||||
| TABLE table_name "=" expression [ visual_shape ]
|
||||
| VAR var_name "=" expression
|
||||
| FUNCTION function_name "=" "(" [ param { "," param } ] ")" "=>" expression
|
||||
| MPARAMETER mparameter_name "=" expression
|
||||
param := param_name [ ":" [ type ] [ subtype ] [ passing_mode ] ] [ "=" expression ]
|
||||
evaluate := EVALUATE expression [ order_by ] [ start_at ]
|
||||
order_by := ORDER BY order_item { "," order_item }
|
||||
order_item := expression [ ASC | DESC ]
|
||||
start_at := START AT start_value { "," start_value }
|
||||
start_value := literal | [ "+" | "-" ] number | "@" name
|
||||
visual_shape := WITH VISUAL SHAPE axis { axis } [ DENSIFY STRING ]
|
||||
axis := AXIS ( ROWS | COLUMNS )
|
||||
group { group }
|
||||
ORDER BY column_ref [ ASC | DESC ] { "," column_ref [ ASC | DESC ] }
|
||||
group := GROUP column_ref { "," column_ref } TOTAL column_ref
|
||||
column_ref := "[" name "]" | table "[" name "]"
|
||||
```
|
||||
|
||||
Statement keywords are matched case-insensitively. There are no statement terminators in the
|
||||
documented grammar: `MEASURE`, `COLUMN`, `TABLE`, `VAR`, `FUNCTION`, `MPARAMETER` and the
|
||||
`EVALUATE` token bound definition bodies and separate statements, so no newline is needed.
|
||||
One or more trailing `;` are accepted as a recovery extension. The `DEFINE` block is optional but
|
||||
requires at least one entry and must be followed by at least one `EVALUATE`. Duplicate definition
|
||||
names and forward/backward references are accepted; resolution is a semantic concern.
|
||||
|
||||
The shape above is illustrative: the Pratt parser applies the precedence and associativity
|
||||
table below rather than a fixed grammar cascade.
|
||||
|
||||
`*` is not a wildcard token: it is only the multiplication operator.
|
||||
|
||||
### Statements
|
||||
|
||||
- `EVALUATE` takes any table expression. `ORDER BY` sorts the result and defaults to `ASC`;
|
||||
`START AT` requires `ORDER BY`, takes literals or `@parameter` references, and may not have
|
||||
more values than `ORDER BY` items.
|
||||
- `DEFINE MEASURE`/`COLUMN` names are `<table>[<name>]`; `TABLE`, `FUNCTION` and `MPARAMETER`
|
||||
names are bare or single-quoted. `VAR` names are bare only. A query-scoped `VAR` has no
|
||||
`RETURN`; an expression-level `VAR ... RETURN ...` requires one. `RETURN` without a preceding
|
||||
`VAR` is an error.
|
||||
- `FUNCTION` parameters may declare a type (`ANYVAL`, `SCALAR`, `TABLE`, `ANYREF`,
|
||||
`CALENDARREF`, `COLUMNREF`, `MEASUREREF`, `TABLEREF`), a scalar subtype (`BOOLEAN`,
|
||||
`DATETIME`, `DECIMAL`, `DOUBLE`, `INT64`, `NUMERIC`, `STRING`, `VARIANT`), a passing mode
|
||||
(`VAL`/`EXPR`) and a default expression. Only `SCALAR` (or an omitted type) accepts a subtype.
|
||||
- `WITH VISUAL SHAPE` is valid only as the suffix of a `DEFINE TABLE`. It needs one or two axes
|
||||
(`AXIS ROWS`, `AXIS COLUMNS`, no duplicates), each with at least one `GROUP ... TOTAL` level
|
||||
and an `ORDER BY` list. `DENSIFY "column"` is optional and last, and takes a double-quoted
|
||||
string, not a bracketed reference. `AXIS ROWPAGES` is not part of the grammar.
|
||||
- `MPARAMETER` is the Power BI dynamic M-parameter binding and is accepted as a `DEFINE` entry
|
||||
even though Microsoft's `DEFINE` grammar omits it.
|
||||
|
||||
### Case and escapes
|
||||
|
||||
- Keywords (`NOT`, `IN`, `EVALUATE`, `TRUE`, `FALSE`, and every statement keyword) are
|
||||
case-insensitive. `TRUE`/`FALSE` are literals unless followed by `(` (then they are calls to a
|
||||
function of that name). The printer writes statement keywords uppercase and keeps identifier
|
||||
spelling.
|
||||
- Bare identifiers keep their spelling. Function names may contain `.` (`STDEV.P`).
|
||||
- Single-quoted table identifiers double an embedded quote: `'It''s'`.
|
||||
- Bracketed columns double an embedded `]`: `[A]]B]`.
|
||||
- String literals double an embedded quote: `"a""b"`.
|
||||
- Number literals are typed: a digit-only literal is an `Integer` (`42`, parsed as `i64`), while
|
||||
a decimal point or exponent is a `Decimal` (`3.14`, `.5`, `1.`, `1e3`, `1.5E-3`, parsed as
|
||||
`f64`). The sign is the unary operator, never part of the token. Values must be finite; an
|
||||
integer that does not fit `i64`, or a decimal that overflows `f64`, is a lexer error with a
|
||||
span. `Decimal` printing always keeps a decimal point or exponent (`1000.0`, `1e-6`) so the
|
||||
text re-lexes as a `Decimal`.
|
||||
- Date/time literals are `dt"YYYY-MM-DD"`, `dt"YYYY-MM-DDThh:mm:ss"` and
|
||||
`dt"YYYY-MM-DD hh:mm:ss"`. The `dt` prefix is matched case-insensitively but must be adjacent
|
||||
to the quote; the printer emits lowercase `dt` and padded components. Unpadded month/day/time
|
||||
components are accepted (`dt"2015-1-9T2:3:0"`). Timezone offsets, fractional seconds,
|
||||
time-only forms, wrong-case `t`, and invalid calendar dates (including non-leap `1900-02-29`)
|
||||
are lexer errors.
|
||||
- `BLANK` is an ordinary identifier. `BLANK()` is a zero-argument call; there is no BLANK literal.
|
||||
- Comments: `// line`, `-- line`, and `/* block */` (blocks do not nest).
|
||||
|
||||
## Operators
|
||||
|
||||
Precedence from the operator table (tighter first); operators of equal precedence evaluate left to
|
||||
right, including `^`:
|
||||
|
||||
| Level | Operators | Associativity |
|
||||
| --- | --- | --- |
|
||||
| 1 | grouping `()`, function calls | — |
|
||||
| 2 | `^` | left |
|
||||
| 3 | unary `+`, `-` | prefix |
|
||||
| 4 | `*`, `/` | left |
|
||||
| 5 | binary `+`, `-` | left |
|
||||
| 6 | `&` | left |
|
||||
| 7 | `=`, `==`, `<>`, `<`, `>`, `<=`, `>=`, `IN` | left |
|
||||
| 8 | `NOT` | prefix |
|
||||
| 9 | `&&` | left |
|
||||
| 10 | `\|\|` | left |
|
||||
|
||||
`=` coerces types at evaluation time; `==` is strict equality. This crate only records which
|
||||
operator was written. `IN` is a comparison at the same level as `=`, so `1 + 2 IN { 3 }` parses as
|
||||
`(1 + 2) IN { 3 }`, and it takes a list (`expr IN { v1, v2 }`) or a table expression
|
||||
(`expr IN VALUES(T[Col])`).
|
||||
|
||||
Microsoft's operator reference states that operators of equal precedence are ordered from left to
|
||||
right, and `^` shares no tier with another operator, so a chain groups left: `2^3^2` is `(2^3)^2` =
|
||||
64, the value Excel and Power Pivot produce as well. Unary minus binds looser than `^`: `-2^2` parses
|
||||
as `-(2^2)`.
|
||||
|
||||
## Data types and static inference
|
||||
|
||||
`types::DataType` is exactly the eight dax.guide types: `Binary`, `Boolean`, `Currency`,
|
||||
`DateTime`, `Decimal`, `Integer`, `String`, `Variant`. `PseudoType` adds the two Microsoft DAX
|
||||
types that are not in that list, `Blank` and `Table`; they are inference results, not
|
||||
`DataType` variants. Each type (including the pseudo-types) has a `TypeMetadata` row with its
|
||||
internal representation, literal syntax (or `None`), range, precision and notes. Literal
|
||||
availability is `Boolean`, `DateTime`, `Decimal`, `Integer`, `String`; `Binary`, `Currency` and
|
||||
`Variant` have no literal, and neither does BLANK (`BLANK()` is a function).
|
||||
|
||||
`literal_type(&Literal)` maps a literal to its `DataType`. `infer_type(&Expr) ->
|
||||
Result<InferredType, TypeError>` infers literals, unary `+`/`-`/`NOT`, binary operators,
|
||||
`TRUE()`/`FALSE()`/`BLANK()` calls, table constructors, and every catalogued function's documented
|
||||
`ReturnType` (`Table` for table functions, `Blank` for BLANK, `Unknown` for `Any`/unknown names).
|
||||
Name references still return `InferredType::Unknown` because they need the model. `Unknown` is not
|
||||
a DAX type; it is the absence of static information.
|
||||
|
||||
The arithmetic and comparison result tables are transcribed from the published DAX operator
|
||||
reference for `Integer`, `Currency`, `Decimal` ("Real") and `DateTime`:
|
||||
`arithmetic_type` implements `+`, `-`, `*`, `/` and `^` (a double). The quirks are preserved
|
||||
rather than normalised: `Integer * DateTime -> Integer`, `Currency * Currency -> Decimal`,
|
||||
`DateTime - DateTime -> DateTime`, and a `DateTime` on the left of `*` has no published row and is
|
||||
a `TypeError`. `&` yields `String`; `&&`, `||`, comparisons and `IN` yield `Boolean`; unary `+`
|
||||
and `-` preserve the numeric type. `Variant` propagates, and BLANK stays polymorphic (for example
|
||||
`BLANK() + 5` is `Integer` while `BLANK() * 5` is `Blank`).
|
||||
|
||||
`comparison_coercion` models `=`, `<>` and ordering: BLANK is coerced to `0`, `""` or `FALSE` for
|
||||
the other operand's type, and String/Boolean compared with a numeric type is a `TypeError` (the
|
||||
engine errors; dax.guide also documents a conflicting type rank). `comparison_compatible` and
|
||||
`comparison_type` also cover `==`, which is strict and does not coerce BLANK. Excel's embedded
|
||||
engine rejects `==` altogether, but dax.guide documents it and this crate parses it.
|
||||
|
||||
This is static typing only. Text-to-number/date/Boolean parsing, BLANK substitution and truth
|
||||
tables, `5/BLANK()` (Infinity), `0/BLANK()` (NaN), Currency rounding, runtime integer overflow,
|
||||
IEEE equality and string collation belong to the evaluator. The module documentation lists the
|
||||
documented conflicts (Currency/Integer endpoints, the DateTime minimum, mixed-type comparisons,
|
||||
and `dt` literal engine support) instead of hiding them behind one total order.
|
||||
|
||||
## Limits, errors and printing
|
||||
|
||||
Expressions are capped at 8192 bytes, queries at 1 MiB, and expression nesting at 256 levels; each
|
||||
limit produces an error, never a stack overflow. The printer and `Expr::walk` use explicit stacks, and
|
||||
the parser's binary loop is iterative, so a left-associated chain does not recurse — but the chain
|
||||
still grows the tree one level per operator, and the depth check applies to it: a flat
|
||||
`1 + 1 + ... + 1` with more than about 256 terms is rejected as too deeply nested (asserted for a
|
||||
1,000-term chain in `src/tests.rs`). Long generated `&&`, `||` or `&` chains hit the same limit.
|
||||
|
||||
Numeric literal overflow (an integer outside `i64`, or a decimal outside finite `f64`) and invalid
|
||||
date/time literals are lexer errors with the literal's span. Errors carry `message` and a byte
|
||||
`span`; `Display` includes both. The canonical printer uses
|
||||
spaces around binary operators, `, ` between arguments/items, and adds parentheses only where
|
||||
precedence or associativity requires them. Re-parsing canonical text yields the same AST.
|
||||
|
||||
`print_query` prints `DEFINE` entries indented one level, each following `EVALUATE` on its own
|
||||
line with indented `ORDER BY`/`START AT` clauses, and visual-shape axes, groups and `DENSIFY`
|
||||
indented under their `TABLE`. The simple `EVALUATE <expression>` form stays on one line, so
|
||||
`print_query(parse_query("EVALUATE 1 + 2"))` is still `EVALUATE 1 + 2`. An expression-level
|
||||
`VAR ... RETURN ...` prints on one line and is parenthesised when it is an operand, because it
|
||||
binds looser than every operator. All printing remains iterative.
|
||||
|
||||
## Function catalog
|
||||
|
||||
`functions::catalog()` returns every function of every
|
||||
[dax.guide function category](https://dax.guide/functions/), in category order. Each
|
||||
`FunctionSpec` records the exact arity, parameter kinds, overloads (including variadic
|
||||
functions), return type, iterator/volatile/not-recommended/Excel flags, description and
|
||||
parseable examples. Each record carries its descriptive signature (`params`, with `optional`
|
||||
markers), exact `overloads` (fixed or variadic), `return_type`, `flags` (`iterator`, `volatile`,
|
||||
`not_recommended`, `excel_compatible`, `direct_query_limited`), `sugar_of`, `blank_policy`,
|
||||
`description` and `examples`. Every example in the catalog parses with `parse_expression`.
|
||||
|
||||
Descriptions and examples are original summaries written for GridCraft. Microsoft's DAX function
|
||||
documentation is a behavioural reference only: no sentence, definition or sample argument list is
|
||||
copied from it (or from dax.guide, which republishes Microsoft's wording). Write what the function
|
||||
returns, what its arguments mean and which edge case it handles, in the project's own voice.
|
||||
|
||||
| Category | Functions |
|
||||
| --- | ---: |
|
||||
| Aggregation | 22 |
|
||||
| Date and Time | 24 |
|
||||
| Filter | 29 |
|
||||
| Financial | 51 |
|
||||
| Information | 114 |
|
||||
| Logical | 13 |
|
||||
| Math and Trig | 49 |
|
||||
| Other | 16 |
|
||||
| Parent-child | 5 |
|
||||
| Relationship management | 4 |
|
||||
| Statistical | 43 |
|
||||
| Table manipulation | 35 |
|
||||
| Text | 23 |
|
||||
| Time Intelligence | 45 |
|
||||
| Visual calculations | 11 |
|
||||
| **Total** | **484** |
|
||||
|
||||
| Function | Arity | Iterator | Sugar of | Blank | Excel | Notes |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `APPROXIMATEDISTINCTCOUNT` | 1 | no | — | BLANK | no | HyperLogLog / DirectQuery pushdown; column reference only. |
|
||||
| `AVERAGE` | 1 | no | `AVERAGEX` | unspecified | yes | Ignores blanks, includes zero; sources disagree on the empty/all-blank result. |
|
||||
| `AVERAGEA` | 1 | no | — | unspecified | yes | Booleans are 1/0, any text is 0 and a BLANK cell is 0 in the denominator (Microsoft's 22/5 example); dax.guide marks it not recommended. |
|
||||
| `AVERAGEX` | 2 | yes | — | BLANK | yes | Row context; blanks ignored, zeros included; empty set observed BLANK. |
|
||||
| `COUNT` | 1 | no | `COUNTX` | BLANK | yes | Counts numbers, dates and strings; empty strings count, booleans do not. |
|
||||
| `COUNTA` | 1 | no | `COUNTAX` | BLANK | yes | Counts non-blank values including booleans. |
|
||||
| `COUNTAX` | 2 | yes | — | BLANK | yes | Row context; booleans count. |
|
||||
| `COUNTBLANK` | 1 | no | — | unspecified | yes | Empty string counts as blank; dax.guide says never 0, Microsoft Learn says 0 when rows exist. |
|
||||
| `COUNTROWS` | 0–1 | no | — | BLANK | yes\* | \*The zero-argument form is rejected by Excel's embedded engine; pass a table there. |
|
||||
| `COUNTX` | 2 | yes | — | BLANK | yes | Row context; booleans are not counted. |
|
||||
| `DISTINCTCOUNT` | 1 | no | — | BLANK | yes | BLANK is one distinct value; totals are non-additive. |
|
||||
| `DISTINCTCOUNTNOBLANK` | 1 | no | `DISTINCTCOUNT` | unspecified | no | Excludes BLANK; rejected by Excel's embedded engine. |
|
||||
| `MAX` | 1–2 | no | `MAXX`\* | unspecified | yes | \*Only the one-argument column overload is sugar. Two scalars treat BLANK as significant per dax.guide, as 0 per Microsoft Learn. |
|
||||
| `MAXA` | 1 | no | — | unspecified | yes | TRUE/FALSE become 1/0; empty result conflicts across sources. |
|
||||
| `MAXX` | 2–3 | yes | — | unspecified | yes | Optional third `Variant` compares mixed types per `ORDER BY DESC`. |
|
||||
| `MIN` | 1–2 | no | `MINX`\* | unspecified | yes | \*Only the one-argument column overload is sugar. Two scalars have the same BLANK conflict as `MAX`. |
|
||||
| `MINA` | 1 | no | — | unspecified | yes | TRUE/FALSE become 1/0; empty result conflicts across sources. |
|
||||
| `MINX` | 2–3 | yes | — | unspecified | yes | Optional third `Variant` compares mixed types per `ORDER BY ASC`. |
|
||||
| `PRODUCT` | 1 | no | `PRODUCTX` | BLANK | yes | Multiplies numeric cells, ignoring blanks, logical values and text. |
|
||||
| `PRODUCTX` | 2 | yes | — | BLANK | yes | Row context; ignores blank results, unlike the `*` operator. |
|
||||
| `SUM` | 1 | no | `SUMX` | BLANK | yes | Adds numeric cells, ignoring blanks, logical values and text. |
|
||||
| `SUMX` | 2 | yes | — | BLANK | yes | Row context; blanks, logical values and text ignored. |
|
||||
|
||||
`AVERAGEA`, `MAXA` and `MINA` use the X function internally but are not pure sugar: their
|
||||
boolean/text coercions differ, so `sugar_of` is `None`. `direct_query_limited` is `true` for all
|
||||
22 functions because Microsoft Learn excludes them from calculated columns and RLS rules in
|
||||
DirectQuery mode; `APPROXIMATEDISTINCTCOUNT` still supports DirectQuery pushdown in measures.
|
||||
|
||||
### Blank policies
|
||||
|
||||
- `BlankWhenEmpty` — the result is BLANK when there are no rows or no qualifying value. Used
|
||||
where dax.guide and the observed engine agree, including the observed empty-set results of
|
||||
`SUMX`, `AVERAGEX`, `COUNTX` and `PRODUCTX`.
|
||||
- `Unspecified` — dax.guide and Microsoft Learn disagree, or the sources are silent. This is
|
||||
deliberate: the catalog does not pick a winner for `AVERAGE`/`AVERAGEA`, `COUNTBLANK`,
|
||||
`MAX`/`MIN`/`MAXA`/`MINA` or `MAXX`/`MINX`.
|
||||
- `ZeroWhenRowsButNoMatch` — documents the Microsoft Learn rule. No function uses it today
|
||||
because no engine observation supported it; it stays in the enum for a future evaluator that
|
||||
needs to model the conflicting rule explicitly.
|
||||
|
||||
### Static validation
|
||||
|
||||
`validate_expression` walks the AST and reports every argument-count or argument-kind error for a
|
||||
catalogued function. Spans point at the offending argument for kind errors and at the whole call
|
||||
for arity errors; unknown functions are ignored but their arguments are still visited.
|
||||
|
||||
A `ParamKind::Column` argument must be a bracketed `NameRef` (`Sales[Amount]` or `[Amount]`), so
|
||||
`SUM ( 1 )` and `AVERAGE ( 1 + 1 )` are rejected. A `ParamKind::Table` argument is rejected when
|
||||
it is certainly not a table — a literal, an operator expression or a bracketed column reference —
|
||||
so `COUNTROWS ( 1 )` and `COUNTROWS ( Sales[Amount] )` fail while
|
||||
`COUNTROWS ( DISTINCT ( Sales[Region] ) )`, table variables and `{ 1, 2 }` are accepted.
|
||||
`COUNTROWS ()` is valid in the catalog (the Excel limitation is recorded on the function, not
|
||||
enforced here). `Date`, `Text`, `Number`, `Boolean`, `Function`, `Reference`, `Json`, `Variant`,
|
||||
`Expression`, `Scalar`, `Logical` and `Any` are not statically decidable: DAX's implicit
|
||||
coercions need the model, so they are recorded for documentation and future type checking only.
|
||||
Variadic overloads repeat their last parameter kind for every additional argument; the third
|
||||
`Variant` argument of `MAXX`/`MINX` accepts any expression.
|
||||
|
||||
## Model, binder and evaluator
|
||||
|
||||
`model::DataModel` is the metadata + inline-row view used by the binder and evaluator. JSON shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"tables": [{"name": "Sales", "columns": [{"name": "Region"}, {"name": "Amount"}],
|
||||
"rows": [["East", 10], ["West", 20]]}],
|
||||
"relationships": [],
|
||||
"measures": [{"name": "Total Sales", "formula": "SUM(Sales[Amount])", "table": "Sales"}]
|
||||
}
|
||||
```
|
||||
|
||||
`DataModel::parse_formulas` parses each measure and validates table/column/relationship names.
|
||||
`Binder::bind_expression` resolves `Table[Column]`, measures, variables and function calls;
|
||||
`Binder::bind_measure` and `Binder::dependency_graph` expose direct measure dependencies and reject
|
||||
cycles. `Evaluator::new` pre-binds the measures and evaluates scalar or table expressions with a
|
||||
`FilterContext`; `pivot::pivot` groups a measure by row fields.
|
||||
|
||||
The evaluator's core switch implements the scalar spine — literals, operators, `VAR`/`RETURN`,
|
||||
context transition, `CALCULATE`/`FILTER`/`ALL`/`VALUES`/`DISTINCT`/`SELECTEDVALUE`, the
|
||||
aggregations and their `*X` iterators, and the logical functions that need lazy arguments — over
|
||||
a columnar store (`storage`: typed columns, dictionary strings, null bitmaps, relationship
|
||||
indexes). `Evaluator::new` materializes the store once and uses it for filters, aggregates,
|
||||
`VALUES`/`DISTINCT`, `COUNTROWS` and `RELATED*` when `ModelStorage::is_faithful` holds; other
|
||||
models keep the row scan. The remaining catalogued functions arrive in family modules under
|
||||
`src/eval/`, one module per family, each registering itself through the evaluator's dispatch
|
||||
array; a family that is not linked reports the catalogued call as not implemented.
|
||||
|
||||
## Extending in later PRs
|
||||
|
||||
- Statement semantics (name resolution, duplicate-name shadowing, `START AT` value types,
|
||||
function overloading and recursion rules, visual-shape evaluation) are not checked here; the
|
||||
parser accepts what the grammar accepts. Query-defined tables/columns and `MPARAMETER` are
|
||||
engine-specific, and the crate records them without validating a model.
|
||||
- `Call`, `NameRef` and `NameStyle` keep spelling/quoting so catalog and type work can resolve
|
||||
names without re-lexing.
|
||||
- `types::infer_type` resolves every catalogued call through its documented `ReturnType`, plus
|
||||
literals, operators, `TRUE()`/`FALSE()`/`BLANK()` and `VAR`/`RETURN` blocks. `InferredType::Unknown`
|
||||
remains for names and functions whose return type is `Any`/unknown.
|
||||
- The binder resolves tables, columns, measures, variables and documented keyword parameters.
|
||||
Each evaluator family ships with its own integration suite under `tests/eval_*.rs`.
|
||||
|
||||
## Example
|
||||
|
||||
```sh
|
||||
cargo run -p gridcraft-dax --example parse -- "1 + 2 * 3"
|
||||
cargo run -p gridcraft-dax --example parse -- "EVALUATE SUM('Sales'[Amount])"
|
||||
cargo run -p gridcraft-dax --example parse -- "DEFINE MEASURE Sales[M] = SUM(Sales[Amount]) EVALUATE Sales ORDER BY [M] DESC"
|
||||
echo 'NOT TRUE || FALSE && TRUE' | cargo run -p gridcraft-dax --example parse
|
||||
```
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Parse DAX from the command line (or stdin), print its syntax tree and canonical text.
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo run -p gridcraft-dax --example parse -- "1 + 2 * 3"
|
||||
//! echo "EVALUATE SUM('Sales'[Amount])" | cargo run -p gridcraft-dax --example parse
|
||||
//! ```
|
||||
|
||||
use std::io::{self, Read};
|
||||
|
||||
use gridcraft_dax::{TokenKind, parse_expression, parse_query, print_expression, print_query, tokenize};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut text = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
|
||||
if text.trim().is_empty() {
|
||||
io::stdin().read_to_string(&mut text)?;
|
||||
}
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err("no DAX expression supplied; pass it as an argument or on stdin".into());
|
||||
}
|
||||
print!("{}", render(text)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parses and renders one input. Queries are preferred; when the query parser fails, a valid
|
||||
/// expression is still accepted (`DEFINE` is a legal bare name), and the query diagnostic is kept
|
||||
/// only when both parsers fail for input that starts with a query keyword.
|
||||
fn render(text: &str) -> Result<String, String> {
|
||||
match parse_query(text) {
|
||||
Ok(query) => Ok(format!("Query\n{query:#?}\nCanonical: {}\n", print_query(&query))),
|
||||
Err(query_error) => {
|
||||
let expr = match parse_expression(text) {
|
||||
Ok(expr) => expr,
|
||||
Err(expr_error) => {
|
||||
if starts_with_query_keyword(text) {
|
||||
return Err(query_error.to_string());
|
||||
}
|
||||
return Err(expr_error.to_string());
|
||||
}
|
||||
};
|
||||
Ok(format!("AST\n{expr:#?}\nCanonical: {}\n", print_expression(&expr)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn starts_with_query_keyword(text: &str) -> bool {
|
||||
tokenize(text).is_ok_and(|tokens| match tokens.first().map(|token| &token.kind) {
|
||||
Some(TokenKind::Evaluate) => true,
|
||||
Some(TokenKind::Ident(word)) => word.eq_ignore_ascii_case("DEFINE"),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn query_only_keywords_stay_on_the_query_parser() {
|
||||
assert!(starts_with_query_keyword("EVALUATE Sales"));
|
||||
assert!(starts_with_query_keyword("DEFINE MEASURE Sales[M] = 1 EVALUATE Sales"));
|
||||
assert!(starts_with_query_keyword(" define measure Sales[M] = 1"));
|
||||
assert!(!starts_with_query_keyword("SUM(Sales[Amount])"));
|
||||
// `DEFINE` alone is a valid expression, so the expression parser wins.
|
||||
assert!(render("DEFINE").expect("bare name expression").starts_with("AST"));
|
||||
let error = render("DEFINE MEASURE").expect_err("malformed query");
|
||||
assert!(error.contains("measure name"), "{error}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
//! DAX syntax tree.
|
||||
//!
|
||||
//! Every expression node carries a [`Span`] in byte offsets into the source text. Statement
|
||||
//! nodes (`DEFINE` entries, `EVALUATE`, `ORDER BY`, visual shapes) group expressions and names.
|
||||
//! [`Expr`] equality deliberately ignores spans (`PartialEq` compares [`ExprKind`] only), which
|
||||
//! makes the parser/printer round-trip invariant expressible as `parse(print(e)) == e`.
|
||||
|
||||
/// A half-open byte range `start..end` into the source text.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Span {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Span {
|
||||
pub const fn new(start: usize, end: usize) -> Self {
|
||||
Span { start, end }
|
||||
}
|
||||
|
||||
/// An empty span at byte offset 0.
|
||||
pub const fn empty() -> Self {
|
||||
Span { start: 0, end: 0 }
|
||||
}
|
||||
|
||||
pub const fn len(self) -> usize {
|
||||
self.end.saturating_sub(self.start)
|
||||
}
|
||||
|
||||
pub const fn is_empty(self) -> bool {
|
||||
self.start >= self.end
|
||||
}
|
||||
|
||||
/// The smallest span covering both operands.
|
||||
pub fn to(self, other: Span) -> Span {
|
||||
Span { start: self.start.min(other.start), end: self.end.max(other.end) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A `dt"..."` date/time literal.
|
||||
///
|
||||
/// Components are validated when the literal is lexed. The `has_time` flag distinguishes
|
||||
/// `dt"2023-05-19"` from `dt"2023-05-19T00:00:00"`, which are different literal forms even
|
||||
/// though they denote the same serial value.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct DateTimeLiteral {
|
||||
pub year: u32,
|
||||
pub month: u32,
|
||||
pub day: u32,
|
||||
pub hour: u32,
|
||||
pub minute: u32,
|
||||
pub second: u32,
|
||||
pub has_time: bool,
|
||||
}
|
||||
|
||||
impl DateTimeLiteral {
|
||||
/// Canonical `YYYY-MM-DD` / `YYYY-MM-DDThh:mm:ss` text, without the `dt` prefix or quotes.
|
||||
pub fn canonical(self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DateTimeLiteral {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)?;
|
||||
if self.has_time {
|
||||
write!(f, "T{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A DAX literal value.
|
||||
///
|
||||
/// Integer and Decimal are distinct literal kinds (not one numeric kind): `42` is an
|
||||
/// [`Literal::Integer`] and `42.0`, `42e0` are [`Literal::Decimal`] values. The sign of a
|
||||
/// negative number is the unary `-` operator, never part of the literal.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Literal {
|
||||
/// A 64-bit signed integer literal such as `42`.
|
||||
Integer(i64),
|
||||
/// An IEEE-754 double literal written with a decimal point or exponent: `3.14`, `.5`, `1e3`.
|
||||
Decimal(f64),
|
||||
/// A `dt"..."` literal.
|
||||
DateTime(DateTimeLiteral),
|
||||
String(String),
|
||||
Boolean(bool),
|
||||
}
|
||||
|
||||
/// How an identifier was written, so the printer can reproduce it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum NameStyle {
|
||||
/// `Sales`
|
||||
Bare,
|
||||
/// `'Sales Table'`
|
||||
Quoted,
|
||||
/// `[Amount]`
|
||||
Bracketed,
|
||||
}
|
||||
|
||||
/// A single identifier, preserving its source spelling and quoting style.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Name {
|
||||
/// Text with quoting removed and doubled quote/bracket escapes resolved.
|
||||
pub text: String,
|
||||
pub style: NameStyle,
|
||||
}
|
||||
|
||||
impl Name {
|
||||
pub fn bare(text: impl Into<String>) -> Self {
|
||||
Name { text: text.into(), style: NameStyle::Bare }
|
||||
}
|
||||
|
||||
pub fn quoted(text: impl Into<String>) -> Self {
|
||||
Name { text: text.into(), style: NameStyle::Quoted }
|
||||
}
|
||||
|
||||
pub fn bracketed(text: impl Into<String>) -> Self {
|
||||
Name { text: text.into(), style: NameStyle::Bracketed }
|
||||
}
|
||||
}
|
||||
|
||||
/// A name, optionally table-qualified: `'Sales'[Amount]`, `Sales[Amount]` or `[Amount]`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct NameRef {
|
||||
/// Table part of a column/measure reference.
|
||||
pub table: Option<Name>,
|
||||
pub name: Name,
|
||||
}
|
||||
|
||||
impl NameRef {
|
||||
pub fn unqualified(name: Name) -> Self {
|
||||
NameRef { table: None, name }
|
||||
}
|
||||
|
||||
pub fn qualified(table: Name, name: Name) -> Self {
|
||||
NameRef { table: Some(table), name }
|
||||
}
|
||||
}
|
||||
|
||||
/// A function call. The name keeps the spelling used in the source (`Sum`, `SUM`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Call {
|
||||
pub name: Name,
|
||||
pub args: Vec<Expr>,
|
||||
}
|
||||
|
||||
/// Prefix operators. `Not` is the keyword operator, not a function call.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum UnaryOp {
|
||||
Plus,
|
||||
Neg,
|
||||
Not,
|
||||
}
|
||||
|
||||
impl UnaryOp {
|
||||
/// Binding power, higher binds tighter (DAX precedence levels 3 and 8).
|
||||
pub const fn precedence(self) -> u8 {
|
||||
match self {
|
||||
UnaryOp::Plus | UnaryOp::Neg => 80,
|
||||
UnaryOp::Not => 30,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn symbol(self) -> &'static str {
|
||||
match self {
|
||||
UnaryOp::Plus => "+",
|
||||
UnaryOp::Neg => "-",
|
||||
UnaryOp::Not => "NOT",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Binary operators, in the precedence order of <https://dax.guide/operators/>.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum BinaryOp {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Pow,
|
||||
Concat,
|
||||
Eq,
|
||||
StrictEq,
|
||||
Ne,
|
||||
Lt,
|
||||
Gt,
|
||||
Le,
|
||||
Ge,
|
||||
And,
|
||||
Or,
|
||||
In,
|
||||
}
|
||||
|
||||
impl BinaryOp {
|
||||
pub const fn symbol(self) -> &'static str {
|
||||
match self {
|
||||
BinaryOp::Add => "+",
|
||||
BinaryOp::Sub => "-",
|
||||
BinaryOp::Mul => "*",
|
||||
BinaryOp::Div => "/",
|
||||
BinaryOp::Pow => "^",
|
||||
BinaryOp::Concat => "&",
|
||||
BinaryOp::Eq => "=",
|
||||
BinaryOp::StrictEq => "==",
|
||||
BinaryOp::Ne => "<>",
|
||||
BinaryOp::Lt => "<",
|
||||
BinaryOp::Gt => ">",
|
||||
BinaryOp::Le => "<=",
|
||||
BinaryOp::Ge => ">=",
|
||||
BinaryOp::And => "&&",
|
||||
BinaryOp::Or => "||",
|
||||
BinaryOp::In => "IN",
|
||||
}
|
||||
}
|
||||
|
||||
/// Binding power, higher binds tighter. The values encode the ten precedence levels
|
||||
/// from the operator table: parentheses/calls, `^`, unary sign, `* /`, `+ -`, `&`,
|
||||
/// comparisons (including `IN`), `NOT`, `&&`, `||`.
|
||||
pub const fn precedence(self) -> u8 {
|
||||
match self {
|
||||
BinaryOp::Pow => 90,
|
||||
BinaryOp::Mul | BinaryOp::Div => 70,
|
||||
BinaryOp::Add | BinaryOp::Sub => 60,
|
||||
BinaryOp::Concat => 50,
|
||||
// `IN` is a comparison, at the same tier as `=`/`<` (Microsoft's operator table).
|
||||
BinaryOp::In | BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => 40,
|
||||
BinaryOp::And => 20,
|
||||
BinaryOp::Or => 10,
|
||||
}
|
||||
}
|
||||
|
||||
/// DAX binary operators all associate to the left. Microsoft's operator reference puts `^` in
|
||||
/// its own precedence tier and states that operators of equal precedence are ordered from left
|
||||
/// to right, so `2^3^2` is `(2^3)^2` = 64 — the same value Excel and Power Pivot produce.
|
||||
pub const fn is_left_associative(self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub const fn is_right_associative(self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub const fn is_comparison(self) -> bool {
|
||||
matches!(self, BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge)
|
||||
}
|
||||
|
||||
pub const fn is_logical(self) -> bool {
|
||||
matches!(self, BinaryOp::And | BinaryOp::Or)
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of an expression, without its span.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ExprKind {
|
||||
Literal(Literal),
|
||||
/// A bare, quoted or table-qualified name.
|
||||
Name(NameRef),
|
||||
/// `SUM(1, 2)`.
|
||||
Call(Call),
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
expr: Box<Expr>,
|
||||
},
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>,
|
||||
},
|
||||
/// A table constructor `{ 1, 2 }`. Rows are [`ExprKind::Tuple`] values.
|
||||
Table(Vec<Expr>),
|
||||
/// A row constructor / parenthesised comma list `(1, "a")`.
|
||||
Tuple(Vec<Expr>),
|
||||
/// An expression-level `VAR <name> = <expr> ... RETURN <expr>` block.
|
||||
VarReturn {
|
||||
vars: Vec<VarDecl>,
|
||||
body: Box<Expr>,
|
||||
},
|
||||
}
|
||||
|
||||
/// One `VAR <name> = <expression>` declaration inside an [`ExprKind::VarReturn`].
|
||||
///
|
||||
/// The name is a plain identifier: DAX variable names cannot be quoted or bracketed. Declarations
|
||||
/// are sequential, so `nameN` is visible only to `expressionN+1` and to the `RETURN` body.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VarDecl {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// A DAX expression with its source span.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Expr {
|
||||
pub kind: ExprKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
pub fn new(kind: ExprKind, span: Span) -> Self {
|
||||
Expr { kind, span }
|
||||
}
|
||||
|
||||
pub fn literal(value: Literal, span: Span) -> Self {
|
||||
Expr::new(ExprKind::Literal(value), span)
|
||||
}
|
||||
|
||||
/// The tree depth (a leaf is 1), computed iteratively so it is safe on any shape the
|
||||
/// parser accepts. The parser uses this to bound the AST that recursive `Debug`,
|
||||
/// `PartialEq` and drop glue would otherwise walk.
|
||||
pub fn depth(&self) -> usize {
|
||||
let mut max = 0;
|
||||
let mut stack = vec![(self, 1usize)];
|
||||
while let Some((node, depth)) = stack.pop() {
|
||||
max = max.max(depth);
|
||||
match &node.kind {
|
||||
ExprKind::Call(call) => stack.extend(call.args.iter().map(|e| (e, depth + 1))),
|
||||
ExprKind::Unary { expr, .. } => stack.push((expr, depth + 1)),
|
||||
ExprKind::Binary { left, right, .. } => {
|
||||
stack.push((right, depth + 1));
|
||||
stack.push((left, depth + 1));
|
||||
}
|
||||
ExprKind::Table(items) | ExprKind::Tuple(items) => {
|
||||
stack.extend(items.iter().map(|e| (e, depth + 1)));
|
||||
}
|
||||
ExprKind::VarReturn { vars, body } => {
|
||||
stack.push((body, depth + 1));
|
||||
stack.extend(vars.iter().map(|var| (&var.expr, depth + 1)));
|
||||
}
|
||||
ExprKind::Literal(_) | ExprKind::Name(_) => {}
|
||||
}
|
||||
}
|
||||
max
|
||||
}
|
||||
|
||||
/// Visits every node depth-first, parents before children. Iterative, so deeply nested
|
||||
/// (but within the parser limits) trees cannot overflow the stack.
|
||||
pub fn walk<'a>(&'a self, f: &mut dyn FnMut(&'a Expr)) {
|
||||
let mut stack = vec![self];
|
||||
while let Some(node) = stack.pop() {
|
||||
f(node);
|
||||
match &node.kind {
|
||||
ExprKind::Call(call) => stack.extend(call.args.iter().rev()),
|
||||
ExprKind::Unary { expr, .. } => stack.push(expr),
|
||||
ExprKind::Binary { left, right, .. } => {
|
||||
stack.push(right);
|
||||
stack.push(left);
|
||||
}
|
||||
ExprKind::Table(items) | ExprKind::Tuple(items) => stack.extend(items.iter().rev()),
|
||||
ExprKind::VarReturn { vars, body } => {
|
||||
stack.push(body);
|
||||
stack.extend(vars.iter().rev().map(|var| &var.expr));
|
||||
}
|
||||
ExprKind::Literal(_) | ExprKind::Name(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spans do not participate in equality: reparsing printed text produces the same AST.
|
||||
impl PartialEq for Expr {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.kind == other.kind
|
||||
}
|
||||
}
|
||||
|
||||
/// A complete DAX query: an optional `DEFINE` block followed by one or more `EVALUATE`
|
||||
/// statements.
|
||||
///
|
||||
/// A query always has at least one [`Evaluate`]; the parser rejects `DEFINE` without a following
|
||||
/// `EVALUATE`. For the simple form `EVALUATE <expression>` the `define` field is `None` and
|
||||
/// `evaluates` holds exactly one entry with no clauses.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Query {
|
||||
pub define: Option<Define>,
|
||||
pub evaluates: Vec<Evaluate>,
|
||||
}
|
||||
|
||||
/// The `DEFINE` block of a query. One block applies to every `EVALUATE` statement.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Define {
|
||||
pub items: Vec<Definition>,
|
||||
}
|
||||
|
||||
/// One entry of a `DEFINE` block.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Definition {
|
||||
Measure(MeasureDef),
|
||||
Column(ColumnDef),
|
||||
Table(TableDef),
|
||||
Var(VarDef),
|
||||
Function(FunctionDef),
|
||||
MParameter(MParameterDef),
|
||||
}
|
||||
|
||||
/// `MEASURE <table>[<measure>] = <scalar expression>`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MeasureDef {
|
||||
pub name: NameRef,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// `COLUMN <table>[<column>] = <scalar expression>`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ColumnDef {
|
||||
pub name: NameRef,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// `VAR <name> = <expression>` in a `DEFINE` block. Unlike an expression-level
|
||||
/// [`ExprKind::VarReturn`], a query-scoped variable has no `RETURN`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VarDef {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// `TABLE <name> = <table expression> [WITH VISUAL SHAPE ...]`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TableDef {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
pub visual_shape: Option<VisualShape>,
|
||||
}
|
||||
|
||||
/// `MPARAMETER <name> = <expression>`: a Power BI dynamic M parameter binding.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MParameterDef {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// A query-defined function: `FUNCTION <name> = (<param>, ...) => <body>`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FunctionDef {
|
||||
pub name: Name,
|
||||
pub params: Vec<FunctionParam>,
|
||||
pub body: Expr,
|
||||
}
|
||||
|
||||
/// One parameter of a [`FunctionDef`].
|
||||
///
|
||||
/// Every annotation is optional: `p`, `p : INT64`, `p : SCALAR INT64 VAL` and `p = 1` are all
|
||||
/// valid parameter declarations.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FunctionParam {
|
||||
pub name: Name,
|
||||
pub ty: Option<ParameterType>,
|
||||
pub subtype: Option<ParameterSubtype>,
|
||||
pub passing: Option<PassingMode>,
|
||||
pub default: Option<Expr>,
|
||||
}
|
||||
|
||||
/// The DAX user-defined-function parameter types.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ParameterType {
|
||||
AnyVal,
|
||||
Scalar,
|
||||
Table,
|
||||
AnyRef,
|
||||
CalendarRef,
|
||||
ColumnRef,
|
||||
MeasureRef,
|
||||
TableRef,
|
||||
}
|
||||
|
||||
impl ParameterType {
|
||||
/// The canonical uppercase keyword.
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
ParameterType::AnyVal => "ANYVAL",
|
||||
ParameterType::Scalar => "SCALAR",
|
||||
ParameterType::Table => "TABLE",
|
||||
ParameterType::AnyRef => "ANYREF",
|
||||
ParameterType::CalendarRef => "CALENDARREF",
|
||||
ParameterType::ColumnRef => "COLUMNREF",
|
||||
ParameterType::MeasureRef => "MEASUREREF",
|
||||
ParameterType::TableRef => "TABLEREF",
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognises a type keyword case-insensitively.
|
||||
pub fn from_keyword(word: &str) -> Option<Self> {
|
||||
Some(match word.to_ascii_uppercase().as_str() {
|
||||
"ANYVAL" => ParameterType::AnyVal,
|
||||
"SCALAR" => ParameterType::Scalar,
|
||||
"TABLE" => ParameterType::Table,
|
||||
"ANYREF" => ParameterType::AnyRef,
|
||||
"CALENDARREF" => ParameterType::CalendarRef,
|
||||
"COLUMNREF" => ParameterType::ColumnRef,
|
||||
"MEASUREREF" => ParameterType::MeasureRef,
|
||||
"TABLEREF" => ParameterType::TableRef,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The scalar subtypes, which are only valid together with [`ParameterType::Scalar`] (or alone,
|
||||
/// as in the documented `p : INT64` shorthand).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ParameterSubtype {
|
||||
Boolean,
|
||||
DateTime,
|
||||
Decimal,
|
||||
Double,
|
||||
Int64,
|
||||
Numeric,
|
||||
String,
|
||||
Variant,
|
||||
}
|
||||
|
||||
impl ParameterSubtype {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
ParameterSubtype::Boolean => "BOOLEAN",
|
||||
ParameterSubtype::DateTime => "DATETIME",
|
||||
ParameterSubtype::Decimal => "DECIMAL",
|
||||
ParameterSubtype::Double => "DOUBLE",
|
||||
ParameterSubtype::Int64 => "INT64",
|
||||
ParameterSubtype::Numeric => "NUMERIC",
|
||||
ParameterSubtype::String => "STRING",
|
||||
ParameterSubtype::Variant => "VARIANT",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_keyword(word: &str) -> Option<Self> {
|
||||
Some(match word.to_ascii_uppercase().as_str() {
|
||||
"BOOLEAN" => ParameterSubtype::Boolean,
|
||||
"DATETIME" => ParameterSubtype::DateTime,
|
||||
"DECIMAL" => ParameterSubtype::Decimal,
|
||||
"DOUBLE" => ParameterSubtype::Double,
|
||||
"INT64" => ParameterSubtype::Int64,
|
||||
"NUMERIC" => ParameterSubtype::Numeric,
|
||||
"STRING" => ParameterSubtype::String,
|
||||
"VARIANT" => ParameterSubtype::Variant,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How a function argument is passed: `VAL` (eagerly) or `EXPR` (lazily).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PassingMode {
|
||||
Val,
|
||||
Expr,
|
||||
}
|
||||
|
||||
impl PassingMode {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
PassingMode::Val => "VAL",
|
||||
PassingMode::Expr => "EXPR",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_keyword(word: &str) -> Option<Self> {
|
||||
match word.to_ascii_uppercase().as_str() {
|
||||
"VAL" => Some(PassingMode::Val),
|
||||
"EXPR" => Some(PassingMode::Expr),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `EVALUATE <table expression> [ORDER BY ...] [START AT ...]` statement.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Evaluate {
|
||||
pub table: Expr,
|
||||
pub order_by: Vec<OrderItem>,
|
||||
pub start_at: Vec<StartValue>,
|
||||
}
|
||||
|
||||
/// One item of a query-level `ORDER BY` clause.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OrderItem {
|
||||
pub expr: Expr,
|
||||
pub direction: SortDirection,
|
||||
}
|
||||
|
||||
/// The sort direction of an `ORDER BY` item. An omitted direction parses as
|
||||
/// [`SortDirection::Asc`], and the printer writes the keyword explicitly.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum SortDirection {
|
||||
Asc,
|
||||
Desc,
|
||||
}
|
||||
|
||||
impl SortDirection {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
SortDirection::Asc => "ASC",
|
||||
SortDirection::Desc => "DESC",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_ascending(self) -> bool {
|
||||
matches!(self, SortDirection::Asc)
|
||||
}
|
||||
}
|
||||
|
||||
/// One value of a `START AT` clause: a constant or an XMLA `@parameter` reference.
|
||||
///
|
||||
/// Start values are constants, not expressions. A sign in front of a numeric literal is folded
|
||||
/// into the literal (`START AT -1`); everything else must be a literal or `@name`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum StartValue {
|
||||
Literal(Literal),
|
||||
Parameter(Name),
|
||||
}
|
||||
|
||||
/// The `WITH VISUAL SHAPE` clause of a query-defined table.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VisualShape {
|
||||
pub axes: Vec<Axis>,
|
||||
/// The optional `DENSIFY "<column>"` clause, always last.
|
||||
pub densify: Option<String>,
|
||||
}
|
||||
|
||||
/// One `AXIS ROWS` / `AXIS COLUMNS` clause of a visual shape.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Axis {
|
||||
pub kind: AxisKind,
|
||||
pub groups: Vec<AxisGroup>,
|
||||
pub order_by: Vec<AxisOrderItem>,
|
||||
}
|
||||
|
||||
/// The axis of a visual shape. Only these two are documented.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum AxisKind {
|
||||
Rows,
|
||||
Columns,
|
||||
}
|
||||
|
||||
impl AxisKind {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
AxisKind::Rows => "ROWS",
|
||||
AxisKind::Columns => "COLUMNS",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `GROUP <column>, ... TOTAL <column>` level of an axis.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AxisGroup {
|
||||
pub columns: Vec<NameRef>,
|
||||
pub total: NameRef,
|
||||
}
|
||||
|
||||
/// One column of an axis `ORDER BY` clause.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AxisOrderItem {
|
||||
pub column: NameRef,
|
||||
pub direction: SortDirection,
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
//! Name binding for DAX expressions and measures.
|
||||
//!
|
||||
//! The binder resolves table names, `Table[Column]` references, measures and expression-level
|
||||
//! `VAR` names against a [`DataModel`]. It validates catalogued function calls with the same
|
||||
//! arity/kind rules as [`crate::validate`], and builds the measure dependency graph.
|
||||
//!
|
||||
//! It is deliberately static: row context and filter context are evaluator concerns. A bracketed
|
||||
//! column that is not qualified by a table is left as [`BoundExpr::UnqualifiedColumn`] so the
|
||||
//! evaluator can resolve it from the current row context.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::ast::{BinaryOp, Literal, NameRef, UnaryOp};
|
||||
use crate::model::DataModel;
|
||||
use crate::{Call, Expr, ExprKind, FunctionSpec, ParamKind, lookup, parse_expression, validate_call};
|
||||
|
||||
/// A name-resolution error with the source span.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message} at bytes {}..{}", span.start, span.end)]
|
||||
pub struct BindError {
|
||||
pub message: String,
|
||||
pub span: crate::Span,
|
||||
}
|
||||
|
||||
impl BindError {
|
||||
fn new(message: impl Into<String>, span: crate::Span) -> Self {
|
||||
BindError { message: message.into(), span }
|
||||
}
|
||||
}
|
||||
|
||||
/// The bound form of an expression.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum BoundExpr {
|
||||
Literal(Literal),
|
||||
/// A resolved `Table[Column]` reference.
|
||||
Column {
|
||||
table: usize,
|
||||
column: usize,
|
||||
},
|
||||
/// `[Column]` without a table qualifier: resolved from the evaluator's row context.
|
||||
UnqualifiedColumn {
|
||||
name: String,
|
||||
},
|
||||
/// A model measure reference.
|
||||
Measure(usize),
|
||||
/// A table reference.
|
||||
Table(usize),
|
||||
/// A catalogued function call with bound arguments.
|
||||
Call {
|
||||
spec: &'static FunctionSpec,
|
||||
args: Vec<BoundExpr>,
|
||||
},
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
expr: Box<BoundExpr>,
|
||||
},
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<BoundExpr>,
|
||||
right: Box<BoundExpr>,
|
||||
},
|
||||
/// `{ value, ... }`.
|
||||
TableConstructor(Vec<BoundExpr>),
|
||||
/// `( value, ... )`.
|
||||
Tuple(Vec<BoundExpr>),
|
||||
/// A variable reference.
|
||||
///
|
||||
/// `index` is the variable's absolute slot in the cumulative stack of every enclosing
|
||||
/// [`BoundExpr::VarReturn`] block — outer blocks first, each block appending its own
|
||||
/// declarations in order — not its position inside the innermost `vars` list. The evaluator
|
||||
/// pushes each block's values onto the same stack, so the index stays valid across nesting.
|
||||
Variable {
|
||||
index: usize,
|
||||
name: String,
|
||||
},
|
||||
/// A function-specific keyword argument (`DAY` in `DATEDIFF`, a type name in `DATATABLE`).
|
||||
Keyword(String),
|
||||
/// `VAR name = expr ... RETURN body`.
|
||||
VarReturn {
|
||||
vars: Vec<BoundVariable>,
|
||||
body: Box<BoundExpr>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BoundVariable {
|
||||
pub name: String,
|
||||
pub expr: BoundExpr,
|
||||
}
|
||||
|
||||
/// A bound measure with its direct measure dependencies.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BoundMeasure {
|
||||
pub name: String,
|
||||
pub expr: BoundExpr,
|
||||
pub dependencies: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// Binds expressions against one model.
|
||||
pub struct Binder<'a> {
|
||||
model: &'a DataModel,
|
||||
}
|
||||
|
||||
impl<'a> Binder<'a> {
|
||||
pub fn new(model: &'a DataModel) -> Self {
|
||||
Binder { model }
|
||||
}
|
||||
|
||||
pub fn model(&self) -> &'a DataModel {
|
||||
self.model
|
||||
}
|
||||
|
||||
/// Binds an expression with no variables in scope.
|
||||
pub fn bind_expression(&self, expr: &Expr) -> Result<BoundExpr, BindError> {
|
||||
self.bind_with_vars(expr, &mut Vec::new())
|
||||
}
|
||||
|
||||
/// Parses and binds a measure formula. The model's measures must have been prepared with
|
||||
/// [`DataModel::parse_formulas`].
|
||||
pub fn bind_measure(&self, name: &str) -> Result<BoundMeasure, BindError> {
|
||||
let index = self.model.measure_index(name).ok_or_else(|| BindError::new(format!("unknown measure `{name}`"), crate::Span::empty()))?;
|
||||
let measure = &self.model.measures[index];
|
||||
if measure.expr.is_none() {
|
||||
return Err(BindError::new(
|
||||
format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name),
|
||||
crate::Span::empty(),
|
||||
));
|
||||
}
|
||||
let Some(formula) = measure.expr.as_ref() else {
|
||||
return Err(BindError::new(
|
||||
format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name),
|
||||
crate::Span::empty(),
|
||||
));
|
||||
};
|
||||
let expr = self.bind_expression(formula)?;
|
||||
let mut dependencies = BTreeSet::new();
|
||||
collect_measure_names(self.model, &expr, &mut dependencies);
|
||||
Ok(BoundMeasure { name: measure.name.clone(), expr, dependencies })
|
||||
}
|
||||
|
||||
/// Builds the direct measure dependency graph and rejects cycles.
|
||||
pub fn dependency_graph(&self) -> Result<BTreeMap<String, BTreeSet<String>>, BindError> {
|
||||
let mut graph = BTreeMap::new();
|
||||
for measure in &self.model.measures {
|
||||
let bound = self.bind_measure(&measure.name)?;
|
||||
graph.insert(bound.name, bound.dependencies);
|
||||
}
|
||||
let mut state: BTreeMap<String, u8> = BTreeMap::new();
|
||||
for name in graph.keys() {
|
||||
self.visit(name, &graph, &mut state)?;
|
||||
}
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
fn visit(&self, name: &str, graph: &BTreeMap<String, BTreeSet<String>>, state: &mut BTreeMap<String, u8>) -> Result<(), BindError> {
|
||||
// Iterative: a measure chain comes from the model JSON, so its length must not grow the
|
||||
// call stack (a long chain would otherwise abort the process instead of returning an error).
|
||||
if state.get(name).copied() == Some(2) {
|
||||
return Ok(());
|
||||
}
|
||||
let empty = BTreeSet::new();
|
||||
state.insert(name.to_string(), 1);
|
||||
let mut stack: Vec<(&str, std::collections::btree_set::Iter<'_, String>)> = vec![(name, graph.get(name).unwrap_or(&empty).iter())];
|
||||
while let Some((current, dependencies)) = stack.last_mut() {
|
||||
match dependencies.next() {
|
||||
Some(dependency) => match state.get(dependency.as_str()).copied() {
|
||||
Some(2) => {}
|
||||
Some(1) => {
|
||||
return Err(BindError::new(format!("circular measure dependency involving `{dependency}`"), crate::Span::empty()));
|
||||
}
|
||||
_ => {
|
||||
state.insert(dependency.clone(), 1);
|
||||
stack.push((dependency.as_str(), graph.get(dependency).unwrap_or(&empty).iter()));
|
||||
}
|
||||
},
|
||||
None => {
|
||||
state.insert((*current).to_string(), 2);
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bind_with_vars(&self, expr: &Expr, vars: &mut Vec<String>) -> Result<BoundExpr, BindError> {
|
||||
match &expr.kind {
|
||||
ExprKind::Literal(literal) => Ok(BoundExpr::Literal(literal.clone())),
|
||||
ExprKind::Name(name) => self.bind_name(name, expr.span, vars),
|
||||
ExprKind::Call(call) => self.bind_call(call, expr.span, vars),
|
||||
ExprKind::Unary { op, expr: inner } => Ok(BoundExpr::Unary { op: *op, expr: Box::new(self.bind_with_vars(inner, vars)?) }),
|
||||
ExprKind::Binary { op, left, right } => Ok(BoundExpr::Binary {
|
||||
op: *op,
|
||||
left: Box::new(self.bind_with_vars(left, vars)?),
|
||||
right: Box::new(self.bind_with_vars(right, vars)?),
|
||||
}),
|
||||
ExprKind::Table(items) => {
|
||||
Ok(BoundExpr::TableConstructor(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::<Result<_, _>>()?))
|
||||
}
|
||||
ExprKind::Tuple(items) => Ok(BoundExpr::Tuple(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::<Result<_, _>>()?)),
|
||||
ExprKind::VarReturn { vars: declarations, body } => {
|
||||
let mut bound = Vec::with_capacity(declarations.len());
|
||||
let mut names = vars.clone();
|
||||
for declaration in declarations {
|
||||
let value = self.bind_with_vars(&declaration.expr, &mut names)?;
|
||||
names.push(declaration.name.text.clone());
|
||||
bound.push(BoundVariable { name: declaration.name.text.clone(), expr: value });
|
||||
}
|
||||
let body = self.bind_with_vars(body, &mut names)?;
|
||||
Ok(BoundExpr::VarReturn { vars: bound, body: Box::new(body) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_name(&self, name: &NameRef, span: crate::Span, vars: &[String]) -> Result<BoundExpr, BindError> {
|
||||
if let Some(table) = &name.table {
|
||||
let table_index = self.model.table_index(&table.text).ok_or_else(|| BindError::new(format!("unknown table `{}`", table.text), span))?;
|
||||
if let Some(column_index) = self.model.column_index(table_index, &name.name.text) {
|
||||
return Ok(BoundExpr::Column { table: table_index, column: column_index });
|
||||
}
|
||||
// `Sales[Total Sales]` names a measure homed on the qualifying table; DAX allows the
|
||||
// table qualifier on a measure reference and only rejects it for another table.
|
||||
if let Some(index) = self.model.measure_index(&name.name.text)
|
||||
&& let Some(home) = self.model.measures[index].table.as_deref()
|
||||
{
|
||||
if self.model.table_index(home) == Some(table_index) {
|
||||
return Ok(BoundExpr::Measure(index));
|
||||
}
|
||||
return Err(BindError::new(format!("measure `{}` belongs to table `{}`, not `{}`", name.name.text, home, table.text), span));
|
||||
}
|
||||
return Err(BindError::new(format!("unknown column `{}` in table `{}`", name.name.text, table.text), span));
|
||||
}
|
||||
|
||||
// A bracketed name is always a model object reference (`[Measure]`, `[Column]`), never a
|
||||
// variable: DAX requires bare identifiers for variables, so `VAR Total = 1 ... [Total]`
|
||||
// refers to the measure, not the variable.
|
||||
if name.name.style == crate::NameStyle::Bracketed {
|
||||
if let Some(index) = self.model.measure_index(&name.name.text) {
|
||||
return Ok(BoundExpr::Measure(index));
|
||||
}
|
||||
// A bracketed name may be a row-context column; the evaluator resolves it.
|
||||
return Ok(BoundExpr::UnqualifiedColumn { name: name.name.text.clone() });
|
||||
}
|
||||
|
||||
if let Some(index) = vars.iter().rposition(|var| var.eq_ignore_ascii_case(&name.name.text)) {
|
||||
return Ok(BoundExpr::Variable { index, name: name.name.text.clone() });
|
||||
}
|
||||
|
||||
if let Some(index) = self.model.table_index(&name.name.text) {
|
||||
return Ok(BoundExpr::Table(index));
|
||||
}
|
||||
if let Some(index) = self.model.measure_index(&name.name.text) {
|
||||
return Ok(BoundExpr::Measure(index));
|
||||
}
|
||||
Err(BindError::new(format!("unknown name `{}`", name.name.text), span))
|
||||
}
|
||||
|
||||
fn bind_call(&self, call: &Call, span: crate::Span, vars: &mut Vec<String>) -> Result<BoundExpr, BindError> {
|
||||
let Some(spec) = lookup(&call.name.text) else {
|
||||
return Err(BindError::new(format!("unknown DAX function `{}`", call.name.text), span));
|
||||
};
|
||||
if let Some(error) = validate_call(call).into_iter().next() {
|
||||
return Err(BindError::new(error.message, span));
|
||||
}
|
||||
let mut args = Vec::with_capacity(call.args.len());
|
||||
for (index, arg) in call.args.iter().enumerate() {
|
||||
// Documented enum parameters (intervals, ties, blanks, text type names) are written
|
||||
// as bare names. The parser cannot tell them from table/measure names, but the
|
||||
// catalog's parameter kind can: a Text position only accepts a literal or a keyword.
|
||||
let expected = spec.overload_for(call.args.len()).and_then(|overload| overload.params.get(index)).copied();
|
||||
let keyword = match spec.name {
|
||||
"DATATABLE" if index % 2 == 1 => keyword_name(arg),
|
||||
"CONVERT" if index == 1 => keyword_name(arg),
|
||||
// RANKX's Ties argument is documented as `Dense` but catalogued as a Scalar.
|
||||
"RANKX" if index == 4 => keyword_name(arg),
|
||||
// RANKX's Order argument is catalogued as a Scalar too, but it is `ASC`/`DESC`.
|
||||
"RANKX" if index == 3 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"DATEDIFF" if index == 2 => keyword_name(arg),
|
||||
// TOPN's `(expression, Order)` pairs: ASC/DESC sit at every odd index from 3.
|
||||
"TOPN" if index >= 3 && index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"CROSSFILTER" if index == 2 => {
|
||||
clause_keyword(arg, &["NONE", "ONE", "ONEWAY", "BOTH", "TWOWAY", "ONEWAY_LEFTFILTERSRIGHT", "ONEWAY_RIGHTFILTERSLEFT"])
|
||||
}
|
||||
// RANK/ROWNUMBER's Reset argument is `NONE`, `LOWESTPARENT` or `HIGHESTPARENT`,
|
||||
// catalogued as `Any` so that a relation expression still binds there.
|
||||
"RANK" if index == 6 => clause_keyword(arg, &["NONE", "LOWESTPARENT", "HIGHESTPARENT"]),
|
||||
// The documented bare ASC/DESC slots: RANKX and RANK.EQ take Order at index 3/2,
|
||||
// TOPNSKIP/CONCATENATEX at index 4 and SAMPLE at index 3.
|
||||
"RANK.EQ" if index == 2 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
// SAMPLE and TOPNSKIP repeat `(orderBy, Order)` pairs, so every order word sits at
|
||||
// an even offset from the first one: 3, 5, 7, ... for SAMPLE and 4, 6, 8, ... for
|
||||
// TOPNSKIP.
|
||||
"TOPNSKIP" if index >= 4 && (index - 4) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"SAMPLE" if index >= 3 && (index - 3) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
// CONCATENATEX takes `(orderBy, Order)` pairs from index 4 on, so every even
|
||||
// offset from 4 is an order word.
|
||||
"CONCATENATEX" if index >= 4 && (index - 4) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"ROWNUMBER" if index == 5 => clause_keyword(arg, &["NONE", "LOWESTPARENT", "HIGHESTPARENT"]),
|
||||
// Window/relation clauses take bare enum words: `ORDERBY(x, DESC)`,
|
||||
// `WINDOW(1, ABS, 1, ABS, ...)`, `INDEX(..., KEEP, PARTITIONBY(...))`, and the
|
||||
// LOOKUP associated-columns behaviour (`INFERRED`).
|
||||
"ORDERBY" if index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"INDEX" | "OFFSET" if index >= 2 => clause_keyword(arg, WINDOW_KEYWORDS),
|
||||
// FromType/ToType are optional, so the blanks/reset slots move with the layout;
|
||||
// `window_table` identifies each slot by its value.
|
||||
"WINDOW" if index >= 1 => clause_keyword(arg, WINDOW_KEYWORDS),
|
||||
"LOOKUP" | "LOOKUPWITHTOTALS" if index % 2 == 1 && index + 1 == call.args.len() => {
|
||||
clause_keyword(arg, &["EXPLICIT", "INFERRED", "DEFAULT"])
|
||||
}
|
||||
// PATHITEM's optional Type is documented as `TEXT`/`INTEGER` but catalogued as
|
||||
// `Any` so that the numeric `0`/`1` spellings still bind.
|
||||
"PATHITEM" | "PATHITEMREVERSE" if index == 2 => clause_keyword(arg, &["TEXT", "INTEGER"]),
|
||||
_ if matches!(expected, Some(ParamKind::Text)) => keyword_name(arg),
|
||||
_ => visual_keyword_name(spec.name, index, arg),
|
||||
}
|
||||
// A name only wins where the position genuinely accepts one — a documented `Text`
|
||||
// argument such as `RANKX(..., Dense)` or a visual calculation's axis. A fixed enum
|
||||
// slot (`DATEDIFF`'s interval, `CONVERT`'s type, the order words) is not a name
|
||||
// position: a table called `Month` must not turn `DATEDIFF(a, b, MONTH)` into a table
|
||||
// reference, and a variable called `YEAR` must not either.
|
||||
.filter(|keyword| {
|
||||
// `DATATABLE`'s type words are types even though the catalog marks them `Text`,
|
||||
// so a table named `INTEGER` must not capture them either.
|
||||
let fixed_slot =
|
||||
spec.name == "DATATABLE" || (!matches!(expected, Some(ParamKind::Text)) && !is_visual_keyword(spec.name, index, keyword));
|
||||
if fixed_slot {
|
||||
return true;
|
||||
}
|
||||
let named = self.model.table_index(keyword).is_some() || self.model.measure_index(keyword).is_some();
|
||||
let variable = vars.iter().any(|var| var.eq_ignore_ascii_case(keyword));
|
||||
!named && !variable
|
||||
});
|
||||
if let Some(keyword) = keyword {
|
||||
args.push(BoundExpr::Keyword(keyword));
|
||||
} else {
|
||||
args.push(self.bind_with_vars(arg, vars)?);
|
||||
}
|
||||
}
|
||||
Ok(BoundExpr::Call { spec, args })
|
||||
}
|
||||
}
|
||||
|
||||
fn keyword_name(expr: &Expr) -> Option<String> {
|
||||
match &expr.kind {
|
||||
ExprKind::Name(name) if name.table.is_none() && name.name.style == crate::NameStyle::Bare => Some(name.name.text.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bare identifiers that visual-calculation functions accept where their syntax documents an
|
||||
/// axis, an ORDERBY flag, a blank-ordering enumeration or a reset clause. These words are not
|
||||
/// names in the model, so they must become [`BoundExpr::Keyword`] instead of failing resolution.
|
||||
fn visual_keyword_name(function: &str, index: usize, arg: &Expr) -> Option<String> {
|
||||
let word = keyword_name(arg)?;
|
||||
is_visual_keyword(function, index, &word).then_some(word)
|
||||
}
|
||||
|
||||
/// Whether `word` is a documented keyword at the 0-based `index` of a visual-calculation call.
|
||||
///
|
||||
/// The positions mirror the Microsoft syntax for each function, e.g. `FIRST ( <column>[, <axis>]
|
||||
/// [, <orderBy>][, <blanks>][, reset] )` and `RANGE ( <step>[, <includeCurrent>][, <axis>]
|
||||
/// [, <orderBy>][, <blanks>][, <reset>] )`. `COLLAPSE`/`EXPAND` also have navigation-only forms
|
||||
/// whose first argument is the axis (`COLLAPSE ( <axis>[, N] )`).
|
||||
fn is_visual_keyword(function: &str, index: usize, word: &str) -> bool {
|
||||
let axis = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "ROWS" | "COLUMNS");
|
||||
let order_by = |positions: &[usize]| positions.contains(&index) && word.eq_ignore_ascii_case("KEEP");
|
||||
let blanks = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "DEFAULT" | "FIRST" | "LAST");
|
||||
let reset =
|
||||
|positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "NONE" | "LOWESTPARENT" | "HIGHESTPARENT");
|
||||
match function {
|
||||
"COLLAPSE" | "EXPAND" | "COLLAPSEALL" | "EXPANDALL" => axis(&[0, 1]),
|
||||
"FIRST" | "LAST" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]),
|
||||
"PREVIOUS" | "NEXT" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]),
|
||||
"MOVINGAVERAGE" => axis(&[3]) || order_by(&[4]) || blanks(&[5]) || reset(&[6]),
|
||||
"RUNNINGSUM" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]),
|
||||
"RANGE" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The enum words accepted by the window/relation clauses. Matching is case-insensitive, and an
|
||||
/// identifier outside this set is left to normal name binding so typos still report an error.
|
||||
const WINDOW_KEYWORDS: &[&str] = &["ASC", "DESC", "ABS", "REL", "DEFAULT", "FIRST", "LAST", "KEEP", "NONE", "LOWESTPARENT", "HIGHESTPARENT"];
|
||||
|
||||
fn clause_keyword(expr: &Expr, allowed: &[&str]) -> Option<String> {
|
||||
let word = keyword_name(expr)?;
|
||||
allowed.iter().any(|candidate| word.eq_ignore_ascii_case(candidate)).then_some(word)
|
||||
}
|
||||
|
||||
fn collect_measure_names(model: &DataModel, expr: &BoundExpr, out: &mut BTreeSet<String>) {
|
||||
match expr {
|
||||
BoundExpr::Measure(index) => {
|
||||
if let Some(measure) = model.measures.get(*index) {
|
||||
out.insert(measure.name.clone());
|
||||
}
|
||||
}
|
||||
BoundExpr::Call { args, .. } | BoundExpr::TableConstructor(args) | BoundExpr::Tuple(args) => {
|
||||
for arg in args {
|
||||
collect_measure_names(model, arg, out);
|
||||
}
|
||||
}
|
||||
BoundExpr::Unary { expr, .. } => collect_measure_names(model, expr, out),
|
||||
BoundExpr::Binary { left, right, .. } => {
|
||||
collect_measure_names(model, left, out);
|
||||
collect_measure_names(model, right, out);
|
||||
}
|
||||
BoundExpr::VarReturn { vars, body } => {
|
||||
for var in vars {
|
||||
collect_measure_names(model, &var.expr, out);
|
||||
}
|
||||
collect_measure_names(model, body, out);
|
||||
}
|
||||
BoundExpr::Literal(_)
|
||||
| BoundExpr::Column { .. }
|
||||
| BoundExpr::UnqualifiedColumn { .. }
|
||||
| BoundExpr::Table(_)
|
||||
| BoundExpr::Variable { .. }
|
||||
| BoundExpr::Keyword(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses and binds one measure formula against a model, without requiring a full model parse.
|
||||
pub fn bind_formula(model: &DataModel, formula: &str) -> Result<BoundExpr, BindError> {
|
||||
let expr = parse_expression(formula).map_err(|error| BindError::new(error.message, error.span))?;
|
||||
Binder::new(model).bind_expression(&expr)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
//! Aggregation functions.
|
||||
//!
|
||||
//! The core evaluator switch owns `SUM`, `AVERAGE`, `COUNT`, `COUNTA`, `COUNTBLANK`, `MIN`,
|
||||
//! `MAX`, `PRODUCT` and the `*X` iterators. This module covers the aggregations the core switch
|
||||
//! leaves out: the `*A` variants, whose text/Boolean coercions differ from their plain
|
||||
//! counterparts, and `DISTINCTCOUNTNOBLANK`.
|
||||
//!
|
||||
//! All four read a column under the current filter context and delegate the arithmetic to
|
||||
//! [`support::aggregate_values`]. `AVERAGEA` uses every row in the denominator and coerces
|
||||
//! BLANK to 0 (Microsoft's DAX example averages 1, 20, "n/a", BLANK, TRUE as 22/5), so only a
|
||||
//! column with no rows at all is BLANK; `DISTINCTCOUNTNOBLANK` drops BLANK before counting
|
||||
//! distinct values.
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Scalar aggregation functions owned by this module.
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
match name.to_ascii_uppercase().as_str() {
|
||||
"AVERAGEA" | "DISTINCTCOUNTNOBLANK" | "MAXA" | "MINA" => Some(aggregate_column(ev, name, args, ctx)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregations are scalar-only; none of these names is a table function, so table dispatch
|
||||
/// never handles one and always returns `None`.
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Evaluates the single column argument and aggregates it. The catalog gives every function in
|
||||
/// this module exactly one `Column` parameter, so a missing argument is a programming error the
|
||||
/// binder already rejected; report it as an ordinary evaluation error all the same.
|
||||
fn aggregate_column(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let column = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a column")))?;
|
||||
let values = ev.column_values(column, ctx)?;
|
||||
super::support::aggregate_values(name, &values)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,71 @@
|
||||
//! Logical functions.
|
||||
//!
|
||||
//! This module owns the engine-only bitwise integer operations and `IF.EAGER`. `IF`, `AND`, `OR`,
|
||||
//! `NOT`, `COALESCE` and `IFERROR` live in the core evaluator because they need lazy argument
|
||||
//! evaluation; `IF.EAGER` is the documented opposite: it forces both branches to be evaluated
|
||||
//! before the condition selects one.
|
||||
|
||||
use super::support::{args as arg_values, eval_all};
|
||||
use super::*;
|
||||
|
||||
/// Scalar logical functions owned by this module: the bitwise integer operations and `IF.EAGER`.
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
match name.as_str() {
|
||||
"BITAND" | "BITOR" | "BITXOR" => Some(bitwise(&name, ev, args, ctx)),
|
||||
"IF.EAGER" => Some(if_eager(ev, args, ctx)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Logical functions are scalar-only; none of these names is a table function, so this module
|
||||
/// never handles table dispatch and always returns `None`.
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Evaluates `BITAND`, `BITOR` or `BITXOR` with both arguments forced, truncating each operand
|
||||
/// to a 64-bit integer before applying the operation. A native `Integer` stays exact: converting
|
||||
/// it through `f64` would lose bits above 2^53.
|
||||
fn bitwise(name: &str, ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = eval_all(ev, args, ctx)?;
|
||||
let a = arg_values(name, &values);
|
||||
let left = bit_operand(a.arg(0)?, name, 0)?;
|
||||
let right = bit_operand(a.arg(1)?, name, 1)?;
|
||||
let result = match name {
|
||||
"BITAND" => left & right,
|
||||
"BITOR" => left | right,
|
||||
"BITXOR" => left ^ right,
|
||||
_ => return Err(EvalError::new(format!("{name} is not a bitwise function"))),
|
||||
};
|
||||
Ok(Scalar::Integer(result))
|
||||
}
|
||||
|
||||
/// Bit operations use the truncated two's-complement `i64` value; DAX documents a signed 64-bit
|
||||
/// result, so negative operands participate through their two's-complement representation.
|
||||
///
|
||||
/// A native `Integer` is used as-is so whole numbers above 2^53 keep every bit. Other numeric
|
||||
/// variants are converted to `f64` (already lossy above 2^53 for `Decimal`) and truncated.
|
||||
fn bit_operand(value: &Scalar, name: &str, index: usize) -> Result<i64, EvalError> {
|
||||
if let Scalar::Integer(integer) = value {
|
||||
return Ok(*integer);
|
||||
}
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))?;
|
||||
if !number.is_finite() || number.trunc() < -9_223_372_036_854_775_808.0 || number.trunc() >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new(format!("{name} argument {} is outside the 64-bit integer range", index + 1)));
|
||||
}
|
||||
Ok(number.trunc() as i64)
|
||||
}
|
||||
|
||||
/// `IF.EAGER` evaluates the condition and both branch expressions before choosing a result, so an
|
||||
/// error in the branch that would not be selected still propagates.
|
||||
fn if_eager(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = eval_all(ev, args, ctx)?;
|
||||
let a = arg_values("IF.EAGER", &values);
|
||||
let condition = a.boolean(0)?;
|
||||
let when_true = a.arg(1)?;
|
||||
if condition {
|
||||
return Ok(when_true.clone());
|
||||
}
|
||||
Ok(a.optional(2).cloned().unwrap_or(Scalar::Blank))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,765 @@
|
||||
//! Shared helpers for the category-specific function implementations.
|
||||
//!
|
||||
//! Each function family lives in its own module (`financial`, `statistical`, ...) and exposes a
|
||||
//! `call`/`call_table` dispatcher. Those dispatchers receive the unevaluated arguments and the
|
||||
//! evaluator's [`Context`](super::Context), so they can choose lazy or eager evaluation and can
|
||||
//! push row frames for iterators. This module holds the small, boring pieces they share: scalar
|
||||
//! argument coercion, Excel date serials, rounding and row-frame construction.
|
||||
#![allow(dead_code)] // helpers are consumed by the per-family modules as they land
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use super::*;
|
||||
use chrono::{Datelike, NaiveDate};
|
||||
|
||||
/// The evaluated arguments of a scalar function call.
|
||||
pub(crate) struct Args<'a> {
|
||||
pub(crate) name: &'a str,
|
||||
pub(crate) values: &'a [Scalar],
|
||||
}
|
||||
|
||||
impl<'a> Args<'a> {
|
||||
pub(crate) fn arg(&self, index: usize) -> Result<&'a Scalar, EvalError> {
|
||||
self.values.get(index).ok_or_else(|| EvalError::new(format!("{} is missing argument {}", self.name, index + 1)))
|
||||
}
|
||||
|
||||
pub(crate) fn optional(&self, index: usize) -> Option<&'a Scalar> {
|
||||
self.values.get(index)
|
||||
}
|
||||
|
||||
pub(crate) fn number(&self, index: usize) -> Result<f64, EvalError> {
|
||||
self.arg(index)?.to_number().ok_or_else(|| EvalError::new(format!("{} argument {} must be numeric", self.name, index + 1)))
|
||||
}
|
||||
|
||||
pub(crate) fn int(&self, index: usize) -> Result<i64, EvalError> {
|
||||
Ok(self.number(index)? as i64)
|
||||
}
|
||||
|
||||
pub(crate) fn text(&self, index: usize) -> Result<String, EvalError> {
|
||||
Ok(self.arg(index)?.to_text())
|
||||
}
|
||||
|
||||
pub(crate) fn boolean(&self, index: usize) -> Result<bool, EvalError> {
|
||||
self.arg(index)?.to_bool().ok_or_else(|| EvalError::new(format!("{} argument {} must be Boolean", self.name, index + 1)))
|
||||
}
|
||||
|
||||
pub(crate) fn date(&self, index: usize) -> Result<f64, EvalError> {
|
||||
let value = self.number(index)?;
|
||||
if !value.is_finite() {
|
||||
return Err(EvalError::new(format!("{} argument {} must be a date", self.name, index + 1)));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn optional_number(&self, index: usize, default: f64) -> Result<f64, EvalError> {
|
||||
match self.values.get(index) {
|
||||
Some(value) if !value.is_blank() => {
|
||||
value.to_number().ok_or_else(|| EvalError::new(format!("{} argument {} must be numeric", self.name, index + 1)))
|
||||
}
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn optional_bool(&self, index: usize, default: bool) -> Result<bool, EvalError> {
|
||||
match self.values.get(index) {
|
||||
Some(value) if !value.is_blank() => {
|
||||
value.to_bool().ok_or_else(|| EvalError::new(format!("{} argument {} must be Boolean", self.name, index + 1)))
|
||||
}
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates every argument eagerly, left to right.
|
||||
pub(crate) fn eval_all(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Vec<Scalar>, EvalError> {
|
||||
args.iter().map(|arg| ev.eval(arg, ctx)).collect()
|
||||
}
|
||||
|
||||
/// Evaluates one argument as a table.
|
||||
pub(crate) fn eval_table(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
ev.eval_table(expr, ctx)
|
||||
}
|
||||
|
||||
/// Builds a row frame for one row of a table value, mapping columns back to the model by name
|
||||
/// when the table keeps its lineage.
|
||||
pub(crate) fn frame_for(ev: &Evaluator<'_>, table: &TableValue, row: &[Scalar]) -> RowFrame {
|
||||
let names: Vec<String> = table.columns.iter().map(|column| column.name.clone()).collect();
|
||||
let model_columns: Vec<Option<usize>> = match table.lineage {
|
||||
Some(lineage) => names.iter().map(|name| ev.model().column_index(lineage, name)).collect(),
|
||||
None => vec![None; names.len()],
|
||||
};
|
||||
RowFrame { lineage: table.lineage, names, values: row.to_vec(), model_columns }
|
||||
}
|
||||
|
||||
/// Builds a frame for a plain model table row whose values follow the model column order.
|
||||
pub(crate) fn model_row_frame(ev: &Evaluator<'_>, table: usize, values: Vec<Scalar>) -> RowFrame {
|
||||
let names: Vec<String> =
|
||||
ev.model().tables.get(table).map(|table| table.columns.iter().map(|column| column.name.clone()).collect()).unwrap_or_default();
|
||||
let model_columns: Vec<Option<usize>> = (0..names.len()).map(Some).collect();
|
||||
RowFrame { lineage: Some(table), names, values, model_columns }
|
||||
}
|
||||
|
||||
/// Builds a frame for a derived table row whose columns are given explicitly.
|
||||
pub(crate) fn derived_row_frame(lineage: Option<usize>, names: Vec<String>, values: Vec<Scalar>, model_columns: Vec<Option<usize>>) -> RowFrame {
|
||||
RowFrame { lineage, names, values, model_columns }
|
||||
}
|
||||
|
||||
/// Eagerly evaluated scalar argument access for functions that already hold `Vec<Scalar>`.
|
||||
pub(crate) fn args<'a>(name: &'a str, values: &'a [Scalar]) -> Args<'a> {
|
||||
Args { name, values }
|
||||
}
|
||||
|
||||
/// Orders two scalars for sorting: deterministic, transitive and total over every variant.
|
||||
///
|
||||
/// [`Scalar::compare`] follows DAX's `=`/`<` coercion rules and answers `None` for pairs DAX
|
||||
/// does not compare: text against a number, and anything against NaN. A sort cannot read `None`
|
||||
/// as equality, because text would then equal every number while the numbers still order among
|
||||
/// themselves — not a total order, which `sort_by` may panic on (Rust 1.81+).
|
||||
///
|
||||
/// This ordering ranks whole classes instead, so mixed columns sort predictably:
|
||||
///
|
||||
/// 1. numbers (`Integer`, `Currency`, `Decimal`, `DateTime`) by numeric value, through
|
||||
/// `f64::total_cmp`, so NaN has a fixed place (after every other number) and `-0.0` sorts
|
||||
/// before `0.0`;
|
||||
/// 2. text, case-insensitively (Unicode lowercase, matching [`Scalar::compare`]); strings equal
|
||||
/// under lowercasing tie-break on the raw strings, so `"A"` and `"a"` still have a fixed
|
||||
/// order;
|
||||
/// 3. Booleans, `FALSE` before `TRUE`.
|
||||
///
|
||||
/// BLANK is the caller's business. Callers with a blank placement policy (`FIRST`/`LAST` in
|
||||
/// `RANK`/`ROWNUMBER`, the blank-aware window ordering) place blanks before calling. A blank
|
||||
/// that does reach this function orders as the number zero, which is DAX's default comparison
|
||||
/// and keeps the order transitive.
|
||||
pub(crate) fn total_order(left: &Scalar, right: &Scalar) -> Ordering {
|
||||
fn class(value: &Scalar) -> u8 {
|
||||
match value {
|
||||
Scalar::String(_) => 1,
|
||||
Scalar::Boolean(_) => 2,
|
||||
Scalar::Blank | Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
// BLANK counts as zero, as in DAX's default comparison; every other number-class variant has
|
||||
// a numeric value, so the NaN fallback is unreachable but keeps the function total.
|
||||
fn number(value: &Scalar) -> f64 {
|
||||
value.to_number().unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
match class(left).cmp(&class(right)) {
|
||||
Ordering::Equal => match (left, right) {
|
||||
(Scalar::String(a), Scalar::String(b)) => a.to_lowercase().cmp(&b.to_lowercase()).then_with(|| a.cmp(b)),
|
||||
(Scalar::Boolean(a), Scalar::Boolean(b)) => a.cmp(b),
|
||||
_ => number(left).total_cmp(&number(right)),
|
||||
},
|
||||
ordering => ordering,
|
||||
}
|
||||
}
|
||||
|
||||
/// 400 Gregorian years, after which the calendar (and every month length) repeats.
|
||||
const GREGORIAN_CYCLE_DAYS: i64 = 146_097;
|
||||
/// chrono counts days from 0001-01-01; 1970-01-01 is the 719,163rd of them.
|
||||
const UNIX_EPOCH_CE_DAYS: i64 = 719_163;
|
||||
/// Excel/OLE serial 0 is 1899-12-30, which is 25,569 days before 1970-01-01.
|
||||
const UNIX_EPOCH_SERIAL: i64 = 25_569;
|
||||
/// The CE day of Excel/OLE serial 0 (1899-12-30): `UNIX_EPOCH_CE_DAYS - UNIX_EPOCH_SERIAL`.
|
||||
const EXCEL_EPOCH_CE_DAYS: i64 = 693_594;
|
||||
|
||||
/// Excel/OLE date serial for a calendar date and time. Dates before 1900-03-01 ignore the
|
||||
/// 1900 leap-year compatibility bug; DAX/Excel only differ there.
|
||||
pub(crate) fn date_serial(year: i64, month: i64, day: i64, hour: i64, minute: i64, second: i64) -> f64 {
|
||||
// Normalize out-of-range months the way Excel does (DATE(2024, 13, 1) is 2025-01-01). The day
|
||||
// counts on from the first of that month, so day 0 is the last day of the month before.
|
||||
let months = month - 1;
|
||||
let year = year.saturating_add(months.div_euclid(12));
|
||||
let month = u32::try_from(months.rem_euclid(12) + 1).unwrap_or(1);
|
||||
let days = month_start_ce_days(year, month) - i128::from(EXCEL_EPOCH_CE_DAYS) + i128::from(day) - 1;
|
||||
days as f64 + (hour as f64 * 3600.0 + minute as f64 * 60.0 + second as f64) / 86400.0
|
||||
}
|
||||
|
||||
/// Calendar date of an Excel/OLE date serial's whole days.
|
||||
pub(crate) fn date_parts(serial: f64) -> (i64, i64, i64) {
|
||||
let unix = (serial.floor() as i64).saturating_sub(UNIX_EPOCH_SERIAL);
|
||||
// The calendar repeats every 400 years (146,097 days), so chrono converts the day within its
|
||||
// cycle and the whole cycles go back into the year (AGENTS.md).
|
||||
let (cycles, rest) = (unix.div_euclid(GREGORIAN_CYCLE_DAYS), unix.rem_euclid(GREGORIAN_CYCLE_DAYS));
|
||||
match i32::try_from(rest + UNIX_EPOCH_CE_DAYS).ok().and_then(NaiveDate::from_num_days_from_ce_opt) {
|
||||
Some(date) => {
|
||||
let year = i128::from(date.year()) + i128::from(cycles) * 400;
|
||||
let year = i64::try_from(year).unwrap_or(if year < 0 { i64::MIN } else { i64::MAX });
|
||||
(year, i64::from(date.month()), i64::from(date.day()))
|
||||
}
|
||||
// Unreachable: `rest + 719_163` is always a valid CE day.
|
||||
None => (1970, 1, 1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of days in a calendar month, `30` for a month outside 1–12 (the value the caller expects
|
||||
/// for a month the evaluator has already normalized).
|
||||
pub(crate) fn days_in_month(year: i64, month: i64) -> i64 {
|
||||
if !(1..=12).contains(&month) {
|
||||
return 30;
|
||||
}
|
||||
// The month's length repeats with the 400-year cycle, so the year within it answers and always
|
||||
// fits `NaiveDate`.
|
||||
let year = year.rem_euclid(400) as i32;
|
||||
let month = month as u32;
|
||||
let first = |year: i32, month: u32| NaiveDate::from_ymd_opt(year, month, 1);
|
||||
match (first(year, month), if month == 12 { first(year + 1, 1) } else { first(year, month + 1) }) {
|
||||
(Some(start), Some(next)) => (next - start).num_days(),
|
||||
// Unreachable: the year is in 0..=399 and the month is 1..=12.
|
||||
_ => 30,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a year is a Gregorian leap year, for every `i64` year.
|
||||
pub(crate) fn is_leap_year(year: i64) -> bool {
|
||||
// Leap years repeat every 400 years, so the year within its cycle decides and always fits
|
||||
// `NaiveDate`: 29 February exists exactly in a leap year.
|
||||
NaiveDate::from_ymd_opt(year.rem_euclid(400) as i32, 2, 29).is_some()
|
||||
}
|
||||
|
||||
/// Days since 0001-01-01 (chrono's `num_days_from_ce`) of the first day of a calendar month, for
|
||||
/// every `i64` year. Whole 400-year Gregorian cycles are added back as days.
|
||||
fn month_start_ce_days(year: i64, month: u32) -> i128 {
|
||||
let cycles = i128::from(year.div_euclid(400));
|
||||
let year = year.rem_euclid(400) as i32;
|
||||
match NaiveDate::from_ymd_opt(year, month, 1) {
|
||||
Some(first) => i128::from(first.num_days_from_ce()) + cycles * i128::from(GREGORIAN_CYCLE_DAYS),
|
||||
// Unreachable: the year within its cycle is in 0..=399 and the month is 1..=12.
|
||||
None => i128::from(NaiveDate::MIN.num_days_from_ce()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn date_weekday(serial: f64) -> i64 {
|
||||
let days = serial.floor() as i64;
|
||||
let weekday = days.rem_euclid(7);
|
||||
if weekday == 0 { 7 } else { weekday }
|
||||
}
|
||||
|
||||
/// The year and month `months` away from the month of `serial`, or `None` when the shift leaves
|
||||
/// the years Excel dates can represent.
|
||||
///
|
||||
/// The month total is computed in `i128`: `months` arrives from `number(..) as i64`, which saturates
|
||||
/// at `i64::MAX`, and `year * 12 + month - 1 + months` would wrap (or panic in debug builds) for
|
||||
/// such an argument.
|
||||
fn shift_month(serial: f64, months: i64) -> Option<(i64, i64)> {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
let total = i128::from(year) * 12 + i128::from(month) - 1 + i128::from(months);
|
||||
let year = i64::try_from(total.div_euclid(12)).ok()?;
|
||||
if !(1..=9999).contains(&year) {
|
||||
return None;
|
||||
}
|
||||
Some((year, i64::try_from(total.rem_euclid(12)).ok()? + 1))
|
||||
}
|
||||
|
||||
pub(crate) fn eomonth(serial: f64, months: i64) -> f64 {
|
||||
match shift_month(serial, months) {
|
||||
Some((year, month)) => date_serial(year, month, days_in_month(year, month), 0, 0, 0),
|
||||
// A shift Excel cannot represent leaves the date where it was instead of wrapping.
|
||||
None => serial,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn edate(serial: f64, months: i64) -> f64 {
|
||||
let (_, _, day) = date_parts(serial);
|
||||
match shift_month(serial, months) {
|
||||
Some((year, month)) => date_serial(year, month, day.min(days_in_month(year, month)), 0, 0, 0),
|
||||
None => serial,
|
||||
}
|
||||
}
|
||||
|
||||
/// The local date as an Excel serial (TODAY).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn today_serial() -> f64 {
|
||||
now_serial().floor()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn today_serial() -> f64 {
|
||||
now_serial().floor()
|
||||
}
|
||||
|
||||
/// The browser clock as an Excel serial, the wasm arm of [`now_serial`]/[`utc_now_serial`].
|
||||
///
|
||||
/// The standard library's clock traps on wasm, so the epoch comes from `js_sys::Date`, the same
|
||||
/// source `crates/core/src/date.rs` uses. `Date::now()` is UTC milliseconds; for the local serial
|
||||
/// the browser's time-zone offset is subtracted (it counts minutes *west* of UTC), and only
|
||||
/// `TODAY`/`UTCTODAY` floor the result.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn wasm_now_serial(local: bool) -> f64 {
|
||||
const MILLISECONDS_PER_DAY: f64 = 86_400_000.0;
|
||||
let offset_minutes = if local { -js_sys::Date::new_0().get_timezone_offset() } else { 0.0 };
|
||||
25569.0 + js_sys::Date::now() / MILLISECONDS_PER_DAY + offset_minutes / 1_440.0
|
||||
}
|
||||
|
||||
/// The local date and time as an Excel serial (NOW).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn now_serial() -> f64 {
|
||||
use chrono::{Datelike, Timelike};
|
||||
let now = chrono::Local::now();
|
||||
date_serial(
|
||||
i64::from(now.year()),
|
||||
i64::from(now.month()),
|
||||
i64::from(now.day()),
|
||||
i64::from(now.hour()),
|
||||
i64::from(now.minute()),
|
||||
i64::from(now.second()),
|
||||
) + f64::from(now.nanosecond()) / 86_400_000_000_000.0
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn now_serial() -> f64 {
|
||||
wasm_now_serial(true)
|
||||
}
|
||||
|
||||
/// The UTC date and time as an Excel serial (UTCNOW).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn utc_now_serial() -> f64 {
|
||||
use chrono::{Datelike, Timelike};
|
||||
let now = chrono::Utc::now();
|
||||
date_serial(
|
||||
i64::from(now.year()),
|
||||
i64::from(now.month()),
|
||||
i64::from(now.day()),
|
||||
i64::from(now.hour()),
|
||||
i64::from(now.minute()),
|
||||
i64::from(now.second()),
|
||||
) + f64::from(now.nanosecond()) / 86_400_000_000_000.0
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn utc_now_serial() -> f64 {
|
||||
wasm_now_serial(false)
|
||||
}
|
||||
|
||||
/// The UTC date at midnight as an Excel serial (UTCTODAY).
|
||||
pub(crate) fn utc_today_serial() -> f64 {
|
||||
utc_now_serial().floor()
|
||||
}
|
||||
|
||||
/// Rounds `value` to 15 significant digits, the precision Excel and DAX compute with.
|
||||
///
|
||||
/// `value * 10^digits` carries the binary representation error of its factors, and a directed
|
||||
/// rounding makes that error visible: `0.29 * 100` is `28.999999999999996`, so `ROUNDDOWN ( 0.29,
|
||||
/// 2 )` would truncate to `0.28` and `ROUNDUP ( 0.07, 2 )` would ceil `7.000000000000001` to
|
||||
/// `0.08`. Snap that noise away before rounding, exactly as `to_dax_text` does when it prints.
|
||||
fn excel_precision(value: f64) -> f64 {
|
||||
// An exact whole number under 2^53 has no binary noise to remove, and snapping it would drop
|
||||
// digits: `ROUND ( 1234567890123457, 0 )` must stay that number.
|
||||
if is_exact_whole(value) {
|
||||
return value;
|
||||
}
|
||||
format!("{value:.14e}").parse().unwrap_or(value)
|
||||
}
|
||||
|
||||
/// Whether `value` is a whole number held exactly in an `f64`.
|
||||
fn is_exact_whole(value: f64) -> bool {
|
||||
value.fract() == 0.0 && value.abs() < 2f64.powi(53)
|
||||
}
|
||||
|
||||
pub(crate) fn round_to(value: f64, digits: i32) -> f64 {
|
||||
// The scale factor overflows or underflows outside f64's exponent range: past +308 digits the
|
||||
// value cannot change, past -308 every digit is rounded away.
|
||||
if digits > 308 {
|
||||
return value;
|
||||
}
|
||||
if digits < -308 {
|
||||
return 0.0;
|
||||
}
|
||||
// An exact whole number is already rounded: scaling it past 2^53 would only make the snap
|
||||
// lose digits, so `ROUND ( 1234567890123457, 1 )` stays that number.
|
||||
if digits >= 0 && is_exact_whole(value) {
|
||||
return value;
|
||||
}
|
||||
let factor = 10f64.powi(digits);
|
||||
let scaled = excel_precision(value * factor);
|
||||
if !scaled.is_finite() {
|
||||
return value;
|
||||
}
|
||||
scaled.round() / factor
|
||||
}
|
||||
|
||||
/// ROUNDUP/ROUNDDOWN: `up` rounds away from zero, otherwise toward zero. Excel and DAX define
|
||||
/// both in terms of the sign, not the floor/ceiling, so `ROUNDDOWN ( -2.9, 0 )` is -2 and
|
||||
/// `ROUNDUP ( -2.1, 0 )` is -3.
|
||||
pub(crate) fn round_direction(value: f64, digits: i32, up: bool) -> f64 {
|
||||
// `10^digits` overflows or underflows outside f64's exponent range; the result is the value
|
||||
// itself when rounding cannot move any digit, and zero when every digit is rounded away.
|
||||
if digits > 308 {
|
||||
return value;
|
||||
}
|
||||
if digits < -308 {
|
||||
return if up && value != 0.0 { f64::INFINITY.copysign(value) } else { 0.0 };
|
||||
}
|
||||
if digits >= 0 && is_exact_whole(value) {
|
||||
return value;
|
||||
}
|
||||
let factor = 10f64.powi(digits);
|
||||
let scaled = excel_precision(value * factor);
|
||||
if !scaled.is_finite() {
|
||||
return value;
|
||||
}
|
||||
let rounded = if up { scaled.abs().ceil().copysign(scaled) } else { scaled.trunc() };
|
||||
rounded / factor
|
||||
}
|
||||
|
||||
/// The greatest common divisor of the two magnitudes, so `i64::MIN` is represented without
|
||||
/// overflowing the way `i64::abs` would.
|
||||
pub(crate) fn gcd(a: i64, b: i64) -> u64 {
|
||||
let (mut a, mut b) = (a.unsigned_abs(), b.unsigned_abs());
|
||||
while b != 0 {
|
||||
let t = a % b;
|
||||
a = b;
|
||||
b = t;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// The least common multiple, or `None` when it does not fit in an `i64` (Excel answers `#NUM!`).
|
||||
pub(crate) fn lcm(a: i64, b: i64) -> Option<i64> {
|
||||
if a == 0 || b == 0 {
|
||||
return Some(0);
|
||||
}
|
||||
(a.unsigned_abs() / gcd(a, b)).checked_mul(b.unsigned_abs()).and_then(|value| i64::try_from(value).ok())
|
||||
}
|
||||
|
||||
/// Applies a scalar aggregation over already-evaluated values.
|
||||
pub(crate) fn aggregate_values(name: &str, values: &[Scalar]) -> Result<Scalar, EvalError> {
|
||||
// Plain aggregations take numeric values only: DAX specifies that SUM/AVERAGE/MIN/MAX/PRODUCT
|
||||
// ignore logicals and text instead of coercing them. The `*A` variants below keep their own
|
||||
// coercion and read `values` directly.
|
||||
let numbers: Vec<f64> = values
|
||||
.iter()
|
||||
.filter(|value| matches!(value, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_)))
|
||||
.filter_map(Scalar::to_number)
|
||||
.collect();
|
||||
match name.to_ascii_uppercase().as_str() {
|
||||
"SUM" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().sum()) }),
|
||||
"AVERAGE" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().sum::<f64>() / numbers.len() as f64) }),
|
||||
"AVERAGEA" => {
|
||||
// Every row counts: text (numeric or not) counts as 0, TRUE/FALSE as 1/0, and a BLANK
|
||||
// cell as 0, so it stays in the denominator — Microsoft's example averages 1, 20,
|
||||
// "n/a", BLANK and TRUE as 22/5. A column with no rows at all is BLANK.
|
||||
if values.is_empty() {
|
||||
return Ok(Scalar::Blank);
|
||||
}
|
||||
let sum: f64 = values
|
||||
.iter()
|
||||
.map(|value| match value {
|
||||
Scalar::String(_) => 0.0,
|
||||
Scalar::Boolean(value) => f64::from(u8::from(*value)),
|
||||
other => other.to_number().unwrap_or(0.0),
|
||||
})
|
||||
.sum();
|
||||
Ok(Scalar::Decimal(sum / values.len() as f64))
|
||||
}
|
||||
"PRODUCT" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().product()) }),
|
||||
"MIN" | "MAX" => {
|
||||
// The winner keeps its own type — a date column answers a DateTime and an integer
|
||||
// column an Integer — so this cannot read the `f64` projection the sum-like
|
||||
// aggregations use. Only numbers compete: text and logicals are not observations.
|
||||
let want = if name.eq_ignore_ascii_case("MIN") { Ordering::Less } else { Ordering::Greater };
|
||||
let mut best: Option<&Scalar> = None;
|
||||
for value in
|
||||
values.iter().filter(|value| matches!(value, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_)))
|
||||
{
|
||||
match best {
|
||||
None => best = Some(value),
|
||||
Some(current) if value.compare(current) == Some(want) => best = Some(value),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
Ok(best.cloned().unwrap_or(Scalar::Blank))
|
||||
}
|
||||
"MINA" => Ok(values
|
||||
.iter()
|
||||
.filter(|value| !value.is_blank())
|
||||
.map(|value| match value {
|
||||
Scalar::String(_) => 0.0,
|
||||
Scalar::Boolean(value) => f64::from(u8::from(*value)),
|
||||
other => other.to_number().unwrap_or(0.0),
|
||||
})
|
||||
.reduce(f64::min)
|
||||
.map(Scalar::Decimal)
|
||||
.unwrap_or(if values.is_empty() { Scalar::Blank } else { Scalar::Decimal(0.0) })),
|
||||
"MAXA" => Ok(values
|
||||
.iter()
|
||||
.filter(|value| !value.is_blank())
|
||||
.map(|value| match value {
|
||||
Scalar::String(_) => 0.0,
|
||||
Scalar::Boolean(value) => f64::from(u8::from(*value)),
|
||||
other => other.to_number().unwrap_or(0.0),
|
||||
})
|
||||
.reduce(f64::max)
|
||||
.map(Scalar::Decimal)
|
||||
.unwrap_or(if values.is_empty() { Scalar::Blank } else { Scalar::Decimal(0.0) })),
|
||||
"COUNT" => {
|
||||
let count = values.iter().filter(|v| !v.is_blank() && !matches!(v, Scalar::Boolean(_))).count();
|
||||
Ok(if count == 0 { Scalar::Blank } else { Scalar::Integer(count as i64) })
|
||||
}
|
||||
"COUNTA" => {
|
||||
let count = values.iter().filter(|v| !v.is_blank()).count();
|
||||
Ok(if count == 0 { Scalar::Blank } else { Scalar::Integer(count as i64) })
|
||||
}
|
||||
"COUNTBLANK" => Ok(Scalar::Integer(values.iter().filter(|v| v.is_blank() || v.to_text().is_empty()).count() as i64)),
|
||||
"DISTINCTCOUNT" | "APPROXIMATEDISTINCTCOUNT" => {
|
||||
let distinct: BTreeSet<ScalarKey> = values.iter().map(distinct_key).collect();
|
||||
Ok(if values.is_empty() { Scalar::Blank } else { Scalar::Integer(distinct.len() as i64) })
|
||||
}
|
||||
"DISTINCTCOUNTNOBLANK" => {
|
||||
let distinct: BTreeSet<ScalarKey> = values.iter().filter(|value| !value.is_blank()).map(distinct_key).collect();
|
||||
Ok(Scalar::Integer(distinct.len() as i64))
|
||||
}
|
||||
_ => Err(EvalError::not_implemented(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Coerces a scalar to a date serial, treating blanks as 0.
|
||||
pub(crate) fn date_value(value: &Scalar) -> Option<f64> {
|
||||
match value {
|
||||
Scalar::DateTime(serial) => Some(*serial),
|
||||
Scalar::String(text) => parse_date_text(text),
|
||||
Scalar::Blank => None,
|
||||
other => other.to_number(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the common textual date forms Excel accepts (`YYYY-MM-DD`, `MM/DD/YYYY`,
|
||||
/// `YYYY-MM-DDTHH:MM:SS`). Locale-specific `DD/MM/YYYY` is deliberately ambiguous and rejected.
|
||||
/// A component outside the calendar (month 13, 30 February) is rejected rather than rolled over.
|
||||
pub(crate) fn parse_date_text(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (date, time) = match text.split_once(['T', ' ']) {
|
||||
Some((date, time)) => (date, Some(time)),
|
||||
None => (text, None),
|
||||
};
|
||||
let parts: Vec<&str> = date.split(['-', '/']).collect();
|
||||
let (year, month, day) = match parts.as_slice() {
|
||||
[first, second, third] => {
|
||||
let first_value: i64 = first.parse().ok()?;
|
||||
let second_value: i64 = second.parse().ok()?;
|
||||
let third_value: i64 = third.parse().ok()?;
|
||||
// A four-digit leading part is `YYYY-MM-DD`; anything else is `MM/DD/YYYY`.
|
||||
let (year, month, day) =
|
||||
if first.len() >= 4 { (first_value, second_value, third_value) } else { (third_value, first_value, second_value) };
|
||||
let year = if year < 100 { year + if year < 30 { 2000 } else { 1900 } } else { year };
|
||||
if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
|
||||
return None;
|
||||
}
|
||||
(year, month, day)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let (hour, minute, second) = match time.map(str::trim).filter(|time| !time.is_empty()) {
|
||||
None => (0, 0, 0),
|
||||
Some(time) => {
|
||||
// `datetime_text` prints a date as `M/D/YYYY H:MM:SS AM/PM`, so the form the crate
|
||||
// itself writes has to parse back. The suffix decides the half of the day and the
|
||||
// hour is then 1-12; without it the hour is 0-23.
|
||||
let (clock, meridiem) = match time.rsplit_once(' ') {
|
||||
Some((clock, suffix)) if suffix.eq_ignore_ascii_case("AM") || suffix.eq_ignore_ascii_case("PM") => {
|
||||
(clock.trim(), Some(suffix.eq_ignore_ascii_case("PM")))
|
||||
}
|
||||
_ => (time, None),
|
||||
};
|
||||
// A present time must parse and be in range: `25:00:00` is rejected rather than
|
||||
// rolled into the next day, like an impossible date.
|
||||
let parts: Vec<&str> = clock.split(':').collect();
|
||||
let hour: i64 = parts.first()?.trim().parse().ok()?;
|
||||
let minute: i64 = parts.get(1).unwrap_or(&"0").trim().parse().ok()?;
|
||||
let second: i64 = parts.get(2).unwrap_or(&"0").trim().parse().ok()?;
|
||||
let hour = match meridiem {
|
||||
// 12 AM is midnight and 12 PM is noon; the other PM hours move to the afternoon.
|
||||
Some(pm) if (1..=12).contains(&hour) => match (hour, pm) {
|
||||
(12, false) => 0,
|
||||
(12, true) => 12,
|
||||
(hour, true) => hour + 12,
|
||||
(hour, false) => hour,
|
||||
},
|
||||
Some(_) => return None,
|
||||
None => hour,
|
||||
};
|
||||
if !(0..24).contains(&hour) || !(0..60).contains(&minute) || !(0..60).contains(&second) {
|
||||
return None;
|
||||
}
|
||||
(hour, minute, second)
|
||||
}
|
||||
};
|
||||
Some(date_serial(year, month, day, hour, minute, second))
|
||||
}
|
||||
|
||||
/// Current evaluation frame's innermost row frame, if any.
|
||||
pub(crate) fn current_frame(ctx: &Context) -> Option<&RowFrame> {
|
||||
ctx.rows.last()
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Columns that are rolled up (blanked) in the `SUMMARIZE` row currently being evaluated.
|
||||
/// `None` outside a `SUMMARIZE` expression, so `ISSUBTOTAL` can tell "detail row" from "not in
|
||||
/// a `SUMMARIZE` at all". The state lives here, next to the evaluator's other row-context
|
||||
/// state, because the function that reads it (`ISSUBTOTAL`) and the one that writes it
|
||||
/// (`SUMMARIZE`) ship in different evaluator families.
|
||||
static SUBTOTAL_COLUMNS: RefCell<Option<Vec<(usize, usize)>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The rolled-up columns of the `SUMMARIZE` row being evaluated, or `None` outside `SUMMARIZE`.
|
||||
pub(crate) fn subtotal_columns() -> Option<Vec<(usize, usize)>> {
|
||||
SUBTOTAL_COLUMNS.with(|columns| columns.borrow().clone())
|
||||
}
|
||||
|
||||
/// Pushes the rolled-up columns for one `SUMMARIZE` row and restores the outer state on drop, so
|
||||
/// a nested `SUMMARIZE` and an error path both leave the context as they found it.
|
||||
pub(crate) struct SubtotalGuard(Option<Vec<(usize, usize)>>);
|
||||
|
||||
impl SubtotalGuard {
|
||||
pub(crate) fn push(columns: Vec<(usize, usize)>) -> Self {
|
||||
let previous = SUBTOTAL_COLUMNS.with(|current| current.borrow_mut().replace(columns));
|
||||
SubtotalGuard(previous)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SubtotalGuard {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
SUBTOTAL_COLUMNS.with(|current| *current.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serials_round_trip_through_chrono() {
|
||||
// Serial 0 is 1899-12-30 and 25,569 is 1970-01-01.
|
||||
assert_eq!(date_serial(1899, 12, 30, 0, 0, 0), 0.0);
|
||||
assert_eq!(date_serial(1970, 1, 1, 0, 0, 0), 25_569.0);
|
||||
assert_eq!(date_parts(0.0), (1899, 12, 30));
|
||||
assert_eq!(date_parts(25_569.0), (1970, 1, 1));
|
||||
// Leap days exist exactly in leap years.
|
||||
assert_eq!(date_serial(2024, 2, 29, 0, 0, 0), 45_351.0);
|
||||
assert_eq!(date_parts(45_351.0), (2024, 2, 29));
|
||||
assert_eq!(date_serial(2000, 2, 29, 0, 0, 0), date_serial(2000, 3, 1, 0, 0, 0) - 1.0);
|
||||
// A time of day is a fraction of the serial.
|
||||
assert_eq!(date_serial(1970, 1, 1, 12, 0, 0), 25_569.5);
|
||||
assert_eq!(date_parts(25_569.75), (1970, 1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serial_helpers_extend_past_chronos_year_range() {
|
||||
// 400 Gregorian years are 146,097 days, so year 400,000 is 999 cycles after year 400.
|
||||
let cycles = 999.0 * 146_097.0;
|
||||
assert_eq!(date_serial(400_000, 1, 1, 0, 0, 0) - cycles, date_serial(400, 1, 1, 0, 0, 0));
|
||||
assert_eq!(date_parts(date_serial(400_000, 2, 29, 0, 0, 0)), (400_000, 2, 29));
|
||||
// The cycle repeats leap-year and month-length rules too.
|
||||
assert!(is_leap_year(400_000));
|
||||
assert!(!is_leap_year(300_100));
|
||||
assert_eq!(days_in_month(400_000, 2), 29);
|
||||
assert_eq!(days_in_month(300_100, 2), 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_months_and_days_roll_over_like_date() {
|
||||
// DATE(2024, 13, 1) is 2025-01-01 and day 0 is the last day of the previous month.
|
||||
assert_eq!(date_serial(2024, 13, 1, 0, 0, 0), date_serial(2025, 1, 1, 0, 0, 0));
|
||||
assert_eq!(date_serial(2024, 0, 1, 0, 0, 0), date_serial(2023, 12, 1, 0, 0, 0));
|
||||
assert_eq!(date_serial(2024, 3, 0, 0, 0, 0), date_serial(2024, 2, 29, 0, 0, 0));
|
||||
assert_eq!(days_in_month(2024, 2), 29);
|
||||
assert_eq!(days_in_month(2023, 2), 28);
|
||||
assert_eq!(days_in_month(1900, 2), 28);
|
||||
assert_eq!(days_in_month(2000, 2), 29);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_aggregations_ignore_text_logicals_and_blanks() {
|
||||
// DAX specifies that SUM/AVERAGE/MIN/MAX/PRODUCT use the numeric rows only: text (even
|
||||
// numeric text), logicals and BLANK are ignored, unlike the `*A` variants.
|
||||
let values = [
|
||||
Scalar::Integer(2),
|
||||
Scalar::String("3".into()),
|
||||
Scalar::Boolean(true),
|
||||
Scalar::Blank,
|
||||
Scalar::Decimal(0.5),
|
||||
Scalar::Currency(15_000),
|
||||
Scalar::DateTime(10.0),
|
||||
];
|
||||
assert_eq!(aggregate_values("SUM", &values).expect("SUM"), Scalar::Decimal(14.0));
|
||||
assert_eq!(aggregate_values("AVERAGE", &values).expect("AVERAGE"), Scalar::Decimal(3.5));
|
||||
// MIN/MAX return the winning value itself: its type survives, so the 10.0 date stays a
|
||||
// DateTime rather than becoming a decimal serial.
|
||||
assert_eq!(aggregate_values("MIN", &values).expect("MIN"), Scalar::Decimal(0.5));
|
||||
assert_eq!(aggregate_values("MAX", &values).expect("MAX"), Scalar::DateTime(10.0));
|
||||
assert_eq!(aggregate_values("PRODUCT", &values).expect("PRODUCT"), Scalar::Decimal(15.0));
|
||||
let integers = [Scalar::Integer(7), Scalar::Integer(3), Scalar::Blank];
|
||||
assert_eq!(aggregate_values("MIN", &integers).expect("MIN"), Scalar::Integer(3));
|
||||
assert_eq!(aggregate_values("MAX", &integers).expect("MAX"), Scalar::Integer(7));
|
||||
// A column holding only text, logicals and blanks has no numeric observations at all.
|
||||
let non_numeric = [Scalar::String("5".into()), Scalar::Boolean(false), Scalar::Blank];
|
||||
assert_eq!(aggregate_values("SUM", &non_numeric).expect("SUM"), Scalar::Blank);
|
||||
assert_eq!(aggregate_values("AVERAGE", &non_numeric).expect("AVERAGE"), Scalar::Blank);
|
||||
// The `*A` variants keep their own coercion: text counts as 0 and TRUE as 1.
|
||||
assert_eq!(aggregate_values("MINA", &non_numeric).expect("MINA"), Scalar::Decimal(0.0));
|
||||
assert_eq!(aggregate_values("COUNTA", &non_numeric).expect("COUNTA"), Scalar::Integer(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_text_parses_month_first_and_rejects_impossible_dates() {
|
||||
// `MM/DD/YYYY`: the leading part is the month, not the year.
|
||||
assert_eq!(parse_date_text("1/8/2009"), Some(39_821.0));
|
||||
assert_eq!(parse_date_text("1/8/09"), Some(39_821.0));
|
||||
// ISO order, and a trailing time is kept.
|
||||
assert_eq!(parse_date_text("2024-01-15"), Some(45_306.0));
|
||||
assert_eq!(parse_date_text("2024-01-15T06:00:00"), Some(45_306.25));
|
||||
// Out-of-range components are rejected instead of rolling over.
|
||||
assert_eq!(parse_date_text("2024-02-30"), None);
|
||||
assert_eq!(parse_date_text("13/1/2024"), None);
|
||||
assert_eq!(parse_date_text("2024-00-10"), None);
|
||||
assert_eq!(parse_date_text("2023-02-29"), None);
|
||||
assert_eq!(parse_date_text("1/8"), None);
|
||||
assert_eq!(parse_date_text(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_text_round_trips_the_ampm_form_the_crate_prints() {
|
||||
// `datetime_text` writes `M/D/YYYY H:MM:SS AM/PM`, so the same text has to parse back:
|
||||
// 12 AM is midnight and 12 PM is noon, and the other PM hours move to the afternoon.
|
||||
assert_eq!(parse_date_text("1/2/2024 12:00:00 AM"), Some(date_serial(2024, 1, 2, 0, 0, 0)));
|
||||
assert_eq!(parse_date_text("1/2/2024 12:00:00 PM"), Some(date_serial(2024, 1, 2, 12, 0, 0)));
|
||||
assert_eq!(parse_date_text("1/2/2024 1:30:15 PM"), Some(date_serial(2024, 1, 2, 13, 30, 15)));
|
||||
assert_eq!(parse_date_text("1/2/2024 1:30:15 AM"), Some(date_serial(2024, 1, 2, 1, 30, 15)));
|
||||
// A suffixed hour is 1-12, so 13 PM and 0 AM are impossible rather than 13:00 and 00:00.
|
||||
assert_eq!(parse_date_text("1/2/2024 13:00:00 PM"), None);
|
||||
assert_eq!(parse_date_text("1/2/2024 0:00:00 AM"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounding_snaps_binary_noise_at_fifteen_digits() {
|
||||
// `value * 100` carries the binary error of the input, and a directed rounding exposes it.
|
||||
assert_eq!(round_to(1.005, 2), 1.01);
|
||||
assert_eq!(round_direction(0.29, 2, false), 0.29);
|
||||
assert_eq!(round_direction(0.07, 2, true), 0.07);
|
||||
// The ordinary cases still behave: sign-aware directed rounding and half away from zero.
|
||||
assert_eq!(round_direction(-2.9, 0, false), -2.0);
|
||||
assert_eq!(round_direction(-2.1, 0, true), -3.0);
|
||||
assert_eq!(round_to(2.5, 0), 3.0);
|
||||
assert_eq!(round_to(2.345, 2), 2.35);
|
||||
// An exact whole input is already the answer: scaling it past 2^53 must not snap digits.
|
||||
assert_eq!(round_to(1_234_567_890_123_457.0, 1), 1_234_567_890_123_457.0);
|
||||
assert_eq!(round_direction(1_234_567_890_123_457.0, 2, true), 1_234_567_890_123_457.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gcd_and_lcm_report_results_that_do_not_fit() {
|
||||
assert_eq!(gcd(12, 18), 6);
|
||||
// `i64::MIN` has no positive counterpart: the magnitudes are used instead of `abs`.
|
||||
assert_eq!(gcd(i64::MIN, 2), 2);
|
||||
assert_eq!(lcm(4, 6), Some(12));
|
||||
assert_eq!(lcm(0, 7), Some(0));
|
||||
// Coprime operands above 2^32 overflow the product, which Excel answers with `#NUM!`.
|
||||
assert_eq!(lcm(1 << 40, (1 << 40) + 1), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,728 @@
|
||||
//! Semantic catalog of the DAX functions.
|
||||
//!
|
||||
//! The catalog records the documented signature of every function in every
|
||||
//! <https://dax.guide/functions/> category — arity, parameter kinds, overloads, return type,
|
||||
//! iterator/volatile behaviour, syntax-sugar relationships, blank handling and host-compatibility
|
||||
//! flags. It is static metadata: the parser already accepts these calls, and [`crate::validate`]
|
||||
//! uses the records to reject statically impossible arguments.
|
||||
//!
|
||||
//! Documentation conflicts (for example whether `COUNTBLANK` returns 0 when rows exist but no
|
||||
//! cell is blank) are recorded as [`BlankPolicy::Unspecified`] instead of silently picking one
|
||||
//! source. See the crate README for the per-function notes.
|
||||
|
||||
/// The function family, matching dax.guide's category pages.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum FunctionCategory {
|
||||
Aggregation,
|
||||
DateAndTime,
|
||||
Filter,
|
||||
Financial,
|
||||
Information,
|
||||
Logical,
|
||||
MathAndTrig,
|
||||
Other,
|
||||
ParentChild,
|
||||
RelationshipManagement,
|
||||
Statistical,
|
||||
TableManipulation,
|
||||
Text,
|
||||
TimeIntelligence,
|
||||
VisualCalculations,
|
||||
}
|
||||
|
||||
impl FunctionCategory {
|
||||
pub const ALL: [FunctionCategory; 15] = [
|
||||
FunctionCategory::Aggregation,
|
||||
FunctionCategory::DateAndTime,
|
||||
FunctionCategory::Filter,
|
||||
FunctionCategory::Financial,
|
||||
FunctionCategory::Information,
|
||||
FunctionCategory::Logical,
|
||||
FunctionCategory::MathAndTrig,
|
||||
FunctionCategory::Other,
|
||||
FunctionCategory::ParentChild,
|
||||
FunctionCategory::RelationshipManagement,
|
||||
FunctionCategory::Statistical,
|
||||
FunctionCategory::TableManipulation,
|
||||
FunctionCategory::Text,
|
||||
FunctionCategory::TimeIntelligence,
|
||||
FunctionCategory::VisualCalculations,
|
||||
];
|
||||
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
FunctionCategory::Aggregation => "Aggregation",
|
||||
FunctionCategory::DateAndTime => "Date and Time",
|
||||
FunctionCategory::Filter => "Filter",
|
||||
FunctionCategory::Financial => "Financial",
|
||||
FunctionCategory::Information => "Information",
|
||||
FunctionCategory::Logical => "Logical",
|
||||
FunctionCategory::MathAndTrig => "Math and Trig",
|
||||
FunctionCategory::Other => "Other",
|
||||
FunctionCategory::ParentChild => "Parent-child",
|
||||
FunctionCategory::RelationshipManagement => "Relationship management",
|
||||
FunctionCategory::Statistical => "Statistical",
|
||||
FunctionCategory::TableManipulation => "Table manipulation",
|
||||
FunctionCategory::Text => "Text",
|
||||
FunctionCategory::TimeIntelligence => "Time Intelligence",
|
||||
FunctionCategory::VisualCalculations => "Visual calculations",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What an argument position accepts.
|
||||
///
|
||||
/// Only [`ParamKind::Column`] and [`ParamKind::Table`] can be checked without a data model;
|
||||
/// the remaining kinds are recorded for documentation and future type checking.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ParamKind {
|
||||
/// A column reference such as `Sales[Amount]` or `[Amount]`.
|
||||
Column,
|
||||
/// A table expression such as `Sales`, `FILTER ( ... )` or `{ 1, 2 }`.
|
||||
Table,
|
||||
/// A scalar expression evaluated in the iterator's row context.
|
||||
Expression,
|
||||
/// A scalar expression evaluated in the caller's context.
|
||||
Scalar,
|
||||
/// A logical (Boolean) expression.
|
||||
Logical,
|
||||
/// Any expression.
|
||||
Any,
|
||||
/// A date/time value.
|
||||
Date,
|
||||
/// A text value.
|
||||
Text,
|
||||
/// A numeric value.
|
||||
Number,
|
||||
/// A Boolean value.
|
||||
Boolean,
|
||||
/// A function or lambda reference.
|
||||
Function,
|
||||
/// A table or column reference.
|
||||
Reference,
|
||||
/// A JSON value.
|
||||
Json,
|
||||
/// A value whose type is decided at run time.
|
||||
Variant,
|
||||
}
|
||||
|
||||
impl ParamKind {
|
||||
/// Human-readable description used in validation messages.
|
||||
pub const fn description(self) -> &'static str {
|
||||
match self {
|
||||
ParamKind::Column => "a column reference",
|
||||
ParamKind::Table => "a table expression",
|
||||
ParamKind::Expression => "an expression",
|
||||
ParamKind::Scalar => "a scalar expression",
|
||||
ParamKind::Logical => "a logical expression",
|
||||
ParamKind::Any => "any expression",
|
||||
ParamKind::Date => "a date/time expression",
|
||||
ParamKind::Text => "a text expression",
|
||||
ParamKind::Number => "a numeric expression",
|
||||
ParamKind::Boolean => "a Boolean expression",
|
||||
ParamKind::Function => "a function reference",
|
||||
ParamKind::Reference => "a table or column reference",
|
||||
ParamKind::Json => "a JSON value",
|
||||
ParamKind::Variant => "a value of any type",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The documented result type. `Numeric` covers decimal/currency/integer results whose exact
|
||||
/// type depends on the model, and `Any` covers functions whose result type follows the inputs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ReturnType {
|
||||
Integer,
|
||||
Numeric,
|
||||
Currency,
|
||||
Decimal,
|
||||
Any,
|
||||
Boolean,
|
||||
DateTime,
|
||||
String,
|
||||
Table,
|
||||
Blank,
|
||||
Variant,
|
||||
}
|
||||
|
||||
impl ReturnType {
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
ReturnType::Integer => "Integer",
|
||||
ReturnType::Numeric => "Numeric",
|
||||
ReturnType::Currency => "Currency",
|
||||
ReturnType::Decimal => "Decimal",
|
||||
ReturnType::Any => "Any",
|
||||
ReturnType::Boolean => "Boolean",
|
||||
ReturnType::DateTime => "DateTime",
|
||||
ReturnType::String => "String",
|
||||
ReturnType::Table => "Table",
|
||||
ReturnType::Blank => "Blank",
|
||||
ReturnType::Variant => "Variant",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns when there is nothing to aggregate.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum BlankPolicy {
|
||||
/// BLANK when the input has no rows or no qualifying value.
|
||||
BlankWhenEmpty,
|
||||
/// 0 when rows exist but none match, as Microsoft Learn documents for some functions. The
|
||||
/// catalog does not currently use this variant: observed engine behaviour and dax.guide
|
||||
/// disagree with that rule for every function where it was considered.
|
||||
ZeroWhenRowsButNoMatch,
|
||||
/// Sources conflict or are silent; callers must not rely on either result.
|
||||
Unspecified,
|
||||
}
|
||||
|
||||
impl BlankPolicy {
|
||||
/// Human-readable description used by documentation and tests.
|
||||
pub const fn description(self) -> &'static str {
|
||||
match self {
|
||||
BlankPolicy::BlankWhenEmpty => "BLANK when empty",
|
||||
BlankPolicy::ZeroWhenRowsButNoMatch => "0 when rows exist but none match",
|
||||
BlankPolicy::Unspecified => "unspecified",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Behaviours that change how a host or optimiser treats the function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct FunctionFlags {
|
||||
/// The function is an iterator: it evaluates a second argument once per row of a table.
|
||||
pub iterator: bool,
|
||||
/// The function may return a different value on every call (`NOW`, `RAND`, ...).
|
||||
pub volatile: bool,
|
||||
/// dax.guide marks the function as not recommended.
|
||||
pub not_recommended: bool,
|
||||
/// The function is available to Excel's embedded DAX engine.
|
||||
pub excel_compatible: bool,
|
||||
/// Microsoft Learn documents DirectQuery restrictions (calculated columns / RLS rules).
|
||||
pub direct_query_limited: bool,
|
||||
}
|
||||
|
||||
impl FunctionFlags {
|
||||
pub const fn new(iterator: bool, volatile: bool, not_recommended: bool, excel_compatible: bool, direct_query_limited: bool) -> Self {
|
||||
FunctionFlags { iterator, volatile, not_recommended, excel_compatible, direct_query_limited }
|
||||
}
|
||||
}
|
||||
|
||||
/// One argument in a descriptive signature, including whether it may be omitted.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Parameter {
|
||||
pub name: &'static str,
|
||||
pub kind: ParamKind,
|
||||
pub optional: bool,
|
||||
}
|
||||
|
||||
const fn required(name: &'static str, kind: ParamKind) -> Parameter {
|
||||
Parameter { name, kind, optional: false }
|
||||
}
|
||||
|
||||
const fn optional(name: &'static str, kind: ParamKind) -> Parameter {
|
||||
Parameter { name, kind, optional: true }
|
||||
}
|
||||
|
||||
/// One exact arity and its parameter kinds. Overloads enumerate every accepted arity, including
|
||||
/// zero-argument `COUNTROWS ()` and the optional `Variant` argument of `MAXX`/`MINX`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Overload {
|
||||
pub params: &'static [ParamKind],
|
||||
/// When true, the last parameter kind repeats for every additional argument.
|
||||
pub variadic: bool,
|
||||
}
|
||||
|
||||
impl Overload {
|
||||
pub const fn arity(self) -> usize {
|
||||
self.params.len()
|
||||
}
|
||||
|
||||
/// Whether this overload accepts exactly `arity` arguments.
|
||||
pub const fn matches(self, arity: usize) -> bool {
|
||||
if self.variadic { arity >= self.params.len() } else { arity == self.params.len() }
|
||||
}
|
||||
|
||||
/// The parameter kind at `index`; a variadic overload repeats its last kind.
|
||||
pub fn kind_at(self, index: usize) -> Option<ParamKind> {
|
||||
self.params.get(index).copied().or_else(|| if self.variadic { self.params.last().copied() } else { None })
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn overload(params: &'static [ParamKind]) -> Overload {
|
||||
Overload { params, variadic: false }
|
||||
}
|
||||
|
||||
pub const fn variadic(params: &'static [ParamKind]) -> Overload {
|
||||
Overload { params, variadic: true }
|
||||
}
|
||||
|
||||
/// A complete catalog record.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FunctionSpec {
|
||||
pub name: &'static str,
|
||||
pub category: FunctionCategory,
|
||||
pub min_args: usize,
|
||||
pub max_args: usize,
|
||||
/// Descriptive signature. Optional markers live here; [`FunctionSpec::overloads`] enumerates
|
||||
/// the concrete arity/kind combinations.
|
||||
pub params: &'static [Parameter],
|
||||
pub overloads: &'static [Overload],
|
||||
pub return_type: ReturnType,
|
||||
pub flags: FunctionFlags,
|
||||
/// The function this one is syntax sugar for, when the semantics are identical.
|
||||
pub sugar_of: Option<&'static str>,
|
||||
pub blank_policy: BlankPolicy,
|
||||
pub description: &'static str,
|
||||
pub examples: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl FunctionSpec {
|
||||
/// Whether the function evaluates an expression per row of a table.
|
||||
pub const fn is_iterator(&self) -> bool {
|
||||
self.flags.iterator
|
||||
}
|
||||
|
||||
/// The overload accepting exactly `arity` arguments, if any.
|
||||
pub fn overload_for(&self, arity: usize) -> Option<&Overload> {
|
||||
self.overloads.iter().find(|overload| overload.matches(arity))
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a catalog record with no syntax-sugar link and an unspecified blank policy. Most
|
||||
/// functions use this; aggregation records spell out the extra fields.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub const fn spec(
|
||||
name: &'static str,
|
||||
category: FunctionCategory,
|
||||
min_args: usize,
|
||||
max_args: usize,
|
||||
params: &'static [Parameter],
|
||||
overloads: &'static [Overload],
|
||||
return_type: ReturnType,
|
||||
flags: FunctionFlags,
|
||||
description: &'static str,
|
||||
examples: &'static [&'static str],
|
||||
) -> FunctionSpec {
|
||||
FunctionSpec {
|
||||
name,
|
||||
category,
|
||||
min_args,
|
||||
max_args,
|
||||
params,
|
||||
overloads,
|
||||
return_type,
|
||||
flags,
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description,
|
||||
examples,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn standard(iterator: bool) -> FunctionFlags {
|
||||
FunctionFlags::new(iterator, false, false, true, true)
|
||||
}
|
||||
|
||||
/// All aggregation functions, in the order listed by dax.guide.
|
||||
pub static AGGREGATION: [FunctionSpec; 22] = [
|
||||
FunctionSpec {
|
||||
name: "APPROXIMATEDISTINCTCOUNT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: FunctionFlags::new(false, false, false, false, true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Approximates the number of distinct values in a column. DirectQuery models \
|
||||
push the aggregation to the source; Import models use HyperLogLog with a \
|
||||
small error rate. The argument must be a column reference.",
|
||||
examples: &["APPROXIMATEDISTINCTCOUNT ( Sales[ProductKey] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "AVERAGE",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("AVERAGEX"),
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Arithmetic mean of a numeric column, ignoring blanks and including zero. \
|
||||
Syntax sugar for AVERAGEX. dax.guide returns BLANK when no value qualifies, \
|
||||
while Microsoft Learn documents 0 when rows exist; the catalog keeps the \
|
||||
conflict explicit.",
|
||||
examples: &["AVERAGE ( Sales[Amount] )", "AVERAGE ( Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "AVERAGEA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: FunctionFlags::new(false, false, true, true, true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Averages a column, counting TRUE as 1, FALSE as 0 and any text as 0. \
|
||||
Internally evaluated with AVERAGEX but not pure sugar because of those \
|
||||
coercions; dax.guide marks it not recommended. Sources disagree on the \
|
||||
empty/all-blank result.",
|
||||
examples: &["AVERAGEA ( Customer[LargeFamily] )", "AVERAGEA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "AVERAGEX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression once per row of the table and returns the mean of \
|
||||
the non-blank results, including zeros. The expression runs in row context, \
|
||||
so a measure reference triggers context transition.",
|
||||
examples: &["AVERAGEX ( Sales, Sales[Quantity] * Sales[Net Price] )", "AVERAGEX ( Customer, [Sales Amount] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("COUNTX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts non-blank numbers, dates and strings in a column; empty strings count \
|
||||
and booleans do not. Syntax sugar for COUNTX.",
|
||||
examples: &["COUNT ( Customer[Customer Name] )", "COUNT ( Sales[Text] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("COUNTAX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts non-blank values in a column, including booleans (as values, not as \
|
||||
1/0). Syntax sugar for COUNTAX.",
|
||||
examples: &["COUNTA ( Customer[Customer Name] )", "COUNTA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTAX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression per row and counts non-blank results, including \
|
||||
booleans.",
|
||||
examples: &["COUNTAX ( Customer, Customer[LargeFamily] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTBLANK",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Counts blanks in a column of any type; the empty string counts as blank and \
|
||||
zero does not. dax.guide says the function never returns 0, while Microsoft \
|
||||
Learn documents 0 when rows exist but no value is blank.",
|
||||
examples: &["COUNTBLANK ( Customer[Customer Name] )", "COUNTBLANK ( Sales[Text] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTROWS",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 0,
|
||||
max_args: 1,
|
||||
params: &[optional("Table", ParamKind::Table)],
|
||||
overloads: &[overload(&[]), overload(&[ParamKind::Table])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts the rows of a table expression. With no argument it counts the home \
|
||||
table of the measure or calculated column. Excel's embedded engine accepts \
|
||||
the one-argument form only.",
|
||||
examples: &["COUNTROWS ( Sales )", "COUNTROWS ( DISTINCT ( Sales[Region] ) )", "COUNTROWS ( )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression per row and counts non-blank results of type number, \
|
||||
date or string; booleans are not counted (use COUNTAX).",
|
||||
examples: &["COUNTX ( Customer, DIVIDE ( Customer[Total Children], Customer[Cars Owned] ) )", "COUNTX ( Sales, Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "DISTINCTCOUNT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts distinct values in a column of any type. BLANK is one distinct value; \
|
||||
totals are not additive. Equivalent to COUNTROWS ( DISTINCT ( table[column] ) ).",
|
||||
examples: &["DISTINCTCOUNT ( Store[Area Manager] )", "DISTINCTCOUNT ( Sales[Region] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "DISTINCTCOUNTNOBLANK",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: FunctionFlags::new(false, false, false, false, true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Counts distinct values in a column, excluding BLANK — DISTINCTCOUNT counts \
|
||||
BLANK, so this is not pure sugar for it. Not available to Excel's embedded \
|
||||
engine.",
|
||||
examples: &["DISTINCTCOUNTNOBLANK ( Store[Area Manager] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MAX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 2,
|
||||
params: &[required("ColumnNameOrScalar1", ParamKind::Any), optional("Scalar2", ParamKind::Scalar)],
|
||||
overloads: &[overload(&[ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Scalar])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "With one argument, the largest non-blank value of a column (the same result \
|
||||
MAXX gives over the column); text compares alphabetically and logical values are unsupported. With \
|
||||
two arguments, the larger scalar, where BLANK is significant per dax.guide \
|
||||
but treated as zero by Microsoft Learn.",
|
||||
examples: &["MAX ( Sales[Net Price] )", "MAX ( 10000, [Sales Amount] )", "MAX ( 3, 5 )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MAXA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Largest value of a column, counting TRUE as 1 and FALSE as 0 instead of \
|
||||
ignoring logical values. Internally MAXX. Sources disagree on the empty \
|
||||
result; text is not rankable.",
|
||||
examples: &["MAXA ( Customer[LargeFamily] )", "MAXA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MAXX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 3,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), optional("Variant", ParamKind::Logical)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression]), overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Logical])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Evaluates the expression per row and returns the largest value, skipping \
|
||||
blanks and ignoring logical values. Mixed-type expressions consider numbers \
|
||||
only unless Variant is TRUE, which compares per ORDER BY DESC.",
|
||||
examples: &["MAXX ( Customer, 1 * Customer[LargeFamily] )", "MAXX ( Sales, Sales[Amount], TRUE )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MIN",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 2,
|
||||
params: &[required("ColumnNameOrScalar1", ParamKind::Any), optional("Scalar2", ParamKind::Scalar)],
|
||||
overloads: &[overload(&[ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Scalar])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "With one argument, the smallest non-blank value of a column (the same result \
|
||||
MINX gives over the column); text compares alphabetically and logical values are unsupported. With \
|
||||
two arguments, the smaller scalar, where BLANK is significant per dax.guide \
|
||||
but treated as zero by Microsoft Learn.",
|
||||
examples: &["MIN ( Sales[Net Price] )", "MIN ( 5000000, [Sales Amount] )", "MIN ( 3, 5 )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MINA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Smallest value of a column, counting TRUE as 1 and FALSE as 0 instead of \
|
||||
ignoring logical values. Internally MINX. Sources disagree on the empty \
|
||||
result.",
|
||||
examples: &["MINA ( Customer[LargeFamily] )", "MINA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MINX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 3,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), optional("Variant", ParamKind::Logical)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression]), overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Logical])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Evaluates the expression per row and returns the smallest value, skipping \
|
||||
blanks and ignoring logical values. Mixed-type expressions consider numbers \
|
||||
only unless Variant is TRUE, which compares per ORDER BY ASC.",
|
||||
examples: &["MINX ( Customer, 1 * Customer[NoCars] )", "MINX ( Sales, Sales[Amount], FALSE )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "PRODUCT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Decimal,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("PRODUCTX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Multiplies the numbers in a column, ignoring blanks, logical values and text. \
|
||||
Syntax sugar for PRODUCTX.",
|
||||
examples: &["PRODUCT ( Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "PRODUCTX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Decimal,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression per row and multiplies the non-blank numeric \
|
||||
results; blanks, logical values and text are ignored, unlike the `*` \
|
||||
operator.",
|
||||
examples: &["PRODUCTX ( Rates, 1 + Rates[InflationRate] )", "PRODUCTX ( Sales, Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "SUM",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("SUMX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Adds the numbers in a column, ignoring blanks, logical values and text. \
|
||||
Syntax sugar for SUMX. dax.guide says the result type follows the column, \
|
||||
while Microsoft Learn documents a decimal number.",
|
||||
examples: &["SUM ( Sales[Amount] )", "SUM ( Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "SUMX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression once per row of the table and sums the numeric \
|
||||
results; blanks, logical values and text are ignored. The expression runs \
|
||||
in row context.",
|
||||
examples: &[
|
||||
"SUMX ( Sales, Sales[Quantity] * Sales[Net Price] )",
|
||||
"SUMX ( FILTER ( InternetSales, InternetSales[SalesTerritoryID] = 5 ), [Freight] )",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
pub mod date_time;
|
||||
pub mod filter;
|
||||
pub mod financial;
|
||||
pub mod information;
|
||||
pub mod logical;
|
||||
pub mod math_trig;
|
||||
pub mod other;
|
||||
pub mod parent_child;
|
||||
pub mod relationships;
|
||||
pub mod statistical;
|
||||
pub mod table_manipulation;
|
||||
pub mod text;
|
||||
pub mod time_intelligence;
|
||||
pub mod visual_calculations;
|
||||
|
||||
/// Every function from every category, in dax.guide category order.
|
||||
static CATALOG: std::sync::LazyLock<Vec<FunctionSpec>> = std::sync::LazyLock::new(|| {
|
||||
let mut all = Vec::with_capacity(600);
|
||||
all.extend_from_slice(&AGGREGATION);
|
||||
all.extend_from_slice(date_time::FUNCTIONS);
|
||||
all.extend_from_slice(filter::FUNCTIONS);
|
||||
all.extend_from_slice(financial::FUNCTIONS);
|
||||
all.extend_from_slice(information::FUNCTIONS);
|
||||
all.extend_from_slice(logical::FUNCTIONS);
|
||||
all.extend_from_slice(math_trig::FUNCTIONS);
|
||||
all.extend_from_slice(other::FUNCTIONS);
|
||||
all.extend_from_slice(parent_child::FUNCTIONS);
|
||||
all.extend_from_slice(relationships::FUNCTIONS);
|
||||
all.extend_from_slice(statistical::FUNCTIONS);
|
||||
all.extend_from_slice(table_manipulation::FUNCTIONS);
|
||||
all.extend_from_slice(text::FUNCTIONS);
|
||||
all.extend_from_slice(time_intelligence::FUNCTIONS);
|
||||
all.extend_from_slice(visual_calculations::FUNCTIONS);
|
||||
all
|
||||
});
|
||||
|
||||
/// Every catalogued function.
|
||||
pub fn catalog() -> &'static [FunctionSpec] {
|
||||
&CATALOG
|
||||
}
|
||||
|
||||
/// Looks a function up by name, ignoring ASCII case.
|
||||
pub fn lookup(name: &str) -> Option<&'static FunctionSpec> {
|
||||
CATALOG.iter().find(|spec| spec.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
//! Date and time functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
|
||||
|
||||
use FunctionCategory::DateAndTime;
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"CALENDAR",
|
||||
DateAndTime,
|
||||
2,
|
||||
2,
|
||||
&[required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
standard(false),
|
||||
"CALENDAR ( <StartDate>, <EndDate> ) returns a single-column table named Date with every \
|
||||
day from StartDate to EndDate, both included. Dates are stored as numbers, so integer \
|
||||
bounds such as CALENDAR ( 1, 100 ) are accepted; a date table should cover whole years \
|
||||
for time-intelligence compatibility.",
|
||||
&["CALENDAR ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )", "CALENDAR ( DATE ( 2023, 7, 1 ), DATE ( 2024, 6, 30 ) )"],
|
||||
),
|
||||
spec(
|
||||
"CALENDARAUTO",
|
||||
DateAndTime,
|
||||
0,
|
||||
1,
|
||||
&[optional("FiscalYearEndMonth", ParamKind::Number)],
|
||||
&[overload(&[]), overload(&[ParamKind::Number])],
|
||||
ReturnType::Table,
|
||||
standard(false),
|
||||
"CALENDARAUTO ( [<FiscalYearEndMonth>] ) scans the imported date columns and returns a \
|
||||
contiguous Date table covering whole fiscal years. FiscalYearEndMonth is 1-12 and \
|
||||
defaults to 12 (December); calculated tables and calculated columns are ignored, and \
|
||||
the model must contain at least one imported datetime column or the call fails.",
|
||||
&["CALENDARAUTO ()", "CALENDARAUTO ( 6 )"],
|
||||
),
|
||||
spec(
|
||||
"DATE",
|
||||
DateAndTime,
|
||||
3,
|
||||
3,
|
||||
&[required("Year", ParamKind::Number), required("Month", ParamKind::Number), required("Day", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"DATE ( <Year>, <Month>, <Day> ) builds a DateTime from numeric parts. Years 0-99 add \
|
||||
1900 (DATE ( 98, 1, 2 ) is 1998-01-02) while years below -1800 or above 9999 raise an \
|
||||
error; month and day overflow roll into neighbouring months and days (DATE ( 2024, 13, \
|
||||
1 ) is 2025-01-01).",
|
||||
&["DATE ( 2024, 1, 1 )", "DATE ( 2024, 13, 1 )", "DATE ( YEAR ( Sales[Order Date] ), 1, 1 )"],
|
||||
),
|
||||
spec(
|
||||
"DATEDIFF",
|
||||
DateAndTime,
|
||||
3,
|
||||
3,
|
||||
&[required("Date1", ParamKind::Date), required("Date2", ParamKind::Date), required("Interval", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"DATEDIFF ( <Date1>, <Date2>, <Interval> ) counts the Interval boundaries crossed \
|
||||
between two dates, positively when Date2 is later and negatively otherwise. Interval is \
|
||||
an unquoted keyword: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or YEAR.",
|
||||
&["DATEDIFF ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), DAY )", "DATEDIFF ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), MONTH )"],
|
||||
),
|
||||
spec(
|
||||
"DATEVALUE",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("DateText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"DATEVALUE ( <DateText> ) converts a text date to a DateTime using the locale of the \
|
||||
model, so \"1/8/2009\" may mean January 8 or August 1. A missing year is taken from the \
|
||||
current year and any time portion is ignored.",
|
||||
&["DATEVALUE ( \"2024-01-01\" )", "DATEVALUE ( \"1/8/2009\" )"],
|
||||
),
|
||||
spec(
|
||||
"DAY",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"DAY ( <Date> ) returns the day of the month as an integer from 1 to 31. A text argument \
|
||||
is converted with the same rules as DATEVALUE, so the locale of the model decides how \
|
||||
the text is read.",
|
||||
&["DAY ( DATE ( 2024, 1, 15 ) )", "DAY ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"EDATE",
|
||||
DateAndTime,
|
||||
2,
|
||||
2,
|
||||
&[required("StartDate", ParamKind::Date), required("Months", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"EDATE ( <StartDate>, <Months> ) shifts a date by the given number of months, keeping the \
|
||||
day of the month and clamping to the end of shorter months (2024-01-31 plus one month \
|
||||
is 2024-02-29). Unlike EOMONTH it does not move to the end of the month.",
|
||||
&["EDATE ( DATE ( 2024, 1, 31 ), 1 )", "EDATE ( Sales[Order Date], -3 )"],
|
||||
),
|
||||
spec(
|
||||
"EOMONTH",
|
||||
DateAndTime,
|
||||
2,
|
||||
2,
|
||||
&[required("StartDate", ParamKind::Date), required("Months", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"EOMONTH ( <StartDate>, <Months> ) returns the last day of the month that is Months \
|
||||
before or after StartDate; 0 gives the end of the current month. There is no SOMONTH, so \
|
||||
the start of a month is EOMONTH ( <date>, -1 ) + 1.",
|
||||
&["EOMONTH ( DATE ( 2024, 1, 15 ), 0 )", "EOMONTH ( Sales[Order Date], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"HOUR",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Datetime", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"HOUR ( <Datetime> ) gives the hour as an integer from 0 to 23. A string that holds only \
|
||||
a time, such as \"16:48:00\", is accepted and parsed using the client computer's locale \
|
||||
and time settings.",
|
||||
&["HOUR ( TIME ( 16, 48, 23 ) )", "HOUR ( Sales[Order Time] )"],
|
||||
),
|
||||
spec(
|
||||
"MINUTE",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Datetime", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"MINUTE ( <Datetime> ) gives the minute as an integer from 0 to 59. A string that holds \
|
||||
only a time, such as \"16:48:00\", is accepted and parsed using the client computer's \
|
||||
locale and time settings.",
|
||||
&["MINUTE ( TIME ( 16, 48, 23 ) )", "MINUTE ( Sales[Order Time] )"],
|
||||
),
|
||||
spec(
|
||||
"MONTH",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"MONTH ( <Date> ) gives 1 for January through 12 for December. Text arguments are read \
|
||||
with the same rules as DATEVALUE.",
|
||||
&["MONTH ( DATE ( 2024, 1, 15 ) )", "MONTH ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NETWORKDAYS",
|
||||
DateAndTime,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("start_date", ParamKind::Date),
|
||||
required("end_date", ParamKind::Date),
|
||||
optional("weekend", ParamKind::Number),
|
||||
optional("holidays", ParamKind::Table),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Date, ParamKind::Date]),
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number]),
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Table]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"NETWORKDAYS ( <start_date>, <end_date> [, <weekend>] [, <holidays>] ) counts whole \
|
||||
workdays between two dates, both included, skipping weekends and holidays. The weekend \
|
||||
code defaults to 1 (Saturday and Sunday), accepts 2-7 for other pairs and 11-17 for a \
|
||||
single day; holidays is a single-column table of dates. Not available in Excel's DAX \
|
||||
engine.",
|
||||
&[
|
||||
"NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ) )",
|
||||
"NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), 1, { DATE ( 2024, 1, 15 ) } )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"NOW",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"Date and time at the moment of evaluation. Volatile: it is evaluated once per query and \
|
||||
moves only when the model or the containing calculated column is refreshed, not \
|
||||
continuously.",
|
||||
&["NOW ()", "YEAR ( NOW () )"],
|
||||
),
|
||||
spec(
|
||||
"QUARTER",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"QUARTER ( <Date> ) gives the calendar quarter number, 1 for January-March through 4 for \
|
||||
October-December; fiscal periods are not followed. Text arguments are read with the \
|
||||
same rules as DATEVALUE.",
|
||||
&["QUARTER ( DATE ( 2024, 5, 15 ) )", "QUARTER ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"SECOND",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Datetime", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"SECOND ( <Datetime> ) gives the second as an integer from 0 to 59. A string that holds \
|
||||
only a time, such as \"16:48:23\", is accepted and parsed using the client computer's \
|
||||
locale and time settings.",
|
||||
&["SECOND ( TIME ( 16, 48, 23 ) )", "SECOND ( Sales[Order Time] )"],
|
||||
),
|
||||
spec(
|
||||
"TIME",
|
||||
DateAndTime,
|
||||
3,
|
||||
3,
|
||||
&[required("Hour", ParamKind::Number), required("Minute", ParamKind::Number), required("Second", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"TIME ( <Hour>, <Minute>, <Second> ) builds a time on the 1899-12-30 epoch. Overflowing \
|
||||
arguments wrap inside the same day instead of raising an error (TIME ( 10, 90, 0 ) is \
|
||||
11:30 and TIME ( 50, 0, 0 ) is 02:00), and each argument is limited to 32,767.",
|
||||
&["TIME ( 16, 48, 23 )", "TIME ( 10, 90, 0 )"],
|
||||
),
|
||||
spec(
|
||||
"TIMEVALUE",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("TimeText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"TIMEVALUE ( <TimeText> ) converts a text time to a DateTime, ignoring any date portion \
|
||||
of the string. Parsing uses the client computer's locale, date and time settings, so the \
|
||||
same text can fail or mean a different time on another machine.",
|
||||
&["TIMEVALUE ( \"16:48:23\" )", "TIMEVALUE ( \"4:48:47 PM\" )"],
|
||||
),
|
||||
spec(
|
||||
"TODAY",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"TODAY () returns the current date at 12:00:00 AM. Volatile: it is evaluated once per \
|
||||
query and only changes when the model or the containing calculated column is refreshed, \
|
||||
not continuously.",
|
||||
&["TODAY ()", "TODAY () - Sales[Order Date]"],
|
||||
),
|
||||
spec(
|
||||
"UTCNOW",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"UTCNOW () gives the date and time at the moment of evaluation, expressed in Coordinated \
|
||||
Universal Time. Volatile: it is evaluated once per query. The Power BI Service always \
|
||||
runs on UTC and applies no daylight saving, so NOW and UTCNOW agree there.",
|
||||
&["UTCNOW ()", "NOW () - UTCNOW ()"],
|
||||
),
|
||||
spec(
|
||||
"UTCTODAY",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"UTCTODAY () returns the current date at 12:00:00 AM in Coordinated Universal Time. \
|
||||
Volatile: it is evaluated once per query and only changes when the model is refreshed.",
|
||||
&["UTCTODAY ()", "TODAY () - UTCTODAY ()"],
|
||||
),
|
||||
spec(
|
||||
"WEEKDAY",
|
||||
DateAndTime,
|
||||
1,
|
||||
2,
|
||||
&[required("Date", ParamKind::Date), optional("ReturnType", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"WEEKDAY ( <Date> [, <ReturnType>] ) returns the day of the week. ReturnType 1 (default) \
|
||||
numbers Sunday 1 through Saturday 7, 2 numbers Monday 1 through Sunday 7, 3 numbers \
|
||||
Monday 0 through Sunday 6, and 11-17 start the week on Monday through Sunday. A text \
|
||||
argument is converted with the same rules as DATEVALUE.",
|
||||
&["WEEKDAY ( DATE ( 2024, 1, 1 ) )", "WEEKDAY ( Sales[Order Date], 2 )"],
|
||||
),
|
||||
spec(
|
||||
"WEEKNUM",
|
||||
DateAndTime,
|
||||
1,
|
||||
2,
|
||||
&[required("Date", ParamKind::Date), optional("ReturnType", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"WEEKNUM ( <Date> [, <ReturnType>] ) gives the week number within the year. The documented \
|
||||
codes are 1 (default), 2, 11-17 and 21: 1, 2 and 11-17 use system 1, where the week \
|
||||
containing January 1 is week 1 (each code picks the first day of the week: 1 Sunday, 2 \
|
||||
Monday, 11 Monday, 12 Tuesday, ... 17 Sunday), and 21 uses ISO 8601 system 2, where the \
|
||||
week containing the first Thursday is week 1. Codes 3-10 are not valid. Text arguments \
|
||||
are read with the same rules as DATEVALUE.",
|
||||
&["WEEKNUM ( DATE ( 2024, 1, 15 ) )", "WEEKNUM ( Sales[Order Date], 21 )"],
|
||||
),
|
||||
spec(
|
||||
"YEAR",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"YEAR ( <Date> ) gives the calendar year as a four-digit integer between 1900 and 9999. \
|
||||
Text arguments are read with the same rules as DATEVALUE.",
|
||||
&["YEAR ( DATE ( 2024, 1, 1 ) )", "YEAR ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"YEARFRAC",
|
||||
DateAndTime,
|
||||
2,
|
||||
3,
|
||||
&[required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date), optional("Basis", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"YEARFRAC ( <StartDate>, <EndDate> [, <Basis>] ) returns the fraction of a year between \
|
||||
two dates. Basis selects the day-count convention: 0 (default) US 30/360, 1 \
|
||||
actual/actual, 2 actual/360, 3 actual/365 and 4 European 30/360. Because of a known bug \
|
||||
in age calculations, dax.guide suggests INT arithmetic instead.",
|
||||
&["YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )", "YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), 1 )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,561 @@
|
||||
//! Filter functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! This category covers table expressions that inspect or remove filter context (`ALL`,
|
||||
//! `ALLSELECTED`, ...), the two functions that build a filter context (`CALCULATE`,
|
||||
//! `CALCULATETABLE`), and the window/apply clauses (`INDEX`, `OFFSET`, `WINDOW`, `ORDERBY`,
|
||||
//! `PARTITIONBY`, `MATCHBY`) that are only meaningful inside one of those table expressions.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Functions whose original implementation shipped in Excel's embedded engine. The argument
|
||||
/// order and semantics are shared with Excel 2016 and later.
|
||||
const EXCEL: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// Engine features that Power BI uses internally for composite models and window functions.
|
||||
/// Excel's embedded engine rejects them, and the DirectQuery notes still apply.
|
||||
const INTERNAL: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
/// `FILTER` is an iterator: it evaluates its predicate once per row.
|
||||
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"ALL",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Returns a table ignoring any filters on it, or every value of a column ignoring the \
|
||||
filters on that column. As a table expression it materialises all rows (or all distinct \
|
||||
values of one or more columns). Without arguments it works only inside \
|
||||
CALCULATE/CALCULATETABLE and clears the whole filter context.",
|
||||
&["ALL ( Sales )", "ALL ( Sales[Region] )", "ALL ( Sales, Sales[Region], Sales[Country] )", "ALL ( )"],
|
||||
),
|
||||
spec(
|
||||
"ALLCROSSFILTERED",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableName", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Removes, as a CALCULATE modifier only, every filter on a table and on the tables that \
|
||||
cross-filter it through weak or bidirectional relationships. Unlike ALL it never returns \
|
||||
a materialised table, so it cannot be used as a table expression.",
|
||||
&["ALLCROSSFILTERED ( Sales )", "ALLCROSSFILTERED ( 'Product' )"],
|
||||
),
|
||||
spec(
|
||||
"ALLEXCEPT",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("TableName", ParamKind::Table), required("ColumnName", ParamKind::Column), optional("ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Removes all filters from a table except those on the listed columns. As a CALCULATE \
|
||||
modifier it keeps only the named column filters; as a table expression it materialises \
|
||||
the unique combinations of the table's remaining columns.",
|
||||
&["ALLEXCEPT ( Sales, Sales[Region] )", "ALLEXCEPT ( 'Product', 'Product'[Color], 'Product'[Brand] )"],
|
||||
),
|
||||
spec(
|
||||
"ALLNOBLANKROW",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Like ALL, removes the filters on a table or on the listed columns, but always excludes \
|
||||
the blank row that the engine adds for an invalid relationship. Real blank values stored \
|
||||
in the columns are kept in the result.",
|
||||
&["ALLNOBLANKROW ( Customer )", "ALLNOBLANKROW ( Customer[Country], Customer[City] )"],
|
||||
),
|
||||
spec(
|
||||
"ALLSELECTED",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Restores the filters that came from outside the query while ignoring the filters applied \
|
||||
inside it, so the result reflects the outer shadow filter context. As a table expression \
|
||||
it needs at least one argument; without arguments it is only a CALCULATE modifier.",
|
||||
&["ALLSELECTED ( Sales )", "ALLSELECTED ( Sales[Region] )", "ALLSELECTED ( )"],
|
||||
),
|
||||
spec(
|
||||
"ALLSELECTEDAPPLY",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Marks a table expression supplied to GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE so that it \
|
||||
starts hidden from the filter context and only becomes active when ALLSELECTED runs \
|
||||
inside CALCULATE. Used internally by Power BI composite models.",
|
||||
&["ALLSELECTEDAPPLY ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ALLSELECTEDREMOVE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("TableExpression", ParamKind::Table), optional("Column", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, hides the listed columns of a table \
|
||||
expression from a later ALLSELECTED so they no longer participate in the restored filter \
|
||||
context. With no column argument every column of the expression is hidden.",
|
||||
&["ALLSELECTEDREMOVE ( VALUES ( Product[Color] ) )", "ALLSELECTEDREMOVE ( VALUES ( Product[Color] ), Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"ALWAYSAPPLY",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, forces a filter table to influence the \
|
||||
measures even if the current filter context is unchanged, for example when the table is \
|
||||
empty. Used internally by Power BI composite models.",
|
||||
&["ALWAYSAPPLY ( FILTER ( VALUES ( Product[Color] ), FALSE ) )"],
|
||||
),
|
||||
spec(
|
||||
"CALCULATE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Expression", ParamKind::Expression), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression]), variadic(&[ParamKind::Expression, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Evaluates an expression in a filter context modified by its filter arguments: table \
|
||||
expressions replace the filters on their columns, boolean predicates are wrapped in \
|
||||
FILTER over ALL, and context transition turns any row context into an equivalent filter \
|
||||
context. Returns the scalar result of the expression.",
|
||||
&["CALCULATE ( SUM ( Sales[Amount] ), Sales[Region] = \"East\" )", "CALCULATE ( [Sales Amount], ALL ( Product ) )"],
|
||||
),
|
||||
spec(
|
||||
"CALCULATETABLE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Runs a table expression under the filter context built by its filter arguments, with \
|
||||
the same filter semantics and context transition as CALCULATE but returning a table \
|
||||
instead of a scalar.",
|
||||
&["CALCULATETABLE ( VALUES ( Product[Color] ), Product[Brand] = \"GridCraft\" )"],
|
||||
),
|
||||
spec(
|
||||
"DEPENDON",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("TableExpression", ParamKind::Table), required("ColumnName", ParamKind::Column), optional("ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Anchors a table expression to outer columns: its first columns are matched, in order, \
|
||||
against the current values of the listed outer columns, acting as an inner join and \
|
||||
hiding the matched columns from the result. Used internally by Power BI composite \
|
||||
models.",
|
||||
&["DEPENDON ( Sales, Sales[OrderDate] )", "DEPENDON ( FILTER ( Sales, Sales[Amount] > 0 ), Sales[OrderDate] )"],
|
||||
),
|
||||
spec(
|
||||
"FILTER",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("FilterExpression", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Logical])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Returns the rows of a table for which the predicate is TRUE. The predicate runs in a row \
|
||||
context, so it can read the current row's columns; context transition applies when it \
|
||||
calls a measure, and BLANK evaluates as FALSE. Filter context is preserved, not replaced.",
|
||||
&["FILTER ( Sales, Sales[Amount] > 0 )", "FILTER ( ALL ( Sales ), Sales[Region] = \"East\" )"],
|
||||
),
|
||||
spec(
|
||||
"FILTERCLUSTER",
|
||||
FunctionCategory::Filter,
|
||||
4,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("FilterTable", ParamKind::Table),
|
||||
required("Separator", ParamKind::Text),
|
||||
required("TableScan", ParamKind::Table),
|
||||
],
|
||||
&[variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Internal helper for GROUPCROSSAPPLY and GROUPCROSSAPPLYTABLE that assembles the \
|
||||
correlated join over a set of groups: group-by columns, filter tables and table scans \
|
||||
are combined with autoexist semantics, and the literal separator only marks where the \
|
||||
table scans begin. Used internally by Power BI composite models.",
|
||||
&["FILTERCLUSTER ( Product[Category], ALL ( Product ), \"\", ALL ( Sales ) )"],
|
||||
),
|
||||
spec(
|
||||
"GROUPCROSSAPPLY",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("FilterTable", ParamKind::Table),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Any),
|
||||
],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Table]), variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Aggregates by the group-by columns across cross-joined filter tables, with no implicit \
|
||||
autoexist. Each name/expression pair adds a column, and rows whose expressions are all \
|
||||
blank are dropped. Used internally by Power BI composite models.",
|
||||
&["GROUPCROSSAPPLY ( 'Date'[Year], ALL ( 'Date' ) )", "GROUPCROSSAPPLY ( 'Date'[Year], ALL ( 'Date' ), \"Sales\", [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"GROUPCROSSAPPLYTABLE",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("FilterTable", ParamKind::Table),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("TableExpression", ParamKind::Table),
|
||||
],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Table]), variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Like GROUPCROSSAPPLY, but the trailing name/table-expression pairs add whole tables \
|
||||
evaluated under the filter tables' context instead of scalar expressions. Used \
|
||||
internally by Power BI composite models.",
|
||||
&["GROUPCROSSAPPLYTABLE ( 'Date'[Year], ALL ( 'Date' ), \"Colors\", VALUES ( 'Product'[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"INDEX",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
7,
|
||||
&[
|
||||
required("Position", ParamKind::Number),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Returns, as a one-row table, the row at an absolute position (1-based, negative counts \
|
||||
from the end) within each partition of the relation, sorted by the ORDERBY clause. An \
|
||||
out-of-range or zero position yields an empty table; the relation defaults to \
|
||||
ALLSELECTED over the ordering and partitioning columns.",
|
||||
&[
|
||||
"INDEX ( 1, Sales, ORDERBY ( Sales[OrderDate] ) )",
|
||||
"INDEX ( -1, ALLSELECTED ( Sales ) )",
|
||||
"INDEX ( 1, Sales, ORDERBY ( Sales[OrderDate] ), KEEP, PARTITIONBY ( Sales[Region] ) )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"KEEPFILTERS",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Expression])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Filter modifier that makes its argument intersect the existing filter context instead of \
|
||||
replacing it, so a conflicting existing filter is kept. Applies to a CALCULATE or \
|
||||
CALCULATETABLE filter argument and also preserves the filter context during context \
|
||||
transition in an iterator.",
|
||||
&["KEEPFILTERS ( Product[Color] = \"Red\" )", "KEEPFILTERS ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"LOOKUP",
|
||||
FunctionCategory::Filter,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Result_ColumnOrExpression", ParamKind::Any),
|
||||
required("Search_Column", ParamKind::Column),
|
||||
required("Search_Value", ParamKind::Any),
|
||||
optional("Search_Column", ParamKind::Column),
|
||||
optional("Search_Value", ParamKind::Any),
|
||||
optional("AssociatedColumnsBehavior", ParamKind::Text),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Searches the cells identified by the search column/value pairs and returns a column value \
|
||||
or an expression evaluated over those cells; filters on columns not listed stay applied. \
|
||||
Only one cell may match, and the optional behaviour argument selects Explicit or \
|
||||
Inferred handling of associated columns.",
|
||||
&["LOOKUP ( [Sales Amount], 'Date'[Year], 2018 )", "LOOKUP ( [Sales Amount], 'Date'[Year], 2018, \"Inferred\" )"],
|
||||
),
|
||||
spec(
|
||||
"LOOKUPVALUE",
|
||||
FunctionCategory::Filter,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Result_ColumnName", ParamKind::Column),
|
||||
required("Search_ColumnName", ParamKind::Column),
|
||||
required("Search_Value", ParamKind::Any),
|
||||
optional("Search_ColumnName", ParamKind::Column),
|
||||
optional("Search_Value", ParamKind::Any),
|
||||
optional("Alternate_Result", ParamKind::Any),
|
||||
],
|
||||
&[variadic(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Returns the result column value from the row where every search column/value pair \
|
||||
matches, ignoring the current filter context. With no match it returns BLANK or the \
|
||||
alternate result; identical values in several matching rows return that value, while \
|
||||
different values return the alternate result or an error.",
|
||||
&["LOOKUPVALUE ( Product[Color], Product[ProductKey], 1 )", "LOOKUPVALUE ( Product[Color], Product[ProductKey], 1, \"Unknown\" )"],
|
||||
),
|
||||
spec(
|
||||
"LOOKUPWITHTOTALS",
|
||||
FunctionCategory::Filter,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Result_ColumnOrExpression", ParamKind::Any),
|
||||
required("Search_Column", ParamKind::Column),
|
||||
required("Search_Value", ParamKind::Any),
|
||||
optional("Search_Column", ParamKind::Column),
|
||||
optional("Search_Value", ParamKind::Any),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Searches the cells identified by the search column/value pairs, like LOOKUP, but resets \
|
||||
the non-specified columns to their grand total instead of keeping the current filters. \
|
||||
Equivalent to COLLAPSEALL around LOOKUP.",
|
||||
&["LOOKUPWITHTOTALS ( [Sales Amount], [Year], 2018 )"],
|
||||
),
|
||||
spec(
|
||||
"MATCHBY",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("MatchBy_ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), variadic(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Declares the columns that identify the current row for a window function such as INDEX, \
|
||||
OFFSET or WINDOW. It is a clause, not a value: it can only appear inside a window \
|
||||
function and does not change the filter context by itself.",
|
||||
&["MATCHBY ( Sales[OrderKey] )", "MATCHBY ( )"],
|
||||
),
|
||||
spec(
|
||||
"NONFILTER",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, keeps a table expression out of the filter \
|
||||
context permanently, even when its columns carry lineage, as if they were extension \
|
||||
columns. Used internally by Power BI composite models.",
|
||||
&["NONFILTER ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"OFFSET",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
7,
|
||||
&[
|
||||
required("Delta", ParamKind::Number),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Returns the row that is a number of rows before or after the current row within each \
|
||||
partition of the relation, ordered by the ORDERBY clause. The result is a one-row table; \
|
||||
a delta moving outside the partition yields an empty table.",
|
||||
&["OFFSET ( -1, Sales, ORDERBY ( Sales[OrderDate] ) )", "OFFSET ( 1, Sales )"],
|
||||
),
|
||||
spec(
|
||||
"ORDERBY",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("OrderBy_Expression", ParamKind::Any), optional("OrderBy_Direction", ParamKind::Any)],
|
||||
&[overload(&[]), variadic(&[ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Declares the sort expressions and directions (ASC or DESC, optionally with BLANKS FIRST \
|
||||
or BLANKS LAST) used by a window function such as INDEX, OFFSET or WINDOW. It is a \
|
||||
clause rather than a value and cannot be evaluated on its own.",
|
||||
&["ORDERBY ( Sales[Amount], DESC )", "ORDERBY ( Sales[OrderDate], ASC )", "ORDERBY ( )"],
|
||||
),
|
||||
spec(
|
||||
"PARTITIONBY",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("PartitionBy_ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), variadic(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Declares the model columns that partition the relation of a window function such as \
|
||||
INDEX, OFFSET or WINDOW. It is a clause rather than a value, and the columns must have a \
|
||||
valid data lineage.",
|
||||
&["PARTITIONBY ( Sales[Region] )", "PARTITIONBY ( )"],
|
||||
),
|
||||
spec(
|
||||
"REMOVEFILTERS",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Alias for ALL with the same filter-removal semantics: it clears the filters on the named \
|
||||
table or columns, or every filter when called without arguments. It is only valid as a \
|
||||
CALCULATE or CALCULATETABLE modifier and never returns a table.",
|
||||
&["REMOVEFILTERS ( Sales )", "REMOVEFILTERS ( Sales[Region] )", "REMOVEFILTERS ( )"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDVALUE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), optional("AlternateResult", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Returns the value of a column when the filter context leaves exactly one distinct value, \
|
||||
otherwise returns the alternate result (BLANK when omitted). Equivalent to \
|
||||
IF ( HASONEVALUE ( column ), VALUES ( column ), alternate ).",
|
||||
&["SELECTEDVALUE ( Product[Color] )", "SELECTEDVALUE ( Product[Color], \"Multiple colors\" )"],
|
||||
),
|
||||
spec(
|
||||
"SHADOWCLUSTER",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, marks a table expression as a shadow so that \
|
||||
it is only enabled inside an ALLSELECTED context. Used internally by Power BI composite \
|
||||
models.",
|
||||
&["SHADOWCLUSTER ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"WINDOW",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
10,
|
||||
&[
|
||||
required("From", ParamKind::Number),
|
||||
optional("FromType", ParamKind::Any),
|
||||
required("To", ParamKind::Number),
|
||||
optional("ToType", ParamKind::Any),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Table,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Table,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Table,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Returns the rows between a start and an end boundary within each partition of the \
|
||||
relation, ordered by the ORDERBY clause. REL boundaries count rows from the current row \
|
||||
while ABS boundaries are absolute positions in the partition; the result is a table.",
|
||||
&["WINDOW ( 1, ABS, 1, ABS, Sales, ORDERBY ( Sales[OrderDate] ) )", "WINDOW ( -1, REL, 1, REL, Sales )"],
|
||||
),
|
||||
];
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,993 @@
|
||||
//! Information functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The `INFO.*` records take no required arguments: dax.guide documents an optional, repeatable
|
||||
//! `RestrictionName` / `RestrictionValue` pair for every one of them, so their arity is open and
|
||||
//! the descriptive signature keeps both positions optional. The `INFO.VIEW.*` functions take no
|
||||
//! arguments at all.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// An `INFO.*` table function with the shared optional restriction-pair syntax.
|
||||
macro_rules! info {
|
||||
($name:literal, $description:literal) => {
|
||||
spec(
|
||||
$name,
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("RestrictionName", ParamKind::Text), optional("RestrictionValue", ParamKind::Any)],
|
||||
&[overload(&[]), overload(&[ParamKind::Text]), variadic(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
$description,
|
||||
&[concat!($name, " ()")],
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"COLUMNSTATISTICS",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns one row per column visible in the model, with the table name, column name, \
|
||||
minimum, maximum, cardinality and maximum string length. The statistics respect the \
|
||||
security roles of the connected user.",
|
||||
&["COLUMNSTATISTICS ()"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINS",
|
||||
FunctionCategory::Information,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("ColumnName", ParamKind::Column), required("Value", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when at least one row of the table has all the supplied column/value \
|
||||
pairs. Each pair is a column reference followed by the value to match, using strict \
|
||||
equality (BLANK does not match 0).",
|
||||
&["CONTAINS ( Product, Product[Color], \"Red\" )", "CONTAINS ( Sales, Sales[ProductKey], 1, Sales[Quantity], 2 )"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINSROW",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Value", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the table has a row whose values equal every supplied value, in \
|
||||
column order. The IN operator executes this function; comparisons are strict, so \
|
||||
BLANK does not match 0.",
|
||||
// The first argument is the row to test against, so both examples pair a one-column table
|
||||
// (a constructor, or a table expression) with exactly one scalar value.
|
||||
&["CONTAINSROW ( { \"Red\", \"Blue\" }, \"Red\" )", "CONTAINSROW ( VALUES ( Sales[ProductKey] ), 1 )"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINSSTRING",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
2,
|
||||
&[required("WithinText", ParamKind::Text), required("FindText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when WithinText contains FindText. The comparison is case-insensitive and \
|
||||
accent-sensitive; `?` and `*` are wildcards and `~?` / `~*` match them literally.",
|
||||
&["CONTAINSSTRING ( Product[Product Name], \"red\" )", "CONTAINSSTRING ( \"Hello\", \"ell\" )"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINSSTRINGEXACT",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
2,
|
||||
&[required("WithinText", ParamKind::Text), required("FindText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when WithinText contains FindText using a case-sensitive and \
|
||||
accent-sensitive comparison. Wildcards are not interpreted.",
|
||||
&["CONTAINSSTRINGEXACT ( Product[Product Name], \"Red\" )", "CONTAINSSTRINGEXACT ( \"Hello\", \"Hell\" )"],
|
||||
),
|
||||
spec(
|
||||
"CUSTOMDATA",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, true, false),
|
||||
"Returns the CustomData connection-string property supplied by the client, or an empty \
|
||||
string when the connection did not define it. It does not inspect the data model or the \
|
||||
filter context. GridCraft has no client connection string in a workbook, so the \
|
||||
evaluator always answers the empty string.",
|
||||
&["CUSTOMDATA ()"],
|
||||
),
|
||||
spec(
|
||||
"EVALUATEANDLOG",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
3,
|
||||
&[required("Value", ParamKind::Any), optional("Label", ParamKind::Text), optional("MaxRows", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Text]), overload(&[ParamKind::Any, ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns the first argument unchanged and writes its value to the DAX Evaluation Log \
|
||||
trace event. The optional Label annotates the event; MaxRows caps the rows captured for \
|
||||
a table expression and defaults to 10.",
|
||||
&["EVALUATEANDLOG ( 1 )", "EVALUATEANDLOG ( [Sales Amount] )", "EVALUATEANDLOG ( Sales, \"Sales rows\", 5 )"],
|
||||
),
|
||||
spec(
|
||||
"HASONEFILTER",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the column has exactly one distinct value resulting from direct \
|
||||
filters on that column. Unlike HASONEVALUE it ignores filters propagated from related \
|
||||
tables.",
|
||||
&["HASONEFILTER ( Product[Color] )", "HASONEFILTER ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"HASONEVALUE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the filter context leaves exactly one distinct value in the column, \
|
||||
regardless of whether the filter is direct or propagated through a relationship.",
|
||||
&["HASONEVALUE ( Product[Category] )", "HASONEVALUE ( Sales[Quantity] )"],
|
||||
),
|
||||
info!(
|
||||
"INFO.ALTERNATEOFDEFINITIONS",
|
||||
"Exposes the TMSCHEMA_ALTERNATE_OF_DEFINITIONS data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ANNOTATIONS",
|
||||
"One row per annotation in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ATTRIBUTEHIERARCHIES",
|
||||
"Exposes the TMSCHEMA_ATTRIBUTE_HIERARCHIES schema rowset as a table; optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ATTRIBUTEHIERARCHYSTORAGES",
|
||||
"Exposes the TMSCHEMA_ATTRIBUTE_HIERARCHY_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALCDEPENDENCY",
|
||||
"Reports which objects a DAX query depends on, so tools can inspect the dependency graph \
|
||||
without parsing formulas."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALCULATIONGROUPS",
|
||||
"Exposes the TMSCHEMA_CALCULATIONGROUPS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALCULATIONITEMS",
|
||||
"Exposes the TMSCHEMA_CALCULATIONITEMS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALENDARCOLUMNGROUPS",
|
||||
"Exposes the TMSCHEMA_CALENDAR_COLUMN_GROUPS schema rowset as a table; optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALENDARCOLUMNREFERENCES",
|
||||
"Exposes the TMSCHEMA_CALENDAR_COLUMN_REFERENCES schema rowset as a table; optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALENDARS",
|
||||
"Exposes the TMSCHEMA_CALENDARS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CATALOGS",
|
||||
"Exposes the DBSCHEMA_CATALOGS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CHANGEDPROPERTIES",
|
||||
"Exposes the TMSCHEMA_CHANGED_PROPERTIES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNPARTITIONSTORAGES",
|
||||
"Exposes the TMSCHEMA_COLUMN_PARTITION_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNPERMISSIONS",
|
||||
"One row per column permission in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNS",
|
||||
"One row per column in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNSTORAGES",
|
||||
"One row per column storage in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CSDLMETADATA",
|
||||
"Provides the model metadata serialized as CSDL XML text, so a tool can read the \
|
||||
conceptual schema without a client library."
|
||||
),
|
||||
info!(
|
||||
"INFO.CULTURES",
|
||||
"One row per culture in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DATACOVERAGEDEFINITIONS",
|
||||
"Exposes the TMSCHEMA_DATACOVERAGEDEFINITIONS data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DATASOURCES",
|
||||
"Exposes the TMSCHEMA_DATASOURCES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DELTATABLEMETADATASTORAGES",
|
||||
"Exposes the TMSCHEMA_DELTA_TABLE_METADATA_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DEPENDENCIES",
|
||||
"Returns the dependency records of a DAX query, describing what the query reads from the \
|
||||
model."
|
||||
),
|
||||
info!(
|
||||
"INFO.DETAILROWSDEFINITIONS",
|
||||
"One row per detail-rows definition in the model, with the columns of the matching \
|
||||
schema rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DICTIONARYSTORAGES",
|
||||
"Exposes the TMSCHEMA_DICTIONARY_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.EXCLUDEDARTIFACTS",
|
||||
"Exposes the TMSCHEMA_EXCLUDED_ARTIFACTS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.EXPRESSIONS",
|
||||
"One row per expression in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.EXTENDEDPROPERTIES",
|
||||
"One row per extended property in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.FORMATSTRINGDEFINITIONS",
|
||||
"Exposes the TMSCHEMA_FORMAT_STRING_DEFINITIONS data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.FUNCTIONS",
|
||||
"Lists the DAX functions the engine makes available, one row per function. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.GENERALSEGMENTMAPSEGMENTMETADATASTORAGES",
|
||||
"Exposes the TMSCHEMA_GENERAL_SEGMENT_MAP_SEGMENT_METADATA_STORAGES data management view \
|
||||
as a table; the optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.GROUPBYCOLUMNS",
|
||||
"Exposes the TMSCHEMA_GROUP_BY_COLUMNS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.HIERARCHIES",
|
||||
"Exposes the TMSCHEMA_HIERARCHIES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.HIERARCHYSTORAGES",
|
||||
"Exposes the TMSCHEMA_HIERARCHY_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.KPIS",
|
||||
"One row per KPI in the model, with the columns of the matching schema rowset. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.LEVELS",
|
||||
"One row per level in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.LINGUISTICMETADATA",
|
||||
"Exposes the TMSCHEMA_LINGUISTIC_METADATA schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.MEASURES",
|
||||
"One row per measure in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.MODEL",
|
||||
"Exposes the TMSCHEMA_MODEL schema rowset as a table; optional restriction name/value \
|
||||
pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.OBJECTTRANSLATIONS",
|
||||
"One row per object translation in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PARQUETFILESTORAGES",
|
||||
"Exposes the TMSCHEMA_PARQUET_FILE_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PARTITIONS",
|
||||
"Exposes the TMSCHEMA_PARTITIONS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PARTITIONSTORAGES",
|
||||
"One row per partition storage in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVECOLUMNS",
|
||||
"One row per perspective column in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVEHIERARCHIES",
|
||||
"One row per perspective hierarchy in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVEMEASURES",
|
||||
"One row per perspective measure in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVES",
|
||||
"One row per perspective in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVETABLES",
|
||||
"One row per perspective table in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PROPERTIES",
|
||||
"Exposes the DISCOVER_PROPERTIES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.QUERYGROUPS",
|
||||
"Exposes the TMSCHEMA_QUERY_GROUPS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.REFRESHPOLICIES",
|
||||
"Exposes the TMSCHEMA_REFRESH_POLICIES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATEDCOLUMNDETAILS",
|
||||
"Exposes the TMSCHEMA_RELATED_COLUMN_DETAILS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATIONSHIPINDEXSTORAGES",
|
||||
"Exposes the TMSCHEMA_RELATIONSHIP_INDEX_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATIONSHIPS",
|
||||
"Exposes the TMSCHEMA_RELATIONSHIPS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATIONSHIPSTORAGES",
|
||||
"Exposes the TMSCHEMA_RELATIONSHIP_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ROLEMEMBERSHIPS",
|
||||
"One row per role membership in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ROLES",
|
||||
"One row per role in the model, with the columns of the matching schema rowset. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.SEGMENTMAPSTORAGES",
|
||||
"One row per segment map storage in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.SEGMENTSTORAGES",
|
||||
"Exposes the TMSCHEMA_SEGMENT_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGEFILES",
|
||||
"One row per storage file in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGEFOLDERS",
|
||||
"One row per storage folder in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGETABLECOLUMNS",
|
||||
"Reports storage statistics for each column of the in-memory tables, so a tool can see \
|
||||
how the model is packed."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGETABLECOLUMNSEGMENTS",
|
||||
"Describes the column segments that hold data for the in-memory tables, one row per \
|
||||
segment."
|
||||
),
|
||||
info!(
|
||||
"INFO.TABLEPERMISSIONS",
|
||||
"One row per table permission in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.TABLES",
|
||||
"One row per table in the model, with the columns of the matching schema rowset. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.TABLESTORAGES",
|
||||
"One row per table storage in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.USERDEFINEDFUNCTIONS",
|
||||
"Exposes the TMSCHEMA_FUNCTIONS schema rowset as a table; optional restriction name/value \
|
||||
pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.VARIATIONS",
|
||||
"One row per variation in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.COLUMNS",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every column in the model, decoded so a query can use it without joins to \
|
||||
other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
|
||||
calculated columns and calculated tables.",
|
||||
&["INFO.VIEW.COLUMNS ()"],
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.MEASURES",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every measure in the model, decoded so a query can use it without joins to \
|
||||
other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
|
||||
calculated columns and calculated tables.",
|
||||
&["INFO.VIEW.MEASURES ()"],
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.RELATIONSHIPS",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every relationship in the model, decoded so a query can use it without joins \
|
||||
to other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
|
||||
calculated columns and calculated tables.",
|
||||
&["INFO.VIEW.RELATIONSHIPS ()"],
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.TABLES",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every table in the model, decoded so a query can use it without joins to other \
|
||||
DMV rowsets. Unlike the plain INFO functions it is allowed in measures, calculated \
|
||||
columns and calculated tables.",
|
||||
&["INFO.VIEW.TABLES ()"],
|
||||
),
|
||||
spec(
|
||||
"ISAFTER",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any), optional("Order", ParamKind::Logical)],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the Value1/Value2 groups compare strictly after the corresponding \
|
||||
values in the ascending/descending order given by each optional Order flag. The \
|
||||
comparison uses the existing evaluation context; ISAFTER is not an iterator.",
|
||||
&["ISAFTER ( Sales[Year], 2008 )", "ISAFTER ( Sales[Year], 2008, 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ISBLANK",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is BLANK. Zero and the empty string are not blank; the \
|
||||
predicate is equivalent to the strict comparison `value == BLANK ()`.",
|
||||
&["ISBLANK ( Sales[Amount] )", "ISBLANK ( BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"ISBOOLEAN",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a Boolean value. Alias of ISLOGICAL.",
|
||||
&["ISBOOLEAN ( TRUE )", "ISBOOLEAN ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISCROSSFILTERED",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("TableNameOrColumnName", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Reference])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the table or column is cross-filtered, meaning a filter is applied to \
|
||||
that table, to one of its columns, or to a column of a related table.",
|
||||
&["ISCROSSFILTERED ( Product )", "ISCROSSFILTERED ( Product[Category] )"],
|
||||
),
|
||||
spec(
|
||||
"ISDATETIME",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value has the Date/time type.",
|
||||
&["ISDATETIME ( DATE ( 2008, 1, 1 ) )", "ISDATETIME ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"ISDECIMAL",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a fixed-precision decimal (Currency) value. Alias of ISCURRENCY.",
|
||||
&["ISDECIMAL ( 1.5 )", "ISDECIMAL ( Sales[Net Price] )"],
|
||||
),
|
||||
spec(
|
||||
"ISDOUBLE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a floating-point decimal value.",
|
||||
&["ISDOUBLE ( 1.5 )", "ISDOUBLE ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISEMPTY",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Table", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the table expression has no rows in the current evaluation context, \
|
||||
including tables whose only row would be blank.",
|
||||
&["ISEMPTY ( Sales )", "ISEMPTY ( FILTER ( Sales, FALSE ) )"],
|
||||
),
|
||||
spec(
|
||||
"ISERROR",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when evaluating the value produces an error. It inspects the value, so the \
|
||||
error is caught rather than propagated.",
|
||||
&["ISERROR ( 1 / 0 )", "ISERROR ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISEVEN",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the number is even, FALSE when it is odd. Truncation applies to \
|
||||
non-integers, matching the mathematical sign of the truncated value.",
|
||||
&["ISEVEN ( 4 )", "ISEVEN ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISFILTERED",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE when the column carries direct filters in the current context; filters propagated \
|
||||
from a related table do not count, so use ISCROSSFILTERED for those.",
|
||||
&["ISFILTERED ( Product[Color] )", "ISFILTERED ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISINSCOPE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the column is the level currently in scope in a hierarchy of levels, \
|
||||
for example the group-by column of the current SUMMARIZECOLUMNS row.",
|
||||
&["ISINSCOPE ( Product[Category] )", "ISINSCOPE ( Product[Subcategory] )"],
|
||||
),
|
||||
spec(
|
||||
"ISINT64",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is a 64-bit integer. This is the alias of ISINTEGER.",
|
||||
&["ISINT64 ( 1 )", "ISINT64 ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISLOGICAL",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a logical value (TRUE or FALSE). Alias of ISBOOLEAN.",
|
||||
&["ISLOGICAL ( FALSE )", "ISLOGICAL ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISNONTEXT",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is not text. A blank cell is not text, so ISNONTEXT also \
|
||||
returns TRUE for BLANK.",
|
||||
&["ISNONTEXT ( 1 )", "ISNONTEXT ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"ISNUMBER",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is a number. Text that looks numeric is not a number; use \
|
||||
VALUE to convert it first.",
|
||||
&["ISNUMBER ( 1 )", "ISNUMBER ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISNUMERIC",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for an integer or decimal number, including Currency and floating-point values.",
|
||||
&["ISNUMERIC ( 1.5 )", "ISNUMERIC ( Sales[Net Price] )"],
|
||||
),
|
||||
spec(
|
||||
"ISODD",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the number is odd, FALSE when it is even. Non-integer values are \
|
||||
truncated before the parity test.",
|
||||
&["ISODD ( 3 )", "ISODD ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISONORAFTER",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any), optional("Order", ParamKind::Logical)],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the Value1/Value2 groups compare on or after the corresponding values \
|
||||
in the order given by each optional Order flag, emulating a START AT clause. It is not \
|
||||
an iterator.",
|
||||
&["ISONORAFTER ( Sales[Year], 2008 )", "ISONORAFTER ( Sales[Year], 2008, 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ISSELECTEDMEASURE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Measure", ParamKind::Reference)],
|
||||
&[variadic(&[ParamKind::Reference])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns TRUE when the measure currently evaluated in a calculation item is one of the \
|
||||
listed measures. A query measure redefined in the DAX query is not recognised.",
|
||||
&["ISSELECTEDMEASURE ( [Sales Amount] )", "ISSELECTEDMEASURE ( [Sales Amount], [Sales Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISSTRING",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is a string. This is the alias of ISTEXT; a blank value is \
|
||||
not text.",
|
||||
&["ISSTRING ( \"text\" )", "ISSTRING ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"ISSUBTOTAL",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, true, true, true),
|
||||
"Returns TRUE when the current SUMMARIZE row is the subtotal for the column, FALSE for a \
|
||||
detail row. It only makes sense inside SUMMARIZE with ROLLUP; SUMMARIZECOLUMNS with \
|
||||
ROLLUPADDISSUBTOTAL supersedes it.",
|
||||
&["ISSUBTOTAL ( Product[Brand] )", "ISSUBTOTAL ( Product[Category] )"],
|
||||
),
|
||||
spec(
|
||||
"ISTEXT",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is text. This is the alias of ISSTRING; a blank value is not \
|
||||
text.",
|
||||
&["ISTEXT ( \"text\" )", "ISTEXT ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"NAMEOF",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
3,
|
||||
&[required("Value", ParamKind::Reference), optional("Component", ParamKind::Text), optional("Escaped", ParamKind::Text)],
|
||||
&[
|
||||
overload(&[ParamKind::Reference]),
|
||||
overload(&[ParamKind::Reference, ParamKind::Text]),
|
||||
overload(&[ParamKind::Reference, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Text name of a table, column, measure or calendar. Component selects TABLE, COLUMN, \
|
||||
MEASURE, CALENDAR, FULL, SELF or PARENT; Escaped selects ESCAPED, UNESCAPED or \
|
||||
MINIMALLYESCAPED. Variables and dynamic expressions are not accepted.",
|
||||
&["NAMEOF ( Sales[Amount] )", "NAMEOF ( [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDMEASURE",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns a reference to the measure currently evaluated in a calculation item. During \
|
||||
application each call is replaced by the selected measure, which also triggers context \
|
||||
transition.",
|
||||
&["SELECTEDMEASURE ()"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDMEASUREFORMATSTRING",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Format string of the measure under evaluation in the current calculation item.",
|
||||
&["SELECTEDMEASUREFORMATSTRING ()"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDMEASURENAME",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Name of the measure under evaluation in the current calculation item, including one \
|
||||
redefined in the DAX query.",
|
||||
&["SELECTEDMEASURENAME ()"],
|
||||
),
|
||||
spec(
|
||||
"TABLEOF",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Reference", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Reference])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Resolves a column, measure or calendar reference to the table that owns it.",
|
||||
&["TABLEOF ( Sales[Amount] )", "TABLEOF ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"TEXTCONTAINS",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
3,
|
||||
&[required("WithinTextColumn", ParamKind::Column), required("SearchText", ParamKind::Text), optional("MatchMode", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Text]), overload(&[ParamKind::Column, ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"TRUE when the column text matches SearchText under full-text query semantics. MatchMode \
|
||||
is TEXTMATCHING (the default), FUZZYMATCHING or PHRASEMATCHING.",
|
||||
&["TEXTCONTAINS ( Product[Product Name], \"red\" )", "TEXTCONTAINS ( Product[Product Name], \"red\", \"FUZZYMATCHING\" )"],
|
||||
),
|
||||
spec(
|
||||
"TEXTSIMILARITY",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
3,
|
||||
&[required("WithinTextColumn", ParamKind::Column), required("SearchText", ParamKind::Text), optional("MatchMode", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Text]), overload(&[ParamKind::Column, ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Decimal,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns the BM25 relevance score of the text in the column against the search text; a \
|
||||
higher score is a stronger match and 0 means no match. MatchMode is TEXTMATCHING (the \
|
||||
default), FUZZYMATCHING or PHRASEMATCHING. Scores are comparable only within the same \
|
||||
search context.",
|
||||
&["TEXTSIMILARITY ( Product[Product Name], \"red\" )", "TEXTSIMILARITY ( Product[Product Name], \"red\", \"FUZZYMATCHING\" )"],
|
||||
),
|
||||
spec(
|
||||
"USERCULTURE",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, false, true),
|
||||
"Returns the culture code of the current user, such as \"en-US\", derived from the \
|
||||
operating system or browser settings.",
|
||||
&["USERCULTURE ()"],
|
||||
),
|
||||
spec(
|
||||
"USERNAME",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, true, false),
|
||||
"The connection identity in domain\\user form, as supplied when the connection was \
|
||||
opened.",
|
||||
&["USERNAME ()"],
|
||||
),
|
||||
spec(
|
||||
"USEROBJECTID",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, false, false),
|
||||
"Returns the current user's object ID from Azure AD, or the security identifier (SID) when \
|
||||
the model runs on-premises.",
|
||||
&["USEROBJECTID ()"],
|
||||
),
|
||||
spec(
|
||||
"USERPRINCIPALNAME",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, false, false),
|
||||
"Returns the user principal name of the current user, typically the email address in \
|
||||
user@domain form.",
|
||||
&["USERPRINCIPALNAME ()"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Logical functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category holds three kinds of functions:
|
||||
//!
|
||||
//! - Boolean combinators (`AND`, `OR`, `NOT`) and the constants `TRUE`/`FALSE`, all of which
|
||||
//! return a Boolean;
|
||||
//! - bitwise integer operations (`BITAND`, `BITOR`, `BITXOR`), which are engine-only: dax.guide
|
||||
//! does not list them for any Excel version;
|
||||
//! - scalar selectors (`IF`, `IF.EAGER`, `IFERROR`, `SWITCH`, `COALESCE`), which return a value
|
||||
//! whose type follows the selected branch and are therefore catalogued as
|
||||
//! [`ReturnType::Any`].
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Available to every host, with the usual DirectQuery restrictions.
|
||||
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// Engine-only functions: no Excel version listed by dax.guide supports them.
|
||||
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
/// Functions dax.guide flags as not recommended (`IFERROR`) or that are documented as an
|
||||
/// optimisation-only escape hatch (`IF.EAGER`).
|
||||
const DISCOURAGED: FunctionFlags = FunctionFlags::new(false, false, true, true, true);
|
||||
|
||||
/// `IF.EAGER` is engine-only and discouraged except for specific optimisations.
|
||||
const EAGER: FunctionFlags = FunctionFlags::new(false, false, true, false, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"AND",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Logical1", ParamKind::Logical), required("Logical2", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Logical])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns TRUE when both logical arguments are TRUE, and FALSE otherwise. The function \
|
||||
accepts exactly two arguments; use the `&&` operator to combine three or more conditions \
|
||||
without nesting. Like the operator, it does not short-circuit when evaluated eagerly.",
|
||||
&["AND ( Sales[Amount] > 0, Sales[Quantity] > 0 )", "AND ( TRUE, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"BITAND",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
ENGINE_ONLY,
|
||||
"Returns the bitwise AND of two integers. Both arguments are converted to integers; the \
|
||||
result is a signed 64-bit integer.",
|
||||
&["BITAND ( 5, 3 )", "BITAND ( 13, 25 )"],
|
||||
),
|
||||
spec(
|
||||
"BITOR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
ENGINE_ONLY,
|
||||
"Returns the bitwise OR of two integers. Both arguments are converted to integers; the \
|
||||
result is a signed 64-bit integer.",
|
||||
&["BITOR ( 5, 3 )", "BITOR ( 13, 25 )"],
|
||||
),
|
||||
spec(
|
||||
"BITXOR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
ENGINE_ONLY,
|
||||
"Returns the bitwise XOR of two integers. Both arguments are converted to integers; the \
|
||||
result is a signed 64-bit integer.",
|
||||
&["BITXOR ( 5, 3 )", "BITXOR ( 13, 25 )"],
|
||||
),
|
||||
spec(
|
||||
"COALESCE",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
ENGINE_ONLY,
|
||||
"The first argument whose value is not BLANK; when every argument is blank the result is \
|
||||
BLANK. At least two arguments are required, and later arguments are not evaluated once \
|
||||
a non-blank value is found. Unlike a chain of IF/ISBLANK checks, the result type follows \
|
||||
the first non-blank argument.",
|
||||
&[
|
||||
"COALESCE ( Sales[Discount], 0 )",
|
||||
"COALESCE ( Store[Area Manager], \"** Not Assigned **\" )",
|
||||
"COALESCE ( [Sales Amount], [Budget Amount], 0 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"FALSE",
|
||||
FunctionCategory::Logical,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns the logical value FALSE. `FALSE` without parentheses is the same constant; FALSE \
|
||||
is converted to 0 when a numeric result is required.",
|
||||
&["FALSE ()", "IF ( Sales[Amount] > 0, TRUE (), FALSE () )"],
|
||||
),
|
||||
spec(
|
||||
"IF",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
3,
|
||||
&[required("LogicalTest", ParamKind::Logical), required("ResultIfTrue", ParamKind::Any), optional("ResultIfFalse", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Any]), overload(&[ParamKind::Logical, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
STANDARD,
|
||||
"Evaluates the logical test and returns `ResultIfTrue` when it is TRUE and \
|
||||
`ResultIfFalse` otherwise. When the third argument is omitted a FALSE test returns \
|
||||
BLANK. Only the selected branch is evaluated in the regular (strict) execution plan, and \
|
||||
the result type follows the selected branch or the common type of both branches.",
|
||||
&["IF ( Sales[Amount] > 0, 1, 0 )", "IF ( [Sales Amount] > 1000, \"Large\", \"Small\" )", "IF ( Sales[Quantity] > 0, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"IF.EAGER",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
3,
|
||||
&[required("LogicalTest", ParamKind::Logical), required("ResultIfTrue", ParamKind::Any), optional("ResultIfFalse", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Any]), overload(&[ParamKind::Logical, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EAGER,
|
||||
"Same conditional semantics as IF, but forces an eager execution plan in which both \
|
||||
branch expressions are evaluated before the test chooses one. It exists only for query \
|
||||
optimisation and should be used only after measuring a clear advantage over IF; the \
|
||||
result type is Variant when the branches differ.",
|
||||
&["IF.EAGER ( Sales[Amount] > 0, 1, 0 )", "IF.EAGER ( [Sales Amount] > 1000, \"Large\", \"Small\" )"],
|
||||
),
|
||||
spec(
|
||||
"IFERROR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Value", ParamKind::Any), required("ValueIfError", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
DISCOURAGED,
|
||||
"Yields `ValueIfError` when the first argument raises an error, and otherwise repeats the \
|
||||
first argument's value; faster than the equivalent \
|
||||
`IF ( ISERROR ( Value ), ValueIfError, Value )`. Neither IFERROR nor ISERROR catches \
|
||||
every runtime error, because block-mode execution can bypass the check, so both are \
|
||||
discouraged.",
|
||||
&["IFERROR ( 1 / 0, 0 )", "IFERROR ( VALUE ( Sales[Text] ), BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"NOT",
|
||||
FunctionCategory::Logical,
|
||||
1,
|
||||
1,
|
||||
&[required("Logical", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Logical])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns the opposite Boolean value: TRUE for a FALSE argument and FALSE for a TRUE \
|
||||
argument. NOT is an operator exposed through function syntax.",
|
||||
&["NOT ( Sales[Amount] > 0 )", "NOT ( TRUE )"],
|
||||
),
|
||||
spec(
|
||||
"OR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Logical1", ParamKind::Logical), required("Logical2", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Logical])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns TRUE when either logical argument is TRUE, and FALSE when both are FALSE. The \
|
||||
function accepts exactly two arguments; use the `||` operator to combine three or more \
|
||||
conditions without nesting.",
|
||||
&["OR ( Sales[Amount] > 0, Sales[Quantity] > 0 )", "OR ( TRUE, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"SWITCH",
|
||||
FunctionCategory::Logical,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Expression", ParamKind::Any),
|
||||
required("Value", ParamKind::Any),
|
||||
required("Result", ParamKind::Any),
|
||||
optional("Else", ParamKind::Any),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
STANDARD,
|
||||
"Compares the expression with each value in turn and returns the result paired with the \
|
||||
first match; when nothing matches it returns the optional else argument, or BLANK when \
|
||||
that argument is omitted. Values and results come in pairs, so the call needs an odd \
|
||||
number of arguments when there is no else and an even number when there is one. All \
|
||||
results and the else value must have the same data type. Using TRUE as the expression \
|
||||
turns SWITCH into a cleaner alternative to cascading IF calls.",
|
||||
&[
|
||||
"SWITCH ( [X], 1, \"a\", 2, \"b\", \"other\" )",
|
||||
"SWITCH ( Sales[Region], \"North\", 1, \"South\", 2, 0 )",
|
||||
"SWITCH ( TRUE (), Sales[Amount] > 1000, \"Large\", Sales[Amount] > 100, \"Medium\", \"Small\" )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"TRUE",
|
||||
FunctionCategory::Logical,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns the logical value TRUE. `TRUE` without parentheses is the same constant; TRUE is \
|
||||
converted to 1 when a numeric result is required.",
|
||||
&["TRUE ()", "IF ( Sales[Amount] > 0, TRUE (), FALSE () )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,677 @@
|
||||
//! Math and trigonometry functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"ABS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Numeric,
|
||||
standard(false),
|
||||
"Absolute value of Number with the sign stripped and the numeric type kept (Currency, \
|
||||
Decimal or Integer). Infinite values are accepted and nothing is rounded.",
|
||||
&["ABS ( -1 )", "ABS ( [Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ACOS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the arccosine of a number in radians, in the range 0 to pi. The argument is the \
|
||||
cosine of the angle and must be between -1 and 1; multiply the result by 180/PI() or \
|
||||
use DEGREES to obtain degrees. Results are approximate Decimal values.",
|
||||
&["ACOS ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ACOSH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the inverse hyperbolic cosine, in radians, of a number greater than or equal to \
|
||||
1. ACOSH(COSH(x)) equals x when x is in range; the result is an approximate Decimal \
|
||||
value.",
|
||||
&["ACOSH ( 2 )"],
|
||||
),
|
||||
spec(
|
||||
"ACOT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Principal arccotangent of a real number, in radians between 0 and pi, as an approximate \
|
||||
Decimal.",
|
||||
&["ACOT ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ACOTH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse hyperbolic cotangent of a number whose absolute value exceeds 1, as an \
|
||||
approximate Decimal.",
|
||||
&["ACOTH ( 2 )"],
|
||||
),
|
||||
spec(
|
||||
"ASIN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the arcsine of a number, in radians, between -pi/2 and pi/2. The argument is \
|
||||
the sine of the angle and must be between -1 and 1; multiply by 180/PI() or use DEGREES \
|
||||
for degrees. Results are approximate Decimal values.",
|
||||
&["ASIN ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ASINH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the inverse hyperbolic sine of any real number, in radians. ASINH(SINH(x)) \
|
||||
equals x; the result is an approximate Decimal value.",
|
||||
&["ASINH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ATAN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the arctangent of a number, in radians, between -pi/2 and pi/2. Multiply by \
|
||||
180/PI() or use DEGREES for degrees; the result is an approximate Decimal value.",
|
||||
&["ATAN ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ATANH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse hyperbolic tangent of a value strictly between -1 and 1, as an approximate \
|
||||
Decimal. The endpoints -1 and 1, and anything outside that range, are errors.",
|
||||
&["ATANH ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"CEILING",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Significance", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Numeric,
|
||||
standard(false),
|
||||
"Moves Number up to the closest multiple of Significance. Unlike ISO.CEILING, a \
|
||||
negative significance makes CEILING round negative numbers toward negative infinity. \
|
||||
The result usually follows the type of Significance, but a Currency Number stays \
|
||||
Currency, a Boolean Significance yields Integer and a non-numeric Significance yields \
|
||||
Decimal.",
|
||||
&["CEILING ( 10.2, 1 )", "CEILING ( 10.7, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"CONVERT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Expression", ParamKind::Any), required("DataType", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
standard(false),
|
||||
"Converts an expression to the requested data type. The type is an unquoted keyword: \
|
||||
BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64 or STRING/TEXT. \
|
||||
Numeric conversions follow the target type's precision, so CURRENCY/DECIMAL rounds to \
|
||||
four decimal places while DOUBLE keeps approximately 15 significant digits.",
|
||||
&["CONVERT ( \"123\", INTEGER )", "CONVERT ( 12345, DATETIME )"],
|
||||
),
|
||||
spec(
|
||||
"COS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the cosine of an angle given in radians. Convert degrees with RADIANS or by \
|
||||
multiplying by PI()/180; the result is an approximate Decimal value.",
|
||||
&["COS ( PI () / 3 )"],
|
||||
),
|
||||
spec(
|
||||
"COSH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic cosine of a real argument, as an approximate Decimal; it grows quickly as \
|
||||
the argument rises.",
|
||||
&["COSH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"COT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the cotangent of an angle given in radians, computed as 1/TAN(angle). It is \
|
||||
undefined at multiples of pi; the result is an approximate Decimal value.",
|
||||
&["COT ( PI () / 4 )"],
|
||||
),
|
||||
spec(
|
||||
"COTH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic cotangent of a hyperbolic angle in radians, computed as 1/TANH(angle); \
|
||||
undefined at zero and returned as an approximate Decimal.",
|
||||
&["COTH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"CURRENCY",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Scalar)],
|
||||
&[overload(&[ParamKind::Scalar])],
|
||||
ReturnType::Currency,
|
||||
standard(false),
|
||||
"Converts a scalar expression to the Currency type, which stores four decimal places. \
|
||||
The fifth significant decimal is rounded up when it is 5 or larger; TRUE becomes 1 and \
|
||||
FALSE becomes 0, and numeric text is parsed. Currency values are fixed-point, so this \
|
||||
conversion is not a general-purpose numeric cast.",
|
||||
&["CURRENCY ( 10.5 )", "CURRENCY ( \"3.66666\" )"],
|
||||
),
|
||||
spec(
|
||||
"DEGREES",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Converts an angle from radians to degrees by multiplying by 180/pi. The result is an \
|
||||
approximate Decimal value; RADIANS performs the inverse conversion.",
|
||||
&["DEGREES ( PI () / 2 )"],
|
||||
),
|
||||
spec(
|
||||
"DIVIDE",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
3,
|
||||
&[required("Numerator", ParamKind::Number), required("Denominator", ParamKind::Number), optional("AlternateResult", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Any])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Performs safe division and returns an alternate result when the denominator is zero, \
|
||||
avoiding the error or infinity produced by the / operator. The alternate result must be \
|
||||
a constant and defaults to BLANK; the quotient is an approximate Decimal value. DIVIDE \
|
||||
runs in the formula engine and is slower than native division when the denominator is \
|
||||
known to be non-zero.",
|
||||
&["DIVIDE ( 10, 2 )", "DIVIDE ( 10, 0, 0 )"],
|
||||
),
|
||||
spec(
|
||||
"EVEN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Rounds a number away from zero to the nearest even integer. An even integer is returned \
|
||||
unchanged, and non-numeric input raises an error. The result is an exact Integer.",
|
||||
&["EVEN ( 3.2 )", "EVEN ( -3.2 )"],
|
||||
),
|
||||
spec(
|
||||
"EXP",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns e raised to the given power, the inverse of LN. The result is an approximate \
|
||||
Decimal value with about 15 significant digits; for other bases use POWER or ^.",
|
||||
&["EXP ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"FACT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the factorial of a non-negative number in Decimal form. A non-integer argument \
|
||||
is truncated, and values above 170 overflow; the result is exact only through 21!. \
|
||||
Calculated columns and RLS rules cannot use FACT in DirectQuery mode.",
|
||||
&["FACT ( 5 )", "FACT ( 21 )"],
|
||||
),
|
||||
spec(
|
||||
"FLOOR",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Significance", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Moves Number toward zero to the closest multiple of Significance; both must share a \
|
||||
sign. The result is always Decimal regardless of the argument types.",
|
||||
&["FLOOR ( 2.7, 1 )", "FLOOR ( -2.7, -1 )"],
|
||||
),
|
||||
spec(
|
||||
"GCD",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Greatest common divisor of two integers. Non-integer arguments are truncated before the \
|
||||
calculation; the result is an exact Integer.",
|
||||
&["GCD ( 36, 48 )"],
|
||||
),
|
||||
spec(
|
||||
"INT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Any,
|
||||
standard(false),
|
||||
"Rounds a number down toward negative infinity to an integer, so INT(-2.1) is -3. The \
|
||||
result is Integer for Integer or Decimal input and Currency for Currency input; unlike \
|
||||
TRUNC, the result type follows the argument and negative values move away from zero.",
|
||||
&["INT ( -2.9 )", "INT ( 2.9 )"],
|
||||
),
|
||||
spec(
|
||||
"ISO.CEILING",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), optional("Significance", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Numeric,
|
||||
standard(false),
|
||||
"Moves Number up to the closest multiple of Significance using ISO rules. When \
|
||||
Significance is omitted it defaults to 1; negative numbers and negative significance \
|
||||
can round differently from CEILING. The result keeps the numeric type of Number, with \
|
||||
Decimal precision when required by the multiple.",
|
||||
&["ISO.CEILING ( 10.2 )", "ISO.CEILING ( 10.7, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"LCM",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Least common multiple of two integers: the smallest positive value that both arguments \
|
||||
divide without a remainder. Non-integer arguments are truncated; the result is an exact \
|
||||
Integer.",
|
||||
&["LCM ( 4, 6 )"],
|
||||
),
|
||||
spec(
|
||||
"LN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the natural logarithm (base e) of a positive number. Zero and negative numbers \
|
||||
produce an error; the result is an approximate Decimal value and is the inverse of EXP.",
|
||||
&["LN ( 10 )"],
|
||||
),
|
||||
spec(
|
||||
"LOG",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), optional("Base", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the logarithm of a positive number in the given base; omitting the base uses \
|
||||
10. The result is an approximate Decimal value, and LOG10 is the fixed base-10 \
|
||||
shortcut.",
|
||||
&["LOG ( 1000 )", "LOG ( 8, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"LOG10",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Base-10 logarithm of a positive number, as an approximate Decimal; the same value as \
|
||||
LOG(number, 10).",
|
||||
&["LOG10 ( 10000 )"],
|
||||
),
|
||||
spec(
|
||||
"MOD",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Divisor", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Any,
|
||||
standard(false),
|
||||
"Returns the remainder after dividing Number by Divisor. The result follows the operand \
|
||||
type (Integer, Currency or Decimal) and its sign follows the divisor; a zero divisor \
|
||||
produces an error. QUOTIENT returns the corresponding integer portion.",
|
||||
&["MOD ( 7, 3 )", "MOD ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"MROUND",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Multiple", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Rounds a number to the nearest multiple, rounding away from zero when the remainder is \
|
||||
at least half the multiple. Number and Multiple must have the same sign; for decimal \
|
||||
multiples the midpoint direction is undefined, so MROUND(6.05, 0.1) can differ from \
|
||||
MROUND(7.05, 0.1). The result is Decimal.",
|
||||
&["MROUND ( 7.3, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ODD",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Rounds a number away from zero to the nearest odd integer. An odd integer is returned \
|
||||
unchanged, and non-numeric input raises an error. The result is an exact Integer.",
|
||||
&["ODD ( 2.1 )", "ODD ( -2.1 )"],
|
||||
),
|
||||
spec(
|
||||
"PI",
|
||||
FunctionCategory::MathAndTrig,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"The constant pi (3.14159265358979) as an approximate Decimal, accurate to 15 digits. \
|
||||
Takes no arguments.",
|
||||
&["PI ()"],
|
||||
),
|
||||
spec(
|
||||
"POWER",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Power", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns Number raised to Power. It is equivalent to the ^ operator and produces an \
|
||||
approximate Decimal value; fractional powers of negative bases produce an error.",
|
||||
&["POWER ( 2, 10 )", "POWER ( 9, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"QUOTIENT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Numerator", ParamKind::Number), required("Denominator", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Whole-number part of dividing Numerator by Denominator, with the fraction cut toward \
|
||||
zero. The result is an exact Integer and a zero denominator is an error; MOD gives the \
|
||||
remainder.",
|
||||
&["QUOTIENT ( 7, 2 )", "QUOTIENT ( -7, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"RADIANS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Converts an angle from degrees to radians by multiplying by pi/180. The result is an \
|
||||
approximate Decimal value; DEGREES performs the inverse conversion.",
|
||||
&["RADIANS ( 180 )"],
|
||||
),
|
||||
spec(
|
||||
"RAND",
|
||||
FunctionCategory::MathAndTrig,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Decimal,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"Returns a random Decimal value in [0, 1), uniformly distributed. RAND is volatile: it \
|
||||
may return a different value on every evaluation and changes on recalculation, so it \
|
||||
cannot be used where a stable result is required.",
|
||||
&["RAND ()"],
|
||||
),
|
||||
spec(
|
||||
"RANDBETWEEN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Bottom", ParamKind::Number), required("Top", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"Returns a random Integer between Bottom and Top inclusive. Both bounds are integers; \
|
||||
if Bottom is greater than Top the function raises an error. RANDBETWEEN is volatile, so \
|
||||
it recalculates to a different value and is unsuitable for stable results.",
|
||||
&["RANDBETWEEN ( 5, 50 )"],
|
||||
),
|
||||
spec(
|
||||
"ROUND",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Rounds a number to the specified number of digits, using half away from zero. A positive \
|
||||
count rounds right of the decimal point, zero rounds to an integer and a negative count \
|
||||
rounds left of it. The result is a Decimal, so large integers can lose precision beyond \
|
||||
about 15 significant digits.",
|
||||
&["ROUND ( 3.14159, 2 )", "ROUND ( 1234, -2 )"],
|
||||
),
|
||||
spec(
|
||||
"ROUNDDOWN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Moves Number toward zero to the requested digit. Positive counts work right of the \
|
||||
decimal point, zero rounds to an integer and negative counts work left of it; the \
|
||||
result is Decimal and differs from FLOOR for negative numbers.",
|
||||
&["ROUNDDOWN ( 2.71828, 3 )", "ROUNDDOWN ( -3.14159, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"ROUNDUP",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Moves Number away from zero to the requested digit, so 2.31 at one digit becomes 2.4. \
|
||||
Positive counts work right of the decimal point, zero rounds to an integer and negative \
|
||||
counts work left of it; the result is Decimal.",
|
||||
&["ROUNDUP ( 3.14159, 2 )", "ROUNDUP ( -3.14159, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"SIGN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Returns the sign of a real number: 1 when positive, 0 when zero and -1 when negative. \
|
||||
The result is an exact Integer; infinite values are not supported.",
|
||||
&["SIGN ( -5 )", "SIGN ( 0 )"],
|
||||
),
|
||||
spec(
|
||||
"SIN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the sine of an angle given in radians. Convert degrees with RADIANS or by \
|
||||
multiplying by PI()/180; the result is an approximate Decimal value.",
|
||||
&["SIN ( PI () / 6 )"],
|
||||
),
|
||||
spec(
|
||||
"SINH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic sine of a real argument, as an approximate Decimal; ASINH is its inverse.",
|
||||
&["SINH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"SQRT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Square root of a non-negative number, as an approximate Decimal; a negative argument is \
|
||||
an error. SQRTPI multiplies by pi before taking the root.",
|
||||
&["SQRT ( 16 )"],
|
||||
),
|
||||
spec(
|
||||
"SQRTPI",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Square root of Number multiplied by pi, as an approximate Decimal; negative input is an \
|
||||
error, and SQRTPI(n) equals SQRT(n * PI()).",
|
||||
&["SQRTPI ( 3 )"],
|
||||
),
|
||||
spec(
|
||||
"TAN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the tangent of an angle given in radians. Convert degrees with RADIANS or by \
|
||||
multiplying by PI()/180; the result is an approximate Decimal value and is undefined at \
|
||||
odd multiples of pi/2.",
|
||||
&["TAN ( PI () / 4 )"],
|
||||
),
|
||||
spec(
|
||||
"TANH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic tangent of a real argument, computed as SINH(number)/COSH(number); the value \
|
||||
lies between -1 and 1.",
|
||||
&["TANH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"TRUNC",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), optional("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Truncates a number toward zero by removing its fractional part or the digits beyond the \
|
||||
requested precision. NumberOfDigits defaults to 0, positive counts keep decimal places \
|
||||
and negative counts truncate left of the decimal point. The result is always Decimal, \
|
||||
unlike INT, which rounds toward negative infinity and follows the input type.",
|
||||
&["TRUNC ( 3.14159 )", "TRUNC ( 3.14159, 2 )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Other functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category collects the bit-shift operators, the row-context helpers, the window ranking
|
||||
//! functions, the metadata table function and the remaining special functions that dax.guide
|
||||
//! lists under "Other". `INFO.STORAGETABLES` keeps the exact dotted spelling and shares the
|
||||
//! optional restriction-pair syntax of the other `INFO.*` functions.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"BITLSHIFT",
|
||||
FunctionCategory::Other,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("ShiftAmount", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Shifts the first argument's integer left by ShiftAmount bits; a negative amount shifts \
|
||||
right. Two's-complement semantics, so the result can overflow or underflow.",
|
||||
&["BITLSHIFT ( 4, 2 )", "BITLSHIFT ( Sales[Quantity], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"BITRSHIFT",
|
||||
FunctionCategory::Other,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("ShiftAmount", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Shifts the first argument's integer right by ShiftAmount bits; a negative amount shifts \
|
||||
left. Two's-complement semantics, so the result can overflow or underflow.",
|
||||
&["BITRSHIFT ( 8, 2 )", "BITRSHIFT ( Sales[Quantity], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"BLANK",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Blank,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the BLANK value. BLANK has no data type and is converted automatically when \
|
||||
compared with other values; use the `==` operator or ISBLANK to test for it.",
|
||||
&["BLANK ()"],
|
||||
),
|
||||
spec(
|
||||
"EARLIER",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), optional("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Column, ParamKind::Number])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, true, true, true),
|
||||
"Returns the value of a column in an outer row context, `Number` evaluation passes back \
|
||||
(default 1). Fails when no outer row context exists. dax.guide marks it not recommended: \
|
||||
a variable captured before the inner row context is easier to read and maintain.",
|
||||
&["EARLIER ( Customer[Yearly Income] )", "EARLIER ( Customer[Yearly Income], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"EARLIEST",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, true, true, true),
|
||||
"Returns the value of a column in the outermost row context, equivalent to EARLIER with \
|
||||
the largest possible scan count. dax.guide marks it not recommended in favour of storing \
|
||||
the value in a variable.",
|
||||
&["EARLIEST ( Customer[Yearly Income] )"],
|
||||
),
|
||||
spec(
|
||||
"ERROR",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("ErrorText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Variant,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Stops evaluation and raises a user-specified error with the supplied message. It can be \
|
||||
used anywhere a scalar is expected, but has no data type of its own, so wrap it in \
|
||||
CONVERT to give the surrounding expression a concrete type.",
|
||||
&["ERROR ( \"Missing inflation rate\" )"],
|
||||
),
|
||||
spec(
|
||||
"EXTERNALMEASURE",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
3,
|
||||
&[required("MeasureName", ParamKind::Text), optional("Type", ParamKind::Text), optional("Datasource", ParamKind::Text)],
|
||||
&[
|
||||
overload(&[ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Invokes a measure defined in a remote model. The optional type name \
|
||||
(BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64, STRING/TEXT, \
|
||||
VARIANT) declares the remote result type and the optional data source names the \
|
||||
external model. Power BI generates these calls for composite models.",
|
||||
&["EXTERNALMEASURE ( \"Remote Sales\", \"DOUBLE\", \"RemoteModel\" )"],
|
||||
),
|
||||
spec(
|
||||
"HASH",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Expression", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Any])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Fingerprints a variable number of input expressions with a hash and returns an integer. \
|
||||
The function appears in the engine metadata but is not documented by Microsoft, so its \
|
||||
exact hash algorithm and stability across versions are unspecified.",
|
||||
&["HASH ( Sales[Amount] )", "HASH ( Sales[OrderNumber], Sales[LineNumber] )"],
|
||||
),
|
||||
spec(
|
||||
"INFO.STORAGETABLES",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("RestrictionName", ParamKind::Text), optional("RestrictionValue", ParamKind::Any)],
|
||||
&[overload(&[]), overload(&[ParamKind::Text]), variadic(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns statistics about the in-memory storage tables of the model, with one row per \
|
||||
table and columns such as DATABASE_NAME, TABLE_ID, TABLE_PARTITIONS_COUNT and \
|
||||
ROWS_COUNT. It corresponds to the DISCOVER_STORAGE_TABLES dynamic management view, \
|
||||
accepts optional restriction name/value pairs, and, like every INFO function, cannot be \
|
||||
used in calculated tables or calculated columns.",
|
||||
&["INFO.STORAGETABLES ()", "INFO.STORAGETABLES ( \"DATABASE_NAME\", \"Sales\" )"],
|
||||
),
|
||||
spec(
|
||||
"ISATLEVEL",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("Column", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"TRUE when the given column appears at the current level of the visual calculation data \
|
||||
grid. Use it to apply different formatting or logic per hierarchy level.",
|
||||
&["ISATLEVEL ( 'Date'[Year] )", "ISATLEVEL ( Product[Category] )"],
|
||||
),
|
||||
spec(
|
||||
"ISCURRENCY",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"TRUE for a fixed-precision decimal (Currency) value. Alias of ISDECIMAL.",
|
||||
&["ISCURRENCY ( Sales[Amount] )", "ISCURRENCY ( 1.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ISINTEGER",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"TRUE for an integer Value. Alias of ISINT64.",
|
||||
&["ISINTEGER ( Sales[Quantity] )", "ISINTEGER ( 2.5 )"],
|
||||
),
|
||||
spec(
|
||||
"KEYWORDMATCH",
|
||||
FunctionCategory::Other,
|
||||
2,
|
||||
2,
|
||||
&[required("MatchExpression", ParamKind::Text), required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, false),
|
||||
"Returns TRUE when the match expression matches the supplied text. dax.guide lists it as \
|
||||
deprecated: it was never released and only appeared in some Excel versions.",
|
||||
&["KEYWORDMATCH ( \"bike\", \"Mountain Bike\" )"],
|
||||
),
|
||||
spec(
|
||||
"RANK",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
7,
|
||||
&[
|
||||
optional("Ties", ParamKind::Text),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Text),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[]),
|
||||
overload(&[ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the rank of the current row inside its partition, ordered by an ORDERBY clause. \
|
||||
The optional Ties argument selects DENSE or SKIP (SKIP is the default), Blanks controls \
|
||||
where blank ordering values sort, PARTITIONBY splits the table, MATCHBY identifies the \
|
||||
current row and Reset restarts the numbering. Relation defaults to ALLSELECTED of the \
|
||||
ordering and partitioning columns, and either Relation or ORDERBY must be supplied.",
|
||||
&["RANK ( DENSE, Sales, ORDERBY ( Sales[Amount] ) )", "RANK ( SKIP, Sales, ORDERBY ( Sales[Amount], DESC ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROWNUMBER",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
6,
|
||||
&[
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Text),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[]),
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the unique row number of the current row inside its partition, ordered by an \
|
||||
ORDERBY clause. Unlike RANK, ties receive different numbers. The optional Blanks, \
|
||||
PARTITIONBY, MATCHBY and Reset arguments behave as they do for RANK; either Relation or \
|
||||
ORDERBY must be supplied.",
|
||||
&["ROWNUMBER ( Sales, ORDERBY ( Sales[Amount] ) )", "ROWNUMBER ( Sales, ORDERBY ( Sales[OrderDate] ), LAST )"],
|
||||
),
|
||||
spec(
|
||||
"SAMPLECARTESIANPOINTSBYCOVER",
|
||||
FunctionCategory::Other,
|
||||
4,
|
||||
7,
|
||||
&[
|
||||
required("Size", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("XAxis", ParamKind::Column),
|
||||
required("YAxis", ParamKind::Column),
|
||||
optional("Radius", ParamKind::Column),
|
||||
optional("MaxMinRatio", ParamKind::Number),
|
||||
optional("MaxBlankRatio", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column, ParamKind::Column]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column, ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Table,
|
||||
ParamKind::Column,
|
||||
ParamKind::Column,
|
||||
ParamKind::Column,
|
||||
ParamKind::Number,
|
||||
ParamKind::Number,
|
||||
]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns a sample of at most `Size` rows from a table, chosen by plotting each row as a \
|
||||
point on the X and Y coordinates and then dropping overlapping points. The optional \
|
||||
Radius column controls point size, MaxMinRatio limits the ratio between the largest and \
|
||||
smallest drawn points, and MaxBlankRatio limits the ratio between the largest point and \
|
||||
those with a blank radius. The function is used by the engine's scatter chart sampling \
|
||||
and is not documented by Microsoft.",
|
||||
&[
|
||||
"SAMPLECARTESIANPOINTSBYCOVER ( 1000, Sales, Sales[Longitude], Sales[Latitude] )",
|
||||
"SAMPLECARTESIANPOINTSBYCOVER ( 1000, Sales, Sales[X], Sales[Y], Sales[Radius], 4, 0.1 )",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Parent-child functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! These five functions flatten a parent-child hierarchy into a delimited path. The delimiter
|
||||
//! is always the vertical bar (`|`); `PATH` produces the string, `PATHLENGTH` counts its items,
|
||||
//! `PATHCONTAINS` searches it, and `PATHITEM`/`PATHITEMREVERSE` extract one item from the left
|
||||
//! or the right end.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
|
||||
|
||||
const FLAGS: FunctionFlags = standard(false);
|
||||
|
||||
/// dax.guide lists the parent-child functions in this order: PATH, PATHCONTAINS, PATHITEM,
|
||||
/// PATHITEMREVERSE and PATHLENGTH.
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"PATH",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
2,
|
||||
&[required("ID_ColumnName", ParamKind::Column), required("Parent_ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Column])],
|
||||
ReturnType::String,
|
||||
FLAGS,
|
||||
"Returns a text string containing the delimited list of IDs that starts at the top of a \
|
||||
parent-child hierarchy and ends with the current row, separating the identifiers with \
|
||||
the vertical bar. Both arguments must be column references, not expressions, and must \
|
||||
share a data type (integer or text); the parent value must exist in the ID column. A \
|
||||
blank parent returns just the ID, a blank ID returns BLANK, and an ID that contains a \
|
||||
vertical bar returns an error. Duplicate IDs with different parents return an error; \
|
||||
with the same parent the common parent is returned.",
|
||||
&["PATH ( Account[AccountKey], Account[ParentAccountKey] )", "PATH ( Employee[EmployeeKey], Employee[ParentEmployeeKey] )"],
|
||||
),
|
||||
spec(
|
||||
"PATHCONTAINS",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
2,
|
||||
&[required("Path", ParamKind::Text), required("Item", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FLAGS,
|
||||
"Returns TRUE when the item appears as a whole segment of the delimited path, and FALSE \
|
||||
otherwise. The path is normally the result of PATH. An integer item is converted to \
|
||||
text before the comparison; when that conversion fails the function returns an error.",
|
||||
&["PATHCONTAINS ( Account[AccountPath], 2 )", "PATHCONTAINS ( Account[AccountPath], \"24\" )", "PATHCONTAINS ( \"1|24|2\", 2 )"],
|
||||
),
|
||||
spec(
|
||||
"PATHITEM",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
3,
|
||||
&[required("Path", ParamKind::Text), required("Position", ParamKind::Number), optional("Type", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number]), overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FLAGS,
|
||||
"Returns the item at the given position in the delimited path, counting from the left \
|
||||
end where 1 is the top of the hierarchy. A position below 1 or beyond the number of \
|
||||
items returns BLANK. The optional Type selects the result: TEXT (or 0), the default, \
|
||||
returns a string, while INTEGER (or 1) converts the item to an integer. The result \
|
||||
type therefore follows the Type argument. An invalid Type enumeration raises an error.",
|
||||
&[
|
||||
"PATHITEM ( Account[AccountPath], 1 )",
|
||||
"PATHITEM ( Account[AccountPath], 2, INTEGER )",
|
||||
"PATHITEM ( Account[AccountPath], 3, TEXT )",
|
||||
"PATHITEM ( \"123|456|789|764\", 2 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"PATHITEMREVERSE",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
3,
|
||||
&[required("Path", ParamKind::Text), required("Position", ParamKind::Number), optional("Type", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number]), overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FLAGS,
|
||||
"Returns the item at the given position in the delimited path, counting backwards from \
|
||||
the last item, so position 1 is the current item and position 2 is its immediate \
|
||||
parent. A position below 1 or beyond the number of items returns BLANK. The optional \
|
||||
Type selects the result: TEXT (or 0), the default, returns a string, while INTEGER (or \
|
||||
1) converts the item to an integer, so the result type follows the Type argument. An \
|
||||
invalid Type enumeration raises an error.",
|
||||
&[
|
||||
"PATHITEMREVERSE ( Account[AccountPath], 1 )",
|
||||
"PATHITEMREVERSE ( Account[AccountPath], 2, INTEGER )",
|
||||
"PATHITEMREVERSE ( Account[AccountPath], 3, TEXT )",
|
||||
"PATHITEMREVERSE ( \"123|456|789|764\", 2 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"PATHLENGTH",
|
||||
FunctionCategory::ParentChild,
|
||||
1,
|
||||
1,
|
||||
&[required("Path", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Integer,
|
||||
FLAGS,
|
||||
"Counts the items in a delimited path, the current item included, so a root node's path \
|
||||
has length 1. The path is normally the result of PATH, but any text with vertical-bar \
|
||||
separators (including a literal such as \"123|456|789|764\") is accepted.",
|
||||
&["PATHLENGTH ( Account[AccountPath] )", "PATHLENGTH ( \"123|456|789|764\" )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Relationship management functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The four functions mirror <https://dax.guide/functions/relationships-management/> in index
|
||||
//! order. `CROSSFILTER` and `USERELATIONSHIP` are filter modifiers: they return no value and
|
||||
//! only alter filter propagation while the filter context that contains them is evaluated.
|
||||
//! `RELATED` and `RELATEDTABLE` traverse an existing relationship from a row context.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, Overload, ParamKind, Parameter, ReturnType, overload, required, spec, standard};
|
||||
|
||||
/// Signature of `CROSSFILTER`, which names both endpoint columns and a direction.
|
||||
const CROSSFILTER_PARAMS: &[Parameter] =
|
||||
&[required("LeftColumnName", ParamKind::Column), required("RightColumnName", ParamKind::Column), required("CrossFilterType", ParamKind::Any)];
|
||||
|
||||
const CROSSFILTER_OVERLOADS: &[Overload] = &[overload(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])];
|
||||
|
||||
const USERELATIONSHIP_PARAMS: &[Parameter] = &[required("ColumnName1", ParamKind::Column), required("ColumnName2", ParamKind::Column)];
|
||||
|
||||
const USERELATIONSHIP_OVERLOADS: &[Overload] = &[overload(&[ParamKind::Column, ParamKind::Column])];
|
||||
|
||||
/// Flags shared by the relationship management functions: none of them is an iterator or
|
||||
/// volatile, dax.guide recommends all of them, and every one is usable in Excel and restricted
|
||||
/// by DirectQuery exactly like the rest of the catalog.
|
||||
const RELATIONSHIP_FLAGS: FunctionFlags = standard(false);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"CROSSFILTER",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
3,
|
||||
3,
|
||||
CROSSFILTER_PARAMS,
|
||||
CROSSFILTER_OVERLOADS,
|
||||
ReturnType::Any,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Overrides the cross-filter direction of an existing relationship for the duration of \
|
||||
the filter context it modifies. The two column arguments identify the relationship \
|
||||
endpoints; the third argument is one of the words NONE, ONE, ONEWAY, BOTH, TWOWAY, \
|
||||
ONEWAY_LEFTFILTERSRIGHT or ONEWAY_RIGHTFILTERSLEFT (the last two flow from the first \
|
||||
column argument's table to the second's, or back). It changes filter propagation between \
|
||||
the two tables, never which relationship is active — activating an inactive relationship \
|
||||
is USERELATIONSHIP's job — so it is used as a filter modifier inside CALCULATE and \
|
||||
similar functions and returns no value.",
|
||||
&[
|
||||
"CALCULATE ( [Sales Amount], CROSSFILTER ( Sales[CustomerKey], Customer[CustomerKey], BOTH ) )",
|
||||
"CALCULATE ( COUNTROWS ( Customer ), CROSSFILTER ( Sales[ProductKey], 'Product'[ProductKey], NONE ) )",
|
||||
"CALCULATE ( [Sales Amount], CROSSFILTER ( Sales[CustomerKey], Customer[CustomerKey], TWOWAY ) )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"RELATED",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Returns the value of a column on the one side of a many-to-one relationship, following \
|
||||
one or more regular relationships from the current row. It requires a row context and \
|
||||
an active regular relationship, so it is used in calculated columns and inside table \
|
||||
iterators; a limited relationship cannot be traversed. The result is BLANK when no \
|
||||
related row exists and the column value can be of any type.",
|
||||
&[
|
||||
"SUMX ( Sales, Sales[Quantity] * RELATED ( 'Product'[List Price] ) )",
|
||||
"RELATED ( 'Product'[Category] )",
|
||||
"RELATED ( Customer[CountryRegion] )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"RELATEDTABLE",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
1,
|
||||
1,
|
||||
&[required("Table", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Returns the rows of a table on the many side of a relationship, filtered to the rows \
|
||||
related to the current row. It performs a context transition from the row context to a \
|
||||
filter context before evaluating the table, making it a shortcut for CALCULATETABLE \
|
||||
with no additional filters; unlike CALCULATETABLE it accepts only a table reference, \
|
||||
not an arbitrary table expression.",
|
||||
&["AVERAGEX ( Customer, COUNTROWS ( RELATEDTABLE ( Sales ) ) )", "RELATEDTABLE ( Sales )", "COUNTROWS ( RELATEDTABLE ( OrderLines ) )"],
|
||||
),
|
||||
spec(
|
||||
"USERELATIONSHIP",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
2,
|
||||
2,
|
||||
USERELATIONSHIP_PARAMS,
|
||||
USERELATIONSHIP_OVERLOADS,
|
||||
ReturnType::Any,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Activates an existing relationship for the duration of the filter context it modifies, \
|
||||
so its filters propagate even when the relationship is inactive in the model. The two \
|
||||
column arguments are the relationship endpoints; the innermost USERELATIONSHIP wins in \
|
||||
nested CALCULATE expressions. It selects which relationship propagates filters, not \
|
||||
their cross-filter direction, and returns no value.",
|
||||
&[
|
||||
"CALCULATE ( [Sales Amount], USERELATIONSHIP ( Sales[Delivery Date], 'Date'[Date] ) )",
|
||||
"CALCULATE ( COUNTROWS ( Sales ), USERELATIONSHIP ( Sales[Order Date], 'Date'[Date] ) )",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,584 @@
|
||||
//! Statistical functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples. The order matches
|
||||
//! <https://dax.guide/functions/statistical/>.
|
||||
//!
|
||||
//! `LINEST`, `LINESTX` and `SAMPLE` have open-ended signatures: their repeated column/expression
|
||||
//! groups (and the trailing `Const`/`Order` argument) are modelled with a variadic overload and
|
||||
//! [`usize::MAX`] as the upper arity bound. All other functions have a closed arity range.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard, variadic};
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"BETA.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
4,
|
||||
6,
|
||||
&[
|
||||
required("X", ParamKind::Number),
|
||||
required("Alpha", ParamKind::Number),
|
||||
required("Beta", ParamKind::Number),
|
||||
required("Cumulative", ParamKind::Logical),
|
||||
optional("A", ParamKind::Number),
|
||||
optional("B", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical, ParamKind::Number, ParamKind::Number]),
|
||||
],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Beta distribution on the interval [A, B]. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function. Omitting A and B uses the standard beta distribution on [0, 1]; Alpha and Beta must be positive, X must lie within [A, B], and a BLANK bound is an error rather than an omitted argument.",
|
||||
&["BETA.DIST ( 0.5, 3.51, 4.02, TRUE, 0, 1 )", "BETA.DIST ( 0.5, 3.51, 4.02, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"BETA.INV",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
5,
|
||||
&[
|
||||
required("Probability", ParamKind::Number),
|
||||
required("Alpha", ParamKind::Number),
|
||||
required("Beta", ParamKind::Number),
|
||||
optional("A", ParamKind::Number),
|
||||
optional("B", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number]),
|
||||
],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse of the beta cumulative distribution function: returns the x for which BETA.DIST ( x, Alpha, Beta, TRUE ) equals Probability. Probability must be strictly between 0 and 1, Alpha and Beta must be positive, A must be less than B, and the result lies between A and B; A and B default to 0 and 1.",
|
||||
&["BETA.INV ( 0.5, 3.51, 4.02 )", "BETA.INV ( 0.75, 3.51, 4.02, 0, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Chi-squared distribution with Deg_freedom degrees of freedom. Cumulative TRUE returns the left-tailed cumulative distribution, FALSE the probability density. Negative X is an error and a non-integer Deg_freedom is truncated.",
|
||||
&["CHISQ.DIST ( 2.5, 10, TRUE )", "CHISQ.DIST ( 2.5, 10, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.DIST.RT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Probability in the right tail of the chi-squared distribution with Deg_freedom degrees of freedom, used to compare observed and expected values in a chi-squared test. A non-integer Deg_freedom is truncated.",
|
||||
&["CHISQ.DIST.RT ( 2.5, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.INV",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse of the left-tailed chi-squared cumulative distribution: returns x such that CHISQ.DIST ( x, Deg_freedom, TRUE ) equals Probability. Probability must be at least 0 and less than 1; a non-integer Deg_freedom is rounded.",
|
||||
&["CHISQ.INV ( 0.95, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.INV.RT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse of the right-tailed chi-squared probability: returns x such that CHISQ.DIST.RT ( x, Deg_freedom ) equals Probability. Probability must be greater than 0 and at most 1; a non-integer Deg_freedom is rounded and the iterative search reports an error if it does not converge.",
|
||||
&["CHISQ.INV.RT ( 0.05, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"COMBIN",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Number of unordered combinations of Number_chosen items drawn without repetition from Number items. Numeric arguments are truncated to integers, and Number must be at least Number_chosen.",
|
||||
&["COMBIN ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"COMBINA",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Number of combinations with repetition of Number_chosen items drawn from Number items. Non-integer arguments are truncated (the remarks document rounding), both must be non-negative, and Number must be at least Number_chosen.",
|
||||
&["COMBINA ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"CONFIDENCE.NORM",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Alpha", ParamKind::Number), required("Standard_dev", ParamKind::Number), required("Size", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Half-width around the sample mean for a normal-distribution confidence interval. Alpha \
|
||||
is the significance level (0.05 gives a 95% interval), Standard_dev is the known \
|
||||
population standard deviation and Size is the sample size.",
|
||||
&["CONFIDENCE.NORM ( 0.05, 2.5, 50 )"],
|
||||
),
|
||||
spec(
|
||||
"CONFIDENCE.T",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Alpha", ParamKind::Number), required("Standard_dev", ParamKind::Number), required("Size", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Half-width around the sample mean when the population standard deviation is unknown, \
|
||||
using Student's t with Size - 1 degrees of freedom. Alpha is the significance level and \
|
||||
Standard_dev is the sample standard deviation.",
|
||||
&["CONFIDENCE.T ( 0.05, 2.5, 50 )"],
|
||||
),
|
||||
spec(
|
||||
"EXPON.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Lambda", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Exponential distribution with rate Lambda. Cumulative TRUE returns the cumulative distribution, FALSE the probability density; X must be non-negative and Lambda must be positive. Commonly used to model the time between events.",
|
||||
&["EXPON.DIST ( 0.2, 10, TRUE )", "EXPON.DIST ( 0.2, 10, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"GEOMEAN",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Geometric mean of the non-blank, positive values in a numeric column. Internally equivalent to GEOMEANX; blank and non-positive values do not contribute a valid term.",
|
||||
&["GEOMEAN ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"GEOMEANX",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Evaluates the expression once per row of the table and returns the geometric mean of the non-blank, positive results. The expression runs in row context, so a measure reference triggers context transition.",
|
||||
&["GEOMEANX ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"LINEST",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("ColumnY", ParamKind::Column), required("ColumnX", ParamKind::Column), optional("Const", ParamKind::Boolean)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Column]), variadic(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Least-squares straight-line fit of ColumnY against one or more ColumnX columns, returned as a one-row table with a slope per X column, the intercept, their standard errors, the coefficient of determination, the standard error, the F statistic, degrees of freedom and the regression/residual sums of squares. All column references must come from the same table; a trailing FALSE forces the intercept to 0.",
|
||||
&["LINEST ( Sales[Amount], Sales[Quantity] )", "LINEST ( Sales[Amount], Sales[Quantity], TRUE )"],
|
||||
),
|
||||
spec(
|
||||
"LINESTX",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
required("ExpressionY", ParamKind::Expression),
|
||||
required("ExpressionX", ParamKind::Expression),
|
||||
optional("Const", ParamKind::Boolean),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Expression]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Expression, ParamKind::Expression, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(true, false, false, false, true),
|
||||
"Evaluates the y and x expressions row by row and returns the same least-squares regression table as LINEST: one slope per x expression, intercept, standard errors, coefficient of determination, standard error, F statistic, degrees of freedom and regression/residual sums of squares. A trailing FALSE forces the intercept to 0.",
|
||||
&["LINESTX ( Sales, Sales[Amount], Sales[Quantity] )", "LINESTX ( Sales, Sales[Amount], Sales[Quantity], TRUE )"],
|
||||
),
|
||||
spec(
|
||||
"MEDIAN",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("Column", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Variant,
|
||||
standard(false),
|
||||
"50th percentile (median) of the non-blank numeric values in a column. Logical values, dates and text are not supported. Returns BLANK when no row has a non-blank numeric value; internally equivalent to MEDIANX, which unlike MEDIAN does not ignore blank results.",
|
||||
&["MEDIAN ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"MEDIANX",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Variant,
|
||||
standard(true),
|
||||
"Evaluates the expression once per row and returns the median of the results. Unlike MEDIAN, blank results returned by the expression are considered; the result is BLANK when no row returns a non-blank value. Integer results make the return type Variant (Integer without ties, Decimal with ties).",
|
||||
&["MEDIANX ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
4,
|
||||
4,
|
||||
&[
|
||||
required("X", ParamKind::Number),
|
||||
required("Mean", ParamKind::Number),
|
||||
required("Standard_dev", ParamKind::Number),
|
||||
required("Cumulative", ParamKind::Logical),
|
||||
],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Normal distribution for the given Mean and Standard_dev. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function; Standard_dev must be positive.",
|
||||
&["NORM.DIST ( 45, 40, 2, TRUE )", "NORM.DIST ( 45, 40, 2, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.INV",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Probability", ParamKind::Number), required("Mean", ParamKind::Number), required("Standard_dev", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"The x for which the normal cumulative probability equals Probability, given Mean and Standard_dev. Probability must lie in (0, 1) and Standard_dev must be positive.",
|
||||
&["NORM.INV ( 0.95, 40, 1.5 )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.S.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Z", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Standard normal distribution (mean 0, standard deviation 1). Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function.",
|
||||
&["NORM.S.DIST ( 1.96, TRUE )", "NORM.S.DIST ( 1.96, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.S.INV",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("Probability", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"The x for which the standard normal cumulative probability equals Probability (mean 0, standard deviation 1). Probability must lie strictly between 0 and 1.",
|
||||
&["NORM.S.INV ( 0.975 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILE.EXC",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Column", ParamKind::Column), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(false),
|
||||
"Exclusive k-th percentile of the non-blank values in a column. K must lie in [1/(n+1), 1-1/(n+1)], where n is the number of valid values; K outside that interval is an error. Blanks in the column are ignored, unlike the blank results considered by PERCENTILEX.EXC.",
|
||||
&["PERCENTILE.EXC ( Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILE.INC",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Column", ParamKind::Column), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(false),
|
||||
"Inclusive k-th percentile of the non-blank values in a column, where K lies in [0, 1]. Blanks in the column are ignored, unlike the blank results considered by PERCENTILEX.INC.",
|
||||
&["PERCENTILE.INC ( Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILEX.EXC",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(true),
|
||||
"Exclusive k-th percentile of the values returned by the expression, evaluated row by row. K must lie in [1/(n+1), 1-1/(n+1)]. Unlike PERCENTILE.EXC, blank values returned by the expression are considered.",
|
||||
&["PERCENTILEX.EXC ( Sales, Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILEX.INC",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(true),
|
||||
"Inclusive k-th percentile of the values returned by the expression, evaluated row by row, where K lies in [0, 1]. Unlike PERCENTILE.INC, blank values returned by the expression are considered.",
|
||||
&["PERCENTILEX.INC ( Sales, Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERMUT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Number of ordered permutations of Number_chosen objects selected from Number objects, where order matters. Both arguments are truncated to integers; Number must be positive, Number_chosen non-negative and Number at least Number_chosen.",
|
||||
&["PERMUT ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"POISSON.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Mean", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Poisson distribution with the given Mean. Cumulative TRUE returns the probability of at most X events, FALSE the probability mass of exactly X events; a non-integer X is truncated and X must be non-negative.",
|
||||
&["POISSON.DIST ( 2, 5, TRUE )", "POISSON.DIST ( 2, 5, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"RANK.EQ",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
3,
|
||||
&[required("Value", ParamKind::Scalar), required("ColumnName", ParamKind::Column), optional("Order", ParamKind::Scalar)],
|
||||
&[overload(&[ParamKind::Scalar, ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Column, ParamKind::Scalar])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Rank of Value among the numbers in ColumnName, with ties sharing the top rank. Order 0/FALSE/DESC ranks descending (the default) and 1/TRUE/ASC ranks ascending. Equivalent to a RANKX call over SELECTCOLUMNS rather than pure syntax sugar.",
|
||||
&["RANK.EQ ( 42, Sales[Quantity] )", "RANK.EQ ( 42, Sales[Quantity], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"RANKX",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
5,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
required("Expression", ParamKind::Expression),
|
||||
optional("Value", ParamKind::Scalar),
|
||||
optional("Order", ParamKind::Scalar),
|
||||
optional("Ties", ParamKind::Scalar),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table, ParamKind::Expression]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar, ParamKind::Scalar]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar, ParamKind::Scalar, ParamKind::Scalar]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
standard(true),
|
||||
"Rank of Value (or of Expression when Value is omitted) among the values Expression returns for every row of Table. Order defaults to descending and Ties defaults to Skip; Dense gives tied elements one shared rank without gaps. Expression runs in row context. Decimal inputs can rank unexpectedly because of floating-point storage, so ROUND or a Currency type is safer.",
|
||||
&["RANKX ( Sales, Sales[Amount] )", "RANKX ( Sales, Sales[Amount], 42, 0, Dense )"],
|
||||
),
|
||||
spec(
|
||||
"SAMPLE",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Size", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("OrderBy", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Scalar),
|
||||
],
|
||||
&[variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
standard(true),
|
||||
"Deterministic sample of Size rows from Table, ordered by one or more OrderBy expressions with optional Order values. The result is fixed: it includes the first and final rows plus the rows spaced evenly between them; Size 0 or less returns an empty table. Group the input by the sort column to avoid duplicate rows.",
|
||||
&["SAMPLE ( 10, Sales, Sales[Amount] )", "SAMPLE ( 10, Sales, Sales[Amount], 0 )"],
|
||||
),
|
||||
spec(
|
||||
"STDEV.P",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Standard deviation of an entire population in a numeric column, ignoring blanks, logical values and text. Internally equivalent to STDEVX.P; use STDEV.S for a sample.",
|
||||
&["STDEV.P ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"STDEV.S",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Sample standard deviation of a numeric column, ignoring blanks, logical values and text. Internally equivalent to STDEVX.S; use STDEV.P for a complete population.",
|
||||
&["STDEV.S ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"STDEVX.P",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Standard deviation of an entire population, computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["STDEVX.P ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"STDEVX.S",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Sample standard deviation computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["STDEVX.S ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"T.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Student's left-tailed t distribution with Deg_freedom degrees of freedom. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density; Deg_freedom cannot be negative.",
|
||||
&["T.DIST ( 2, 10, TRUE )", "T.DIST ( 2, 10, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"T.DIST.2T",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Two-tailed Student's t distribution with Deg_freedom degrees of freedom. Neither argument can be negative.",
|
||||
&["T.DIST.2T ( 2, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"T.DIST.RT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Right-tailed Student's t distribution with Deg_freedom degrees of freedom. Deg_freedom cannot be negative.",
|
||||
&["T.DIST.RT ( 2, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"T.INV",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Solves for the t value whose cumulative probability equals Probability, on the left tail of Student's t. Probability must lie between 0 and 1 and Deg_freedom cannot be negative.",
|
||||
&["T.INV ( 0.95, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"T.INV.2T",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Solves for the t value whose two-tailed probability equals Probability. Neither argument can be negative.",
|
||||
&["T.INV.2T ( 0.05, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"VAR.P",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Variance of an entire population in a numeric column, ignoring blanks, logical values and text. Internally equivalent to VARX.P; use VAR.S for a sample.",
|
||||
&["VAR.P ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"VAR.S",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Sample variance of a numeric column, ignoring blanks, logical values and text. Internally equivalent to VARX.S; use VAR.P for a complete population.",
|
||||
&["VAR.S ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"VARX.P",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Variance of an entire population, computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["VARX.P ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"VARX.S",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Sample variance computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["VARX.S ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,641 @@
|
||||
//! Table manipulation functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category holds four kinds of functions:
|
||||
//!
|
||||
//! - table constructors and projections (`DATATABLE`, `ROW`, `ADDCOLUMNS`, `SELECTCOLUMNS`,
|
||||
//! `SUMMARIZE`, `SUMMARIZECOLUMNS`, `GROUPBY`);
|
||||
//! - relational operations (`CROSSJOIN`, `UNION`, `EXCEPT`, `INTERSECT`, the natural joins and
|
||||
//! `SUBSTITUTEWITHINDEX`);
|
||||
//! - companion functions that are only valid as arguments of those operations (`CURRENTGROUP`,
|
||||
//! `IGNORE`, `NONVISUAL`, `NATURALJOINUSAGE`, `ROLLUP`, `ROLLUPGROUP`,
|
||||
//! `ROLLUPADDISSUBTOTAL`, `ROLLUPISSUBTOTAL`);
|
||||
//! - row selection and value helpers (`DISTINCT`, `VALUES`, `FILTERS`, `TOPN`, `TOPNSKIP`,
|
||||
//! `GENERATESERIES`, `DETAILROWS`, `TREATAS`, `SAMPLEAXISWITHLOCALMINMAX`,
|
||||
//! `TOPNPERLEVEL`).
|
||||
//!
|
||||
//! The companion functions are catalogued because the parser accepts them, but several do not
|
||||
//! return a value on their own: they are syntax markers inside `SUMMARIZE`,
|
||||
//! `SUMMARIZECOLUMNS` or `ADDMISSINGITEMS`, so their return type is [`ReturnType::Blank`].
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Available to every host, with the usual DirectQuery restrictions.
|
||||
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// Iterators evaluate an expression once per row of the first table argument.
|
||||
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
|
||||
|
||||
/// No Excel version listed by dax.guide supports the function.
|
||||
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
/// Power BI-only extension functions: engine extensions that DirectQuery cannot evaluate.
|
||||
const EXTENSION: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"ADDCOLUMNS",
|
||||
FunctionCategory::TableManipulation,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Name", ParamKind::Text), required("Expression", ParamKind::Expression)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Text, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Returns the input table with new columns added. Each expression is evaluated in the \
|
||||
row context of the table, so the expressions are repeatable in `Name, Expression` \
|
||||
pairs. The added columns keep the data lineage of a simple column reference for \
|
||||
NATURALINNERJOIN/NATURALLEFTOUTERJOIN but not for context transition.",
|
||||
&[
|
||||
"ADDCOLUMNS ( Sales, \"Margin\", Sales[Amount] - Sales[Cost] )",
|
||||
"ADDCOLUMNS ( Product, \"Brand\", Product[Brand], \"Price\", Product[List Price] )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"ADDMISSINGITEMS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("ShowAll_ColumnName", ParamKind::Column),
|
||||
required("Table", ParamKind::Table),
|
||||
optional("GroupBy_ColumnName", ParamKind::Any),
|
||||
optional("FilterTable", ParamKind::Table),
|
||||
],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Adds back the rows of a SUMMARIZECOLUMNS result that were removed because every \
|
||||
measure was blank. The optional leading columns list which columns must show all \
|
||||
items; the table argument is the SUMMARIZECOLUMNS result, followed by optional \
|
||||
group-by columns (possibly ROLLUPGROUP/ROLLUPADDISSUBTOTAL calls) and filters. \
|
||||
ROLLUPISSUBTOTAL marks the subtotal columns.",
|
||||
&["ADDMISSINGITEMS ( Sales[Region], SUMMARIZECOLUMNS ( Sales[Region], \"Amount\", SUM ( Sales[Amount] ) ), Sales[Region] )"],
|
||||
),
|
||||
spec(
|
||||
"CROSSJOIN",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table)],
|
||||
&[variadic(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the Cartesian product of the table arguments. The result has the product of \
|
||||
the row counts and the sum of the column counts; column names must be different in \
|
||||
every argument or the function raises an error.",
|
||||
&["CROSSJOIN ( Product, Store )", "CROSSJOIN ( Product, Store, 'Date' )"],
|
||||
),
|
||||
spec(
|
||||
"CURRENTGROUP",
|
||||
FunctionCategory::TableManipulation,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the subset of rows of the GROUPBY input table that belong to the current \
|
||||
group. It takes no arguments and is only valid as the table argument of an \
|
||||
aggregation iterator inside GROUPBY, such as SUMX or COUNTX.",
|
||||
&["GROUPBY ( Sales, Sales[Region], \"Amount\", SUMX ( CURRENTGROUP (), Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"DATATABLE",
|
||||
FunctionCategory::TableManipulation,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Name", ParamKind::Text), required("DataType", ParamKind::Text), required("Data", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Text, ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns a table whose columns and rows are declared inline. Column names and data type \
|
||||
names alternate, followed by a single table constructor with the data. Data type names \
|
||||
are BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64 and \
|
||||
STRING/TEXT; unlike the table constructor, DATATABLE requires literal values.",
|
||||
&[
|
||||
"DATATABLE ( \"Name\", STRING, { { \"Small\", 1 }, { \"Medium\", 2 } } )",
|
||||
"DATATABLE ( \"Name\", STRING, \"Ordinal\", INTEGER, { { \"Small\", 1 }, { \"Large\", 3 } } )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"DETAILROWS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Measure", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Reference])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the table produced by the DetailRows expression defined on a measure. When the \
|
||||
measure has no DetailRows expression, the entire table the measure belongs to is \
|
||||
returned. Context transition is not applied by the engine; wrap the call in \
|
||||
CALCULATETABLE inside a row context when transition is intended.",
|
||||
&["DETAILROWS ( [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"DISTINCT",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnNameOrTableExpr", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the distinct values of a column, or the distinct rows of a table expression. \
|
||||
Unlike VALUES, a column argument does not add the blank row generated by an invalid \
|
||||
relationship.",
|
||||
&["DISTINCT ( Sales[Region] )", "DISTINCT ( Sales )"],
|
||||
),
|
||||
spec(
|
||||
"EXCEPT",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the rows of the left table that do not appear in the right table. A row present \
|
||||
in both tables is removed together with its duplicates; columns are matched by position \
|
||||
with strict comparison and the result keeps the left table's column names and lineage.",
|
||||
&["EXCEPT ( Sales, SalesArchive )"],
|
||||
),
|
||||
spec(
|
||||
"FILTERS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the filter values applied directly to a column, as a single-column table. The \
|
||||
column argument must be a column reference; the result can include the blank row \
|
||||
generated by an invalid relationship.",
|
||||
&["FILTERS ( Store[Continent] )", "FILTERS ( 'Date'[Calendar Year] )"],
|
||||
),
|
||||
spec(
|
||||
"GENERATE",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("Table1", ParamKind::Table), required("Table2", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Evaluates the second table expression for every row of the first table and returns the \
|
||||
union of those results with the corresponding first-table columns. Rows of the first \
|
||||
table whose second expression is empty are dropped, unlike GENERATEALL.",
|
||||
&["GENERATE ( Product, RELATEDTABLE ( Sales ) )"],
|
||||
),
|
||||
spec(
|
||||
"GENERATEALL",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("Table1", ParamKind::Table), required("Table2", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Evaluates the second table expression for every row of the first table and keeps the \
|
||||
first-table row even when that expression is empty, filling the second table's columns \
|
||||
with blanks. Column names must be different in both arguments.",
|
||||
&["GENERATEALL ( Product, RELATEDTABLE ( Sales ) )"],
|
||||
),
|
||||
spec(
|
||||
"GENERATESERIES",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
3,
|
||||
&[required("StartValue", ParamKind::Number), required("EndValue", ParamKind::Number), optional("IncrementValue", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns a single-column table named Value holding an arithmetic series from StartValue \
|
||||
to EndValue. IncrementValue must be positive and defaults to 1; the series stops at the \
|
||||
last value less than or equal to EndValue, and EndValue below StartValue yields an \
|
||||
empty table.",
|
||||
&["GENERATESERIES ( 1, 10, 2 )", "GENERATESERIES ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )"],
|
||||
),
|
||||
spec(
|
||||
"GROUPBY",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
optional("GroupBy_ColumnName", ParamKind::Column),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Expression),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Column]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Groups the input table by the given columns and adds expression columns evaluated per \
|
||||
group. Expressions added by GROUPBY must aggregate CURRENTGROUP() and cannot use \
|
||||
CALCULATE; use SUMMARIZE when the added columns aggregate base-table columns.",
|
||||
&["GROUPBY ( Sales, Sales[Region], \"Amount\", SUMX ( CURRENTGROUP (), Sales[Amount] ) )", "GROUPBY ( Customer, Customer[Country] )"],
|
||||
),
|
||||
spec(
|
||||
"IGNORE",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Measure_Expression", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Marks a SUMMARIZECOLUMNS expression so that it is excluded when deciding whether a row \
|
||||
is blank. Rows are kept as long as another expression without IGNORE returns a value; \
|
||||
the function itself returns no value.",
|
||||
&["SUMMARIZECOLUMNS ( Sales[Region], IGNORE ( [Sales Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"INTERSECT",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the rows of the left table that also appear in the right table, keeping \
|
||||
duplicates from the left table. Columns are matched by position without type coercion; \
|
||||
the operation is not commutative and the result keeps the left table's column names and \
|
||||
lineage.",
|
||||
&["INTERSECT ( Sales, SalesArchive )"],
|
||||
),
|
||||
spec(
|
||||
"NATURALINNERJOIN",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Joins two tables on all columns they have in common (including columns of their \
|
||||
expanded tables) and returns the matching rows. Joined columns must have the same name, \
|
||||
data type and lineage; comparison is strict, with no type coercion.",
|
||||
&["NATURALINNERJOIN ( Sales, Product )"],
|
||||
),
|
||||
spec(
|
||||
"NATURALJOINUSAGE",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Expression", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
ENGINE_ONLY,
|
||||
"Adds a table as a natural join to the filter context. It is only valid as a value \
|
||||
filter of SUMMARIZECOLUMNS and is used mostly in queries sent to composite models; \
|
||||
dax.guide lists no Excel support and Microsoft documentation is not available.",
|
||||
&["SUMMARIZECOLUMNS ( Sales[Region], NATURALJOINUSAGE ( Product ) )"],
|
||||
),
|
||||
spec(
|
||||
"NATURALLEFTOUTERJOIN",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Joins two tables on all columns they have in common and returns every row of the left \
|
||||
table, with blanks where the right table has no match. Joined columns must share name, \
|
||||
data type and lineage, and comparison does not coerce types.",
|
||||
&["NATURALLEFTOUTERJOIN ( Sales, Product )"],
|
||||
),
|
||||
spec(
|
||||
"NONVISUAL",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Expression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Marks a SUMMARIZECOLUMNS value filter as non-visual: the filter still restricts the \
|
||||
grouping columns but does not affect measure values, so measures that use \
|
||||
ALLSELECTED can return the non-visual totals.",
|
||||
&["SUMMARIZECOLUMNS ( 'Date'[Calendar Year], NONVISUAL ( TREATAS ( { \"CY 2008\" }, 'Date'[Calendar Year] ) ), \"Amount\", [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUP",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("GroupBy_ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Identifies the SUMMARIZE group-by columns that also produce subtotal rows. The \
|
||||
arguments must be qualified column names, not expressions, and are only valid inside \
|
||||
SUMMARIZE; the function itself returns no value.",
|
||||
&["SUMMARIZE ( Sales, ROLLUP ( Sales[Country], Sales[City] ), \"Amount\", SUM ( Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUPADDISSUBTOTAL",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("GrandtotalFilter", ParamKind::Table),
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("Name", ParamKind::Text),
|
||||
optional("GroupLevelFilter", ParamKind::Table),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Identifies the SUMMARIZECOLUMNS group-by columns that produce subtotals and adds a \
|
||||
Boolean column per pair indicating whether the row is a subtotal. It accepts an \
|
||||
optional grand-total filter before the pairs and an optional per-level filter after \
|
||||
each pair; it is only valid inside SUMMARIZECOLUMNS and returns no value.",
|
||||
&["SUMMARIZECOLUMNS ( ROLLUPADDISSUBTOTAL ( Sales[Country], \"IsSubtotal Country\" ), \"Amount\", SUM ( Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUPGROUP",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("GroupBy_ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Column])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Identifies a group of SUMMARIZE or SUMMARIZECOLUMNS columns that produce subtotals \
|
||||
together. Inside ROLLUP it suppresses the partial subtotals that ROLLUP would \
|
||||
otherwise add; the function itself returns no value.",
|
||||
&["SUMMARIZE ( Sales, ROLLUPGROUP ( Sales[Country], Sales[City] ), \"Amount\", SUM ( Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUPISSUBTOTAL",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("GrandtotalFilter", ParamKind::Table),
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("IsSubtotal_ColumnName", ParamKind::Text),
|
||||
optional("GroupLevelFilter", ParamKind::Table),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Pairs the subtotal columns created by ROLLUPADDISSUBTOTAL with their group-by columns \
|
||||
so that ADDMISSINGITEMS can add the missing subtotal rows. It is only valid inside \
|
||||
ADDMISSINGITEMS and returns no value.",
|
||||
&[
|
||||
"ADDMISSINGITEMS ( Sales[Country], SUMMARIZECOLUMNS ( ROLLUPADDISSUBTOTAL ( Sales[Country], \"IsSubtotal\" ), \"Amount\", SUM ( Sales[Amount] ) ), ROLLUPISSUBTOTAL ( Sales[Country], [IsSubtotal] ) )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"ROW",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Name", ParamKind::Text), required("Expression", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns a single-row table with the named columns. Arguments come in `Name, \
|
||||
Expression` pairs; column references used as expressions lose their data lineage rather \
|
||||
than keeping it.",
|
||||
&["ROW ( \"Product\", \"Bike\", \"Price\", 1500 )", "ROW ( \"Value\", 1 )"],
|
||||
),
|
||||
spec(
|
||||
"SAMPLEAXISWITHLOCALMINMAX",
|
||||
FunctionCategory::TableManipulation,
|
||||
5,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Size", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("Axis", ParamKind::Column),
|
||||
required("Measure", ParamKind::Expression),
|
||||
required("MinResolution", ParamKind::Number),
|
||||
optional("DynamicSeries", ParamKind::Column),
|
||||
optional("DynamicSeriesSelectionCriteria", ParamKind::Text),
|
||||
optional("DynamicSeriesSelectionOrder", ParamKind::Boolean),
|
||||
optional("MaxResolution", ParamKind::Number),
|
||||
optional("MaxDynamicSeries", ParamKind::Number),
|
||||
optional("MaxIterations", ParamKind::Number),
|
||||
],
|
||||
&[variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Any, ParamKind::Number])],
|
||||
ReturnType::Table,
|
||||
ENGINE_ONLY,
|
||||
"Returns a subset of the input table obtained by binning the numeric or date axis into \
|
||||
equal-sized bins and preserving the local minimum and maximum of each measure per \
|
||||
series. Power BI uses it to reduce the points of line charts with a continuous axis; \
|
||||
dax.guide lists no Excel support and Microsoft documentation is not available.",
|
||||
&["SAMPLEAXISWITHLOCALMINMAX ( 100, Sales, Sales[Order Date], Sales[Amount], 10 )"],
|
||||
),
|
||||
spec(
|
||||
"SELECTCOLUMNS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), optional("Name", ParamKind::Text), optional("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Projects the input to one column per `Name, Expression` pair, keeping the same row \
|
||||
count; each expression is evaluated in row context. Unlike ADDCOLUMNS it starts from an \
|
||||
empty table; the name may be omitted when the expression is a simple column reference, \
|
||||
and simple references keep their data lineage.",
|
||||
&[
|
||||
"SELECTCOLUMNS ( Sales, \"Amount\", Sales[Amount] )",
|
||||
"SELECTCOLUMNS ( Product, \"Brand\", Product[Brand], \"Category\", Product[Category] )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"SUBSTITUTEWITHINDEX",
|
||||
FunctionCategory::TableManipulation,
|
||||
4,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
required("Name", ParamKind::Text),
|
||||
required("SemiJoinIndexTable", ParamKind::Table),
|
||||
required("Expression", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Number),
|
||||
],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Text, ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Semijoins two tables and replaces the common columns with a zero-based index column. \
|
||||
The index follows the row order obtained by sorting the second table with the supplied \
|
||||
order expressions; matching uses the same lineage rules as the natural joins and raises \
|
||||
an error when no column matches.",
|
||||
&["SUBSTITUTEWITHINDEX ( Sales, \"ProductIndex\", DISTINCT ( Sales[ProductKey] ), Sales[ProductKey] )"],
|
||||
),
|
||||
spec(
|
||||
"SUMMARIZE",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
optional("GroupBy_ColumnName", ParamKind::Reference),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Expression),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Reference]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Reference, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Groups the input table by the given columns and optionally adds computed columns. The \
|
||||
group-by arguments can be columns of the table or its related tables, or ROLLUP / \
|
||||
ROLLUPGROUP calls. Adding columns with SUMMARIZE is deprecated in favour of \
|
||||
SUMMARIZECOLUMNS or ADDCOLUMNS, and ROLLUP/ROLLUPGROUP columns lose their data lineage.",
|
||||
&["SUMMARIZE ( Sales, Sales[Region], \"Amount\", SUM ( Sales[Amount] ) )", "SUMMARIZE ( Sales, 'Product'[Brand], 'Date'[Calendar Year] )"],
|
||||
),
|
||||
spec(
|
||||
"SUMMARIZECOLUMNS",
|
||||
FunctionCategory::TableManipulation,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("GroupBy_ColumnName", ParamKind::Any),
|
||||
optional("FilterTable", ParamKind::Table),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Expression),
|
||||
],
|
||||
&[overload(&[]), variadic(&[ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Builds a summary table from group-by columns, filters applied only to the grouping, and \
|
||||
added expression columns. A row is included only when at least one expression returns a \
|
||||
non-blank value; filters accept KEEPFILTERS, REMOVEFILTERS and NONVISUAL, and group-by \
|
||||
arguments accept ROLLUPGROUP and ROLLUPADDISSUBTOTAL. Since June 2024 it can run inside \
|
||||
context transition, with the remaining limitations documented by Microsoft.",
|
||||
&[
|
||||
"SUMMARIZECOLUMNS ( Sales[Region], \"Amount\", SUM ( Sales[Amount] ) )",
|
||||
"SUMMARIZECOLUMNS ( 'Product'[Brand], 'Date'[Calendar Year], \"Amount\", [Sales Amount] )",
|
||||
"SUMMARIZECOLUMNS ( )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"TOPN",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("N_Value", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
optional("OrderBy_Expression", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Number),
|
||||
],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Table]), variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Returns the top N rows of a table according to the order-by expressions. Order is \
|
||||
0/FALSE/DESC or 1/TRUE/ASC and defaults to descending; ties at the N-th row are all \
|
||||
returned, and N_Value of zero or less yields an empty table. The result has no \
|
||||
guaranteed sort order.",
|
||||
&["TOPN ( 10, Sales, Sales[Amount], DESC )"],
|
||||
),
|
||||
spec(
|
||||
"TOPNPERLEVEL",
|
||||
FunctionCategory::TableManipulation,
|
||||
6,
|
||||
6,
|
||||
&[
|
||||
required("Rows", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("LevelsDefinition", ParamKind::Table),
|
||||
required("NodesExpanded", ParamKind::Table),
|
||||
required("LevelsBoundaries", ParamKind::Table),
|
||||
required("RestartIndicatorColumnName", ParamKind::Text),
|
||||
],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Table, ParamKind::Table, ParamKind::Table, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
EXTENSION,
|
||||
"Returns the rows to display for an expanded hierarchy, restricted to the selected nodes \
|
||||
and boundaries. It is an undocumented Power BI extension that is not part of the \
|
||||
Analysis Services engine and has no Excel or DirectQuery support.",
|
||||
&["TOPNPERLEVEL ( 10, Sales, Levels, Expanded, Boundaries, \"Restart\" )"],
|
||||
),
|
||||
spec(
|
||||
"TOPNSKIP",
|
||||
FunctionCategory::TableManipulation,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Rows", ParamKind::Number),
|
||||
required("Skip_Rows_Value", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
optional("OrderBy_Expression", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Number),
|
||||
optional("Ties", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Table]),
|
||||
variadic(&[ParamKind::Number, ParamKind::Number, ParamKind::Table, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Retrieves Rows rows from a table after skipping Skip rows, ordered by the order-by \
|
||||
expressions. Ties can be handled as Skip (ranking skips tied elements) or Dense (all \
|
||||
tied elements count as one); the result has no guaranteed sort order. With a non-zero \
|
||||
skip the table has to reference physical columns that carry lineage, and context \
|
||||
transition cannot occur.",
|
||||
&["TOPNSKIP ( 10, 20, Sales, Sales[Amount], DESC )"],
|
||||
),
|
||||
spec(
|
||||
"TREATAS",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Expression", ParamKind::Table), required("ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Applies the data lineage of the output columns to the table returned by the first \
|
||||
argument, so that its values filter the model columns as if they came from those \
|
||||
columns. Only a table expression is accepted there; unused values are filtered out and \
|
||||
the result can be stored in a variable.",
|
||||
&["TREATAS ( { \"North America\" }, Sales[Region] )", "TREATAS ( { 2008, 2009 }, 'Date'[Calendar Year] )"],
|
||||
),
|
||||
spec(
|
||||
"UNION",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Table2", ParamKind::Table)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns all rows of all table arguments, keeping duplicates. Columns are combined by \
|
||||
position and the result takes its column names from the first table; differing data \
|
||||
types are resolved with DAX coercion rules, and lineage is kept only where all input \
|
||||
columns share it.",
|
||||
&["UNION ( Sales, SalesArchive )", "UNION ( Sales, SalesArchive, SalesForecast )"],
|
||||
),
|
||||
spec(
|
||||
"VALUES",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("TableNameOrColumnName", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"With a column, returns its unique values as a single-column table, including the blank \
|
||||
row produced by an invalid relationship. With a table name it returns every row of that \
|
||||
table with its columns unchanged, without removing duplicates. VALUES needs a model \
|
||||
table or column, so it cannot be applied to a variable.",
|
||||
&["VALUES ( Sales[Region] )", "VALUES ( Store )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Text functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category splits into three kinds of functions:
|
||||
//!
|
||||
//! - string construction (`COMBINEVALUES`, `CONCATENATE`, `CONCATENATEX`, `LEFT`, `MID`,
|
||||
//! `REPLACE`, `REPT`, `RIGHT`, `SUBSTITUTE`, `TRIM`), which return text and whose result
|
||||
//! length is measured in Unicode code points;
|
||||
//! - classification and conversion (`EXACT`, `FIND`, `LEN`, `LOWER`, `SEARCH`, `UNICHAR`,
|
||||
//! `UNICODE`, `UPPER`), which are case- or accent-sensitive to different degrees;
|
||||
//! - formatting and serialization (`FIXED`, `FORMAT`, `TOCSV`, `TOJSON`, `VALUE`), whose output
|
||||
//! or parsing depends on the model locale.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Available to every host, with no documented DirectQuery restriction.
|
||||
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, false);
|
||||
|
||||
/// Functions that DirectQuery does not support in calculated columns.
|
||||
const DQ_RESTRICTED: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// `CONCATENATEX` is an iterator and is also restricted in DirectQuery calculated columns.
|
||||
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
|
||||
|
||||
/// Engine-only functions: no Excel version listed by dax.guide supports them.
|
||||
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"COMBINEVALUES",
|
||||
FunctionCategory::Text,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Delimiter", ParamKind::Text), required("Expression1", ParamKind::Any), required("Expression2", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Text, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Concatenates two or more scalar values with a delimiter and returns one text value. The \
|
||||
function is designed for calculated columns that stand in for multi-column relationships \
|
||||
in DirectQuery models: the engine can translate the call into an optimized join \
|
||||
predicate, assuming without validating that different input combinations produce \
|
||||
different output strings. Choose a delimiter that cannot occur ambiguously in the \
|
||||
values, and remember that the delimiter itself is not escaped.",
|
||||
&["COMBINEVALUES ( \" | \", Customer[Customer Name], Customer[Customer Code] )", "COMBINEVALUES ( \"-\", \"GridCraft\", \"2024\", \"Q1\" )"],
|
||||
),
|
||||
spec(
|
||||
"CONCATENATE",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
2,
|
||||
&[required("Text1", ParamKind::Text), required("Text2", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Joins two text values into one text value without inserting a separator. The `&` operator \
|
||||
performs the same concatenation and accepts any number of operands, so CONCATENATE is \
|
||||
only convenient for two. Non-text arguments are converted to text using the model's \
|
||||
locale rather than the caller's culture.",
|
||||
&["CONCATENATE ( \"GridCraft\", \" 2024\" )", "CONCATENATE ( Customer[Customer Name], Customer[Customer Code] )"],
|
||||
),
|
||||
spec(
|
||||
"CONCATENATEX",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[
|
||||
overload(&[ParamKind::Table, ParamKind::Expression]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression, ParamKind::Logical]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression]),
|
||||
],
|
||||
ReturnType::String,
|
||||
ITERATOR,
|
||||
"Iterates a table, evaluates the expression for every row and concatenates the results \
|
||||
into a single text value using an optional delimiter. An order-by expression and an \
|
||||
optional order (0/FALSE/DESC or 1/TRUE/ASC, ascending by default) sort the values; \
|
||||
without them the row order is unspecified and does not reflect the source table's \
|
||||
physical order. Ordering follows the model collation, while the delimiter is inserted \
|
||||
verbatim.",
|
||||
&[
|
||||
"CONCATENATEX ( Sales, Sales[Product], \", \" )",
|
||||
"CONCATENATEX ( Sales, Sales[Product], \", \", Sales[Amount] )",
|
||||
"CONCATENATEX ( Sales, Sales[Product], \", \", Sales[Amount], TRUE )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"EXACT",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
2,
|
||||
&[required("Text1", ParamKind::Text), required("Text2", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Compares two text values and returns TRUE when they are exactly the same, including \
|
||||
case. The ordinary `=` comparison is case-insensitive, so EXACT is the way to force a \
|
||||
case-sensitive and accent-sensitive test. BLANK and an empty string compare equal here.",
|
||||
&["EXACT ( \"GridCraft\", \"gridcraft\" )", "EXACT ( Sales[Code], \"A-100\" )"],
|
||||
),
|
||||
spec(
|
||||
"FIND",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("FindText", ParamKind::Text),
|
||||
required("WithinText", ParamKind::Text),
|
||||
optional("StartPosition", ParamKind::Number),
|
||||
optional("NotFoundValue", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Returns the 1-based position of FindText inside WithinText, beginning the search at \
|
||||
StartPosition (default 1). The comparison is case-sensitive and accent-sensitive, and \
|
||||
wildcards are not interpreted; use SEARCH for case-insensitive or wildcard matching. If \
|
||||
the text is absent the function returns NotFoundValue when it is supplied, otherwise it \
|
||||
raises an error.",
|
||||
&["FIND ( \"Red\", \"GridCraft Cell S100 Red\" )", "FIND ( \"Red\", \"GridCraft Cell S100 Red\", 1, BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"FIXED",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
3,
|
||||
&[required("Number", ParamKind::Number), optional("Decimals", ParamKind::Number), optional("NoCommas", ParamKind::Boolean)],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Boolean]),
|
||||
],
|
||||
ReturnType::String,
|
||||
DQ_RESTRICTED,
|
||||
"Rounds a number to the requested number of decimals and returns it as text, grouping the \
|
||||
integer part with commas unless NoCommas is TRUE. Decimals defaults to 2, and a negative \
|
||||
value rounds to the left of the decimal separator. The decimal and grouping separators \
|
||||
come from the model locale, not from the caller's culture.",
|
||||
&["FIXED ( 384518.16, 2, FALSE )", "FIXED ( 4392768.29, 0, TRUE )", "FIXED ( 6741548.73, -2 )"],
|
||||
),
|
||||
spec(
|
||||
"FORMAT",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
3,
|
||||
&[required("Value", ParamKind::Any), required("Format", ParamKind::Text), optional("LocaleName", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Any, ParamKind::Text]), overload(&[ParamKind::Any, ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
DQ_RESTRICTED,
|
||||
"Formats a value as text using a Visual Basic (OLE Automation) format string or one of \
|
||||
the predefined numeric and date/time format names; unknown strings are treated as a \
|
||||
custom format or literal. The result is always text, and BLANK produces an empty string. \
|
||||
Month and weekday names and separators follow the model locale, which the optional \
|
||||
LocaleName overrides where the host supports that argument.",
|
||||
&["FORMAT ( 0.742, \"Percent\" )", "FORMAT ( DATE ( 2019, 3, 28 ), \"yyyy-mm-dd\" )", "FORMAT ( 1234.567, \"$#,0.00\", \"en-US\" )"],
|
||||
),
|
||||
spec(
|
||||
"LEFT",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
2,
|
||||
&[required("Text", ParamKind::Text), optional("NumberOfCharacters", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text]), overload(&[ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns the first NumberOfCharacters characters of a text value; the count defaults to 1. \
|
||||
It is intended for fixed-position extraction. Characters are counted as Unicode code \
|
||||
points, and no case or locale conversion is applied to the result.",
|
||||
&["LEFT ( \"DAX is so cool!\", 3 )", "LEFT ( Customer[Customer Name] )"],
|
||||
),
|
||||
spec(
|
||||
"LEN",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Character count of a text value, spaces included. Characters are Unicode code points, \
|
||||
so a character outside the Basic Multilingual Plane counts as one.",
|
||||
&["LEN ( \"DAX is so cool!\" )", "LEN ( Customer[Customer Name] )"],
|
||||
),
|
||||
spec(
|
||||
"LOWER",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Converts every letter in a text value to lowercase and returns the result. Case mapping \
|
||||
follows Unicode rules and is locale-sensitive for some scripts, such as the Turkish \
|
||||
dotted and dotless I, while digits and symbols are left unchanged.",
|
||||
&["LOWER ( \"DAX is SO cool!\" )", "LOWER ( Customer[CountryRegion] )"],
|
||||
),
|
||||
spec(
|
||||
"MID",
|
||||
FunctionCategory::Text,
|
||||
3,
|
||||
3,
|
||||
&[required("Text", ParamKind::Text), required("StartPosition", ParamKind::Number), required("NumberOfCharacters", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns NumberOfCharacters characters from a text value starting at the 1-based \
|
||||
StartPosition. If the requested length extends past the end of the text only the \
|
||||
remaining characters are returned. Positions and lengths are counted in Unicode code \
|
||||
points, and no case conversion is applied.",
|
||||
&["MID ( \"DAX is so cool!\", 11, 4 )", "MID ( \"123-45-6789\", 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"REPLACE",
|
||||
FunctionCategory::Text,
|
||||
4,
|
||||
4,
|
||||
&[
|
||||
required("OldText", ParamKind::Text),
|
||||
required("StartPosition", ParamKind::Number),
|
||||
required("NumberOfCharacters", ParamKind::Number),
|
||||
required("NewText", ParamKind::Text),
|
||||
],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Number, ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
DQ_RESTRICTED,
|
||||
"Replaces a fixed run of characters: NumberOfCharacters characters starting at the \
|
||||
1-based StartPosition are replaced by NewText, whose length need not match the removed \
|
||||
text. Because the position is explicit there is no searching, so case and locale do not \
|
||||
affect the match; positions are counted in Unicode code points.",
|
||||
&["REPLACE ( \"DAX is so cool!\", 11, 4, \"fantastic\" )", "REPLACE ( \"123-45-6789\", 1, 3, \"XXX\" )"],
|
||||
),
|
||||
spec(
|
||||
"REPT",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
2,
|
||||
&[required("Text", ParamKind::Text), required("NumberOfTimes", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Repeats a text value NumberOfTimes times and returns the concatenation. A count of zero \
|
||||
returns an empty string, a fractional count is truncated to an integer, and the \
|
||||
result may not exceed 32,767 characters or the function raises an error. The text is \
|
||||
repeated verbatim, without case or locale conversion.",
|
||||
&["REPT ( \"?\", 3 )", "REPT ( \"0\", 5 )"],
|
||||
),
|
||||
spec(
|
||||
"RIGHT",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
2,
|
||||
&[required("Text", ParamKind::Text), optional("NumberOfCharacters", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text]), overload(&[ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns the last NumberOfCharacters characters of a text value; the count defaults to 1. \
|
||||
It is intended for fixed-position extraction from the end of the text. Counting is by \
|
||||
Unicode code point, and no case conversion is applied.",
|
||||
&["RIGHT ( \"DAX is so cool!\", 5 )", "RIGHT ( Customer[Customer Code], 4 )"],
|
||||
),
|
||||
spec(
|
||||
"SEARCH",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("FindText", ParamKind::Text),
|
||||
required("WithinText", ParamKind::Text),
|
||||
optional("StartPosition", ParamKind::Number),
|
||||
optional("NotFoundValue", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Returns the 1-based position of FindText inside WithinText, starting at StartPosition \
|
||||
(default 1). Unlike FIND the comparison ignores case but remains accent-sensitive, and \
|
||||
the search text treats `?` and `*` as wildcards with `~` as the escape character. If the \
|
||||
text is absent the function returns NotFoundValue when supplied, otherwise it raises an \
|
||||
error.",
|
||||
&["SEARCH ( \"red\", \"GridCraft Cell S100 Red\" )", "SEARCH ( \"cell*s100\", \"GridCraft Cell S100 Blue\", 1, BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"SUBSTITUTE",
|
||||
FunctionCategory::Text,
|
||||
3,
|
||||
4,
|
||||
&[
|
||||
required("Text", ParamKind::Text),
|
||||
required("OldText", ParamKind::Text),
|
||||
required("NewText", ParamKind::Text),
|
||||
optional("InstanceNumber", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text, ParamKind::Number]),
|
||||
],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Replaces occurrences of OldText with NewText in a text value. With no InstanceNumber \
|
||||
every occurrence is replaced; otherwise only that occurrence is. Matching is \
|
||||
case-sensitive and accent-sensitive, so a difference in case leaves the text untouched, \
|
||||
and the search text is a literal substring rather than a pattern.",
|
||||
&["SUBSTITUTE ( \"GridCraft Cell S100 Red\", \"Cell\", \"Tablet\" )", "SUBSTITUTE ( \"GridCraft Cell S100 Red\", \"S\", \"X\", 1 )"],
|
||||
),
|
||||
spec(
|
||||
"TOCSV",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
4,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
optional("MaxRows", ParamKind::Number),
|
||||
optional("Delimiter", ParamKind::Text),
|
||||
optional("IncludeHeaders", ParamKind::Boolean),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Number]),
|
||||
overload(&[ParamKind::Table, ParamKind::Number, ParamKind::Text]),
|
||||
overload(&[ParamKind::Table, ParamKind::Number, ParamKind::Text, ParamKind::Boolean]),
|
||||
],
|
||||
ReturnType::String,
|
||||
ENGINE_ONLY,
|
||||
"Serializes a table's records as comma-separated text. MaxRows limits how many rows are \
|
||||
converted (default 10, negative for all), Delimiter is a non-empty constant field \
|
||||
separator (default a comma), and IncludeHeaders controls the header row (default TRUE). \
|
||||
Row order is unspecified and line endings are fixed; quotation marks are doubled, and a \
|
||||
value containing a quote or the delimiter is enclosed in quotes. Not available in Excel, \
|
||||
and not supported in DirectQuery calculated columns.",
|
||||
&["TOCSV ( Customer )", "TOCSV ( Customer, 3, \",\", FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"TOJSON",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), optional("MaxRows", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Table]), overload(&[ParamKind::Table, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
ENGINE_ONLY,
|
||||
"Serializes a table's records as a JSON document with header, rowCount and data members. \
|
||||
MaxRows limits how many rows are converted (default 10, negative for all), while values \
|
||||
keep their native types inside the JSON text. Row order is unspecified. Not available in \
|
||||
Excel, and not supported in DirectQuery calculated columns.",
|
||||
&["TOJSON ( Customer )", "TOJSON ( Customer, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"TRIM",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Removes leading and trailing spaces and collapses runs of spaces between words to a \
|
||||
single space. Only the 7-bit ASCII space (character 32) is removed: the non-breaking \
|
||||
space (character 160), tabs and other whitespace survive, which matters for text copied \
|
||||
from web pages.",
|
||||
&["TRIM ( \" DAX is awesome !!! \" )", "TRIM ( Customer[Customer Name] )"],
|
||||
),
|
||||
spec(
|
||||
"UNICHAR",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns the Unicode character for a numeric code point. A supplementary character is \
|
||||
one code point value. Code point 0 and values outside the allowable Unicode range \
|
||||
raise an error.",
|
||||
&["UNICHAR ( 9473 )", "UNICHAR ( 65 )"],
|
||||
),
|
||||
spec(
|
||||
"UNICODE",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Returns the numeric Unicode value of the first character of a text value; an empty \
|
||||
string raises an error. The engine counts Unicode code points, so a character outside \
|
||||
the Basic Multilingual Plane is returned as one value. Use UNICHAR for the inverse \
|
||||
conversion.",
|
||||
&["UNICODE ( \"A\" )", "UNICODE ( Customer[CountryRegion] )"],
|
||||
),
|
||||
spec(
|
||||
"UPPER",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Converts every letter in a text value to uppercase and returns the result. Case mapping \
|
||||
follows Unicode rules and is locale-sensitive for some scripts, such as the Turkish \
|
||||
dotted and dotless I, while digits and symbols are left unchanged.",
|
||||
&["UPPER ( \"dax is so cool!\" )", "UPPER ( Customer[CountryRegion] )"],
|
||||
),
|
||||
spec(
|
||||
"VALUE",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Decimal,
|
||||
STANDARD,
|
||||
"Converts text that represents a number, date or time into its numeric value. Parsing \
|
||||
accepts the constant, number and date/time formats the engine recognizes and follows the \
|
||||
model locale for separators and date order; text that cannot be parsed raises an error. \
|
||||
Because the engine also coerces text implicitly, VALUE mainly makes the conversion \
|
||||
explicit, and it should be protected with IF when the column may contain invalid text.",
|
||||
&["VALUE ( \"123.45678\" )", "VALUE ( \"2020-10-23\" )", "VALUE ( Sales[TextAmount] )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,716 @@
|
||||
//! Time intelligence functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! Every function in this category assumes a well-formed date table: a contiguous range of
|
||||
//! dates, one unique date/date-time column marked as the date table, and a relationship to the
|
||||
//! fact table based on that column (or the table explicitly marked as a date table). The
|
||||
//! optional `YearEndDate` arguments control fiscal years; the week-based functions and the
|
||||
//! calendar-only arguments introduced with model calendars require a calendar reference rather
|
||||
//! than a date column and are not available to Excel's embedded engine.
|
||||
|
||||
use super::{FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec};
|
||||
use crate::functions::FunctionCategory;
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"CLOSINGBALANCEMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression at the last date of the current month, after applying the \
|
||||
optional filter. It opens a month-to-date window only at its closing date, so a filter \
|
||||
on the date table is replaced by ENDOFMONTH; the date table must be contiguous and \
|
||||
marked as a date table for the relationship to be treated as a calendar.",
|
||||
&["CLOSINGBALANCEMONTH ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"CLOSINGBALANCEQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression at the last date of the current quarter, after applying the \
|
||||
optional filter. The quarter is derived from the marked date table, so missing dates or \
|
||||
a relationship not based on the date column invalidate the closing balance.",
|
||||
&["CLOSINGBALANCEQUARTER ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"CLOSINGBALANCEWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Evaluates the expression at the last date of the current week of a model calendar, \
|
||||
after applying the optional filter. Week boundaries come from the calendar definition, \
|
||||
so a plain date column is not accepted and the calendar must define week categories.",
|
||||
&["CLOSINGBALANCEWEEK ( [Sales Amount], Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"CLOSINGBALANCEYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("Expression", ParamKind::Expression),
|
||||
required("Dates", ParamKind::Date),
|
||||
optional("Filter", ParamKind::Any),
|
||||
optional("YearEndDate", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Expression, ParamKind::Date]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression at the last date of the current year, after applying the \
|
||||
optional filter. Pass YearEndDate to make the closing date follow a fiscal year; the \
|
||||
date table must contain every day of that fiscal year and stay marked as a date table.",
|
||||
&["CLOSINGBALANCEYEAR ( [Sales Amount], 'Date'[Date] )", "CLOSINGBALANCEYEAR ( [Sales Amount], 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"DATEADD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
3,
|
||||
5,
|
||||
&[
|
||||
required("Dates", ParamKind::Date),
|
||||
required("NumberOfIntervals", ParamKind::Number),
|
||||
required("Interval", ParamKind::Text),
|
||||
optional("Extension", ParamKind::Text),
|
||||
optional("Truncation", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text]),
|
||||
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Shifts the dates visible in the filter context by NumberOfIntervals units of Interval \
|
||||
(DAY, MONTH, QUARTER or YEAR) and returns the dates that exist in the date column. \
|
||||
Extension and Truncation are available only for a model calendar; for a date column \
|
||||
DATEADD accepts exactly three arguments. With a calendar, YEAR follows the calendar's \
|
||||
year definition, which may be a fiscal year.",
|
||||
&["DATEADD ( 'Date'[Date], -1, YEAR )", "DATEADD ( Gregorian, 1, MONTH )", "DATEADD ( Gregorian, 1, MONTH, EXTENDING, ANCHORED )"],
|
||||
),
|
||||
spec(
|
||||
"DATESBETWEEN",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
3,
|
||||
3,
|
||||
&[required("Dates", ParamKind::Date), required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the dates between two inclusive boundaries that exist in the date column. A \
|
||||
BLANK StartDate begins at MIN ( Dates ), a BLANK EndDate ends at MAX ( Dates ), and a \
|
||||
StartDate after EndDate returns an empty table. The result keeps the lineage of the \
|
||||
marked date table, so the date table must be contiguous for windows to be meaningful.",
|
||||
&["DATESBETWEEN ( 'Date'[Date], DATE ( 2008, 8, 1 ), DATE ( 2008, 8, 31 ) )"],
|
||||
),
|
||||
spec(
|
||||
"DATESINPERIOD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
4,
|
||||
5,
|
||||
&[
|
||||
required("Dates", ParamKind::Date),
|
||||
required("StartDate", ParamKind::Date),
|
||||
required("NumberOfIntervals", ParamKind::Number),
|
||||
required("Interval", ParamKind::Text),
|
||||
optional("EndBehavior", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Text]),
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the dates from StartDate over NumberOfIntervals units of Interval (DAY, WEEK, \
|
||||
MONTH, QUARTER or YEAR); a negative count looks backwards. BLANK StartDate uses the \
|
||||
minimum date in the column. EndBehavior (PRECISE or ENDALIGNED) is available only with \
|
||||
a model calendar; consider WINDOW when the interval arithmetic is not needed.",
|
||||
&[
|
||||
"DATESINPERIOD ( 'Date'[Date], MAX ( 'Date'[Date] ), -12, MONTH )",
|
||||
"DATESINPERIOD ( Gregorian, DATE ( 2008, 2, 29 ), -1, MONTH, ENDALIGNED )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"DATESMTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Month-to-date window: from the first day of the month up to whatever latest date the \
|
||||
filter context exposes, restricted to dates present in the column. This is syntax sugar \
|
||||
for DATESBETWEEN over the current month and requires a marked, contiguous date table.",
|
||||
&["DATESMTD ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"DATESQTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Quarter-to-date window: from the first day of the current quarter up to whatever latest \
|
||||
date the filter context exposes. Quarter boundaries come from the marked date table, so \
|
||||
an incomplete or unmarked date table breaks the window.",
|
||||
&["DATESQTD ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"DATESWTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the week-to-date window of a model calendar: dates from the first day of the \
|
||||
current week through the last visible date. Week numbering and the first day of the week \
|
||||
come from the calendar definition, not from the date column, and the function is not \
|
||||
available to Excel's DAX engine.",
|
||||
&["DATESWTD ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"DATESYTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Year-to-date window: from the start of the year up to whatever latest date the filter \
|
||||
context exposes, keeping only dates present in the column. YearEndDate selects a fiscal \
|
||||
year end (for example \"6/30\"); the date table must cover whole fiscal years and be \
|
||||
marked as a date table for the window to be correct.",
|
||||
&["DATESYTD ( 'Date'[Date] )", "DATESYTD ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date of the month visible in the filter context as a single-row table: \
|
||||
the latest date of that month that exists in the date column of the marked date table. Use it as a CALCULATE \
|
||||
modifier for semi-additive measures.",
|
||||
&["ENDOFMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date of the quarter visible in the filter context as a single-row table, \
|
||||
restricted to dates present in the date column. Quarter boundaries follow the marked \
|
||||
date table; a non-contiguous table can omit the quarter-end date.",
|
||||
&["ENDOFQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the last date of the week visible in the filter context for a model calendar. \
|
||||
The week definition, including the first day of the week, comes from the calendar, so a \
|
||||
date column is not accepted and Excel's DAX engine does not support the function.",
|
||||
&["ENDOFWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date of the year visible in the filter context as a single-row table. \
|
||||
YearEndDate selects a fiscal year end; without it the window is December 31. The date \
|
||||
table must be marked and must contain the resulting date.",
|
||||
&["ENDOFYEAR ( 'Date'[Date] )", "ENDOFYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"FIRSTDATE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date visible in the filter context, as a single-row table, restricted \
|
||||
to dates that exist in the date column. Blanks are considered, unlike FIRSTNONBLANK; \
|
||||
the column's table needs the date table marking so that time intelligence windows \
|
||||
behave correctly.",
|
||||
&["FIRSTDATE ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"FIRSTNONBLANK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Iterates the column in its sort order and returns the first value for which the \
|
||||
expression is not blank, as a single-column, single-row table. The column need not be a \
|
||||
date, but over a marked date table it defines the start of the time window; the iterator \
|
||||
can cause performance and memory issues on large models, so prefer an optimized pattern.",
|
||||
&["FIRSTNONBLANK ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"FIRSTNONBLANKVALUE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Returns the expression evaluated at the start of the visible time window: the first \
|
||||
value of the column whose expression is not blank, without returning a table. It is the \
|
||||
scalar counterpart of FIRSTNONBLANK and is commonly used for semi-additive measures over \
|
||||
a marked date table; the evaluation is an iterator, so large models pay per-row cost.",
|
||||
&["FIRSTNONBLANKVALUE ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"LASTDATE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date visible in the filter context, as a single-row table, restricted \
|
||||
to dates that exist in the date column. It is the anchor of many YTD windows; a missing \
|
||||
or unmarked date table makes the result follow partial selections instead of the calendar.",
|
||||
&["LASTDATE ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"LASTNONBLANK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Iterates the column in its sort order and returns the last value for which the \
|
||||
expression is not blank, as a single-column, single-row table. The column need not be a \
|
||||
date, but over a marked date table it defines the end of the time window; the iterator \
|
||||
can be expensive, so dax.guide recommends optimized semi-additive patterns.",
|
||||
&["LASTNONBLANK ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"LASTNONBLANKVALUE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Returns the expression evaluated at the end of the visible time window: the last value \
|
||||
of the column whose expression is not blank, without returning a table. It is the scalar \
|
||||
counterpart of LASTNONBLANK and a typical semi-additive pattern over a marked date \
|
||||
table; the per-row iteration is costly on large models.",
|
||||
&["LASTNONBLANKVALUE ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTDAY",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the day after the last date visible in the filter context, as a single-row table \
|
||||
restricted to dates present in the date column. Because the date table must be \
|
||||
contiguous, a missing next day yields an empty table.",
|
||||
&["NEXTDAY ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the month after the last date visible in the filter context. The \
|
||||
month boundaries come from the marked date table, so gaps in the calendar produce \
|
||||
incomplete results and a bad relationship makes the window follow the wrong selection.",
|
||||
&["NEXTMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the quarter after the last date visible in the filter context. The \
|
||||
quarter is derived from the marked date table; the result keeps the date column lineage \
|
||||
and excludes dates absent from the calendar.",
|
||||
&["NEXTQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns all dates of the week after the last date visible in the filter context, using \
|
||||
the week definition of a model calendar. A plain date column cannot supply week \
|
||||
boundaries, and Excel's embedded DAX engine does not expose the calendar-based function.",
|
||||
&["NEXTWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the year after the last date visible in the filter context. \
|
||||
YearEndDate shifts the year to a fiscal calendar; the date table must contain the whole \
|
||||
following year, be contiguous and be marked as a date table.",
|
||||
&["NEXTYEAR ( 'Date'[Date] )", "NEXTYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression on the final date of the preceding month, after applying the \
|
||||
optional filter. The opening balance uses the marked date table's month boundaries, so \
|
||||
the relationship and date coverage must be valid or the window slides on partial data.",
|
||||
&["OPENINGBALANCEMONTH ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression on the final date of the preceding quarter, after applying the \
|
||||
optional filter. Quarter boundaries come from the marked date table; an unmarked table \
|
||||
or a relationship not based on the date column changes the opening period.",
|
||||
&["OPENINGBALANCEQUARTER ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Evaluates the expression on the final date of the preceding week of a model calendar, \
|
||||
after applying the optional filter. The calendar defines the week, so a date column is \
|
||||
not accepted and the function is unavailable to Excel's DAX engine.",
|
||||
&["OPENINGBALANCEWEEK ( [Sales Amount], Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("Expression", ParamKind::Expression),
|
||||
required("Dates", ParamKind::Date),
|
||||
optional("Filter", ParamKind::Any),
|
||||
optional("YearEndDate", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Expression, ParamKind::Date]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression on the final date of the preceding year, after applying the \
|
||||
optional filter. YearEndDate aligns the opening balance with a fiscal year; the date \
|
||||
table must cover entire fiscal years and be marked as a date table.",
|
||||
&["OPENINGBALANCEYEAR ( [Sales Amount], 'Date'[Date] )", "OPENINGBALANCEYEAR ( [Sales Amount], 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"PARALLELPERIOD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
3,
|
||||
3,
|
||||
&[required("Dates", ParamKind::Date), required("NumberOfIntervals", ParamKind::Number), required("Interval", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Moves the visible first and last dates by NumberOfIntervals units of MONTH, QUARTER or \
|
||||
YEAR, then returns the contiguous dates between the moved boundaries, expanding partial \
|
||||
periods to complete ones. Only dates in the marked date column appear, so a \
|
||||
discontinuous calendar leaves gaps.",
|
||||
&["PARALLELPERIOD ( 'Date'[Date], -1, YEAR )", "PARALLELPERIOD ( 'Date'[Date], 0, MONTH )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSDAY",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the day before the first date visible in the filter context, as a single-row \
|
||||
table restricted to dates present in the date column. The marked date table must be \
|
||||
contiguous; otherwise the previous day may not exist in the model.",
|
||||
&["PREVIOUSDAY ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the month before the first date visible in the filter context. Month \
|
||||
boundaries come from the marked date table; gaps in the calendar or an incorrect \
|
||||
relationship make the previous month incomplete.",
|
||||
&["PREVIOUSMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the quarter before the first date visible in the filter context. The \
|
||||
quarter is derived from the marked date table, so the table must contain every day of \
|
||||
the previous quarter for the window to be complete.",
|
||||
&["PREVIOUSQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns all dates of the week before the first date visible in the filter context, using \
|
||||
a model calendar's week definition. Week boundaries are calendar metadata, so a date \
|
||||
column is not accepted and Excel's DAX engine cannot call the function.",
|
||||
&["PREVIOUSWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the year before the first date visible in the filter context, \
|
||||
optionally aligned to a fiscal year end. The marked date table must include the whole \
|
||||
previous year, including leap days, for the window to be complete.",
|
||||
&["PREVIOUSYEAR ( 'Date'[Date] )", "PREVIOUSYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"SAMEPERIODLASTYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the dates of the same period one year earlier, preserving the number of days \
|
||||
rather than the month boundaries. It is syntax sugar for DATEADD ( Dates, -1, YEAR ) and \
|
||||
relies on a marked, contiguous date table; a fiscal year requires adapting the offset \
|
||||
or the calendar definition.",
|
||||
&["SAMEPERIODLASTYEAR ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date of the month visible in the filter context, as a single-row table \
|
||||
restricted to dates in the date column. The marked date table must contain the month's \
|
||||
first day for the result to be non-empty.",
|
||||
&["STARTOFMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date of the quarter visible in the filter context, as a single-row \
|
||||
table restricted to dates in the date column. Quarter boundaries follow the marked date \
|
||||
table, so an incomplete calendar can omit the first day.",
|
||||
&["STARTOFQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the first date of the week visible in the filter context for a model calendar. \
|
||||
The calendar defines the first day of the week, so a date column is not accepted and the \
|
||||
function is not available to Excel's embedded DAX engine.",
|
||||
&["STARTOFWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date of the year visible in the filter context as a single-row table. \
|
||||
YearEndDate shifts the start to a fiscal year; the date table must be marked and include \
|
||||
every day from the fiscal-year start through year end.",
|
||||
&["STARTOFYEAR ( 'Date'[Date] )", "STARTOFYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALMTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression over the month-to-date window, from the first day of the month \
|
||||
through the last visible date, after applying the optional filter. It is syntax sugar \
|
||||
for CALCULATE with DATESMTD and depends on a marked, contiguous date table.",
|
||||
&["TOTALMTD ( SUM ( Sales[Amount] ), 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALQTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression over the quarter-to-date window, from the first day of the \
|
||||
quarter through the last visible date, after applying the optional filter. It is syntax \
|
||||
sugar for CALCULATE with DATESQTD and requires the date table to be marked.",
|
||||
&["TOTALQTD ( SUM ( Sales[Amount] ), 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALWTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Evaluates the expression over the week-to-date window defined by a model calendar, from \
|
||||
the first day of the week through the last visible date, after applying the optional \
|
||||
filter. Week boundaries come from the calendar, and Excel's DAX engine does not support \
|
||||
the function.",
|
||||
&["TOTALWTD ( SUM ( Sales[Amount] ), Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALYTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("Expression", ParamKind::Expression),
|
||||
required("Dates", ParamKind::Date),
|
||||
optional("Filter", ParamKind::Any),
|
||||
optional("YearEndDate", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Expression, ParamKind::Date]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression over the year-to-date window, from the first day of the year \
|
||||
through the last visible date, after applying the optional filter. It is syntax sugar \
|
||||
for CALCULATE with DATESYTD; YearEndDate selects a fiscal year and the date table must \
|
||||
be marked and cover whole fiscal years.",
|
||||
&[
|
||||
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date] )",
|
||||
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date], Sales[Region] = \"US\" )",
|
||||
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,295 @@
|
||||
//! Visual calculation functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! All functions in this category are Power BI visual calculation functions: they can only be
|
||||
//! used in the visual calculation editor and are rejected in measures, calculated columns and
|
||||
//! calculated tables. The `axis` parameter is defined by the VISUAL SHAPE query syntax emitted
|
||||
//! by the visual calculation feature, so `ROWS` and `COLUMNS` appear in examples as bare names.
|
||||
|
||||
use super::{FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Power BI visual calculations are not available to Excel's embedded engine, and the
|
||||
/// DirectQuery restrictions listed for measures and calculated columns do not apply because
|
||||
/// the functions cannot be used there.
|
||||
const VISUAL: FunctionFlags = FunctionFlags::new(false, false, false, false, false);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"COLLAPSE",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Expression", ParamKind::Any),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("Column", ParamKind::Column),
|
||||
optional("N", ParamKind::Number),
|
||||
],
|
||||
&[overload(&[ParamKind::Any]), variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Retrieves a context with the detail levels above the current one removed, or returns its \
|
||||
first argument evaluated in that coarser context. Navigation-only calls (an axis or a \
|
||||
list of columns) can be used inside CALCULATE. Available only in Power BI visual \
|
||||
calculations; `N` defaults to one level.",
|
||||
&[
|
||||
"COLLAPSE ( [Sales Amount], ROWS )",
|
||||
"COLLAPSE ( [Sales Amount], ROWS, 2 )",
|
||||
"COLLAPSE ( [Sales Amount], [Month] )",
|
||||
"COLLAPSE ( ROWS, 1 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"COLLAPSEALL",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
2,
|
||||
&[optional("Expression", ParamKind::Any), required("Axis", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Removes every detail level along an axis, returning the expression evaluated at the \
|
||||
highest level of that axis. The inverse of EXPANDALL. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["COLLAPSEALL ( [Sales Amount], ROWS )", "COLLAPSEALL ( ROWS )", "COLLAPSEALL ( [Sales Amount], COLUMNS )"],
|
||||
),
|
||||
spec(
|
||||
"EXPAND",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Expression", ParamKind::Any),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("Column", ParamKind::Column),
|
||||
optional("N", ParamKind::Number),
|
||||
],
|
||||
&[overload(&[ParamKind::Any]), variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Retrieves a context with additional detail levels compared to the current one, or \
|
||||
returns its first argument evaluated in that finer context. Navigation-only calls (an \
|
||||
axis or a list of columns) can be used inside CALCULATE. Available only in Power BI \
|
||||
visual calculations; `N` defaults to one level.",
|
||||
&["EXPAND ( [Sales Amount], ROWS )", "EXPAND ( [Sales Amount], ROWS, 2 )", "EXPAND ( [Sales Amount], [Month] )"],
|
||||
),
|
||||
spec(
|
||||
"EXPANDALL",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
2,
|
||||
&[optional("Expression", ParamKind::Any), required("Axis", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Adds every detail level along an axis, returning the expression evaluated at the lowest \
|
||||
level of that axis. The inverse of COLLAPSEALL. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["EXPANDALL ( [Sales Amount], ROWS )", "EXPANDALL ( ROWS )", "EXPANDALL ( [Sales Amount], COLUMNS )"],
|
||||
),
|
||||
spec(
|
||||
"FIRST",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
5,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column in the first row of an axis or partition. OrderBy columns \
|
||||
define the sort order; Blanks accepts DEFAULT, FIRST or LAST and Reset accepts NONE, \
|
||||
LOWESTPARENT, HIGHESTPARENT or a level number. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["FIRST ( [Sales Amount] )", "FIRST ( [Sales Amount], ROWS )", "FIRST ( [Sales Amount], ROWS, [Month], DEFAULT, NONE )"],
|
||||
),
|
||||
spec(
|
||||
"LAST",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
5,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column in the last row of an axis or partition. OrderBy columns \
|
||||
define the sort order; Blanks accepts DEFAULT, FIRST or LAST and Reset accepts NONE, \
|
||||
LOWESTPARENT, HIGHESTPARENT or a level number. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["LAST ( [Sales Amount] )", "LAST ( [Sales Amount], ROWS )", "LAST ( [Sales Amount], ROWS, [Month], FIRST, LOWESTPARENT )"],
|
||||
),
|
||||
spec(
|
||||
"MOVINGAVERAGE",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
2,
|
||||
7,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
required("WindowSize", ParamKind::Number),
|
||||
optional("IncludeCurrent", ParamKind::Boolean),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Numeric,
|
||||
VISUAL,
|
||||
"Calculates the average of the values in a sliding window of WindowSize rows along an \
|
||||
axis. IncludeCurrent defaults to TRUE; when FALSE the window holds the previous \
|
||||
WindowSize rows. OrderBy, Blanks and Reset behave as in FIRST. Available only in Power \
|
||||
BI visual calculations.",
|
||||
&[
|
||||
"MOVINGAVERAGE ( [Sales Amount], 6 )",
|
||||
"MOVINGAVERAGE ( [Sales Amount], 3, FALSE )",
|
||||
"MOVINGAVERAGE ( [Sales Amount], 6, TRUE, ROWS )",
|
||||
"MOVINGAVERAGE ( [Sales Amount], 12, TRUE, ROWS, [Month], DEFAULT, NONE )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"NEXT",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
6,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Steps", ParamKind::Number),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column the given number of rows after the current row on an axis. \
|
||||
Steps defaults to 1 and must be at least 1. OrderBy, Blanks and Reset behave as in \
|
||||
FIRST. Available only in Power BI visual calculations.",
|
||||
&["NEXT ( [Sales Amount] )", "NEXT ( [Sales Amount], 1, ROWS )", "NEXT ( [Sales Amount], 2, ROWS, [Month], LAST, HIGHESTPARENT )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUS",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
6,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Steps", ParamKind::Number),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column the given number of rows before the current row on an \
|
||||
axis. Steps defaults to 1 and is negated internally, so it must be at least 1. OrderBy, \
|
||||
Blanks and Reset behave as in FIRST. Available only in Power BI visual calculations.",
|
||||
&[
|
||||
"PREVIOUS ( [Sales Amount] )",
|
||||
"PREVIOUS ( [Sales Amount], 1, ROWS )",
|
||||
"PREVIOUS ( [Sales Amount], 2, ROWS, [Month], DEFAULT, LOWESTPARENT )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"RANGE",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
6,
|
||||
&[
|
||||
required("Step", ParamKind::Number),
|
||||
optional("IncludeCurrent", ParamKind::Boolean),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
VISUAL,
|
||||
"Returns the interval of rows within an axis that starts Step rows before (negative Step) \
|
||||
or after (non-negative Step) the current row, optionally including the current row. The \
|
||||
result is normally passed to CALCULATE. Available only in Power BI visual calculations.",
|
||||
&["RANGE ( 6 )", "RANGE ( -5, TRUE, ROWS )", "RANGE ( 12, FALSE, ROWS, [Month], DEFAULT, NONE )"],
|
||||
),
|
||||
spec(
|
||||
"RUNNINGSUM",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
5,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Numeric,
|
||||
VISUAL,
|
||||
"Calculates the cumulative sum of a column from the start of the axis or partition up to \
|
||||
the current row. OrderBy, Blanks and Reset behave as in FIRST. Available only in Power \
|
||||
BI visual calculations.",
|
||||
&["RUNNINGSUM ( [Sales Amount] )", "RUNNINGSUM ( [Sales Amount], ROWS )", "RUNNINGSUM ( [Sales Amount], ROWS, [Month], DEFAULT, NONE )"],
|
||||
),
|
||||
];
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,553 @@
|
||||
//! Tokenizer for DAX expressions.
|
||||
//!
|
||||
//! Spans are byte offsets into the source. Keywords are recognised case-insensitively; the
|
||||
//! parser keeps the source spelling of identifiers and function names. `TRUE`/`FALSE` stay
|
||||
//! identifiers here so the parser can tell the boolean literal from a call such as `TRUE()`.
|
||||
//!
|
||||
//! Numeric tokens are typed: digit-only text becomes [`TokenKind::Integer`] when it fits `i64`,
|
||||
//! while a decimal point or exponent becomes [`TokenKind::Decimal`]. `dt"..."` text is
|
||||
//! validated here and emitted as [`TokenKind::DateTime`]. Overflow and malformed date/time
|
||||
//! literals are [`LexError`] values carrying the literal's span.
|
||||
//!
|
||||
//! Statement punctuation is lexed here too: `:` ([`TokenKind::Colon`]) separates a function
|
||||
//! parameter's name from its annotation, `@name` becomes [`TokenKind::AtName`] for `START AT`
|
||||
//! parameters, and `;` ([`TokenKind::Semicolon`]) is the optional trailing query terminator.
|
||||
//! Statement keywords such as `DEFINE` and `MEASURE` stay plain [`TokenKind::Ident`] tokens and
|
||||
//! are matched case-insensitively by the parser, so they remain available as identifier text
|
||||
//! wherever the grammar does not reserve them.
|
||||
|
||||
use chrono::NaiveDate;
|
||||
|
||||
use crate::ast::{DateTimeLiteral, Span};
|
||||
|
||||
/// Longest expression accepted by [`crate::parse_expression`], in bytes. Mirrors DAX's
|
||||
/// expression limit and bounds the size of the tree a long operator chain can build.
|
||||
pub const MAX_INPUT_LEN: usize = 8_192;
|
||||
|
||||
/// Longest query accepted by [`crate::parse_query`], in bytes. A query has no documented length
|
||||
/// limit comparable to the expression bound, so it gets a larger, independent ceiling that still
|
||||
/// bounds memory for `DEFINE` blocks and repeated `EVALUATE` statements.
|
||||
pub const MAX_QUERY_LEN: usize = 1_048_576;
|
||||
|
||||
/// A lexical token.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TokenKind {
|
||||
/// A digit-only literal that fits in `i64`, e.g. `42`.
|
||||
Integer(i64),
|
||||
/// A literal with a decimal point or exponent, e.g. `3.14`, `.5`, `1e3`.
|
||||
Decimal(f64),
|
||||
/// A validated `dt"..."` date/time literal.
|
||||
DateTime(DateTimeLiteral),
|
||||
String(String),
|
||||
/// A bare identifier, function name or table name (`Sales`, `STDEV.P`, `TRUE`).
|
||||
Ident(String),
|
||||
/// A single-quoted table name, with `''` escapes resolved.
|
||||
QuotedIdent(String),
|
||||
/// A bracketed column name, with `]]` escapes resolved.
|
||||
BracketIdent(String),
|
||||
/// The `NOT` operator (case-insensitive).
|
||||
Not,
|
||||
/// The `IN` operator (case-insensitive).
|
||||
In,
|
||||
/// The `EVALUATE` statement keyword (case-insensitive).
|
||||
Evaluate,
|
||||
Plus,
|
||||
Minus,
|
||||
Star,
|
||||
Slash,
|
||||
Caret,
|
||||
Amp,
|
||||
Eq,
|
||||
StrictEq,
|
||||
NotEq,
|
||||
Lt,
|
||||
Gt,
|
||||
Le,
|
||||
Ge,
|
||||
AndAnd,
|
||||
OrOr,
|
||||
/// `=>`, used by `DEFINE FUNCTION` definitions.
|
||||
Arrow,
|
||||
/// `:` between a function parameter name and its type annotation.
|
||||
Colon,
|
||||
/// `@name`, an XMLA statement parameter reference in `START AT`.
|
||||
AtName(String),
|
||||
/// `;`, accepted only as an optional trailing statement terminator.
|
||||
Semicolon,
|
||||
LParen,
|
||||
RParen,
|
||||
LBrace,
|
||||
RBrace,
|
||||
Comma,
|
||||
Eof,
|
||||
}
|
||||
|
||||
/// A token and its byte span.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Token {
|
||||
pub kind: TokenKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message} at bytes {}..{}", span.start, span.end)]
|
||||
pub struct LexError {
|
||||
pub message: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl LexError {
|
||||
fn new(message: impl Into<String>, span: Span) -> Self {
|
||||
LexError { message: message.into(), span }
|
||||
}
|
||||
}
|
||||
|
||||
/// Tokenizes `src` and appends an [`TokenKind::Eof`] token at `src.len()`.
|
||||
///
|
||||
/// Whitespace is insignificant and comments (`//`, `--` to end of line, and `/* ... */`) are
|
||||
/// skipped. A block comment does not nest.
|
||||
#[allow(clippy::cognitive_complexity)]
|
||||
// A hand-written scanner: one loop with a case per token kind.
|
||||
pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
|
||||
let chars: Vec<(usize, char)> = src.char_indices().collect();
|
||||
let n = chars.len();
|
||||
let ch = |i: usize| chars.get(i).map(|(_, c)| *c);
|
||||
let pos = |i: usize| chars.get(i).map(|(p, _)| *p).unwrap_or(src.len());
|
||||
let mut out: Vec<Token> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
|
||||
while i < n {
|
||||
let start = pos(i);
|
||||
let Some(c) = ch(i) else { break };
|
||||
match c {
|
||||
c if c.is_whitespace() => {
|
||||
i += 1;
|
||||
}
|
||||
'/' if ch(i + 1) == Some('/') => {
|
||||
i += 2;
|
||||
while ch(i).is_some_and(|c| c != '\n' && c != '\r') {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'-' if ch(i + 1) == Some('-') => {
|
||||
i += 2;
|
||||
while ch(i).is_some_and(|c| c != '\n' && c != '\r') {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'/' if ch(i + 1) == Some('*') => {
|
||||
let mut j = i + 2;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => {
|
||||
return Err(LexError::new("unterminated block comment", Span::new(start, src.len())));
|
||||
}
|
||||
Some('*') if ch(j + 1) == Some('/') => {
|
||||
j += 2;
|
||||
break;
|
||||
}
|
||||
Some(_) => j += 1,
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
'"' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => return Err(LexError::new("unterminated string literal", Span::new(start, src.len()))),
|
||||
Some('"') if ch(j + 1) == Some('"') => {
|
||||
text.push('"');
|
||||
j += 2;
|
||||
}
|
||||
Some('"') => {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
text.push(c);
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(Token { kind: TokenKind::String(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'\'' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => return Err(LexError::new("unterminated quoted identifier", Span::new(start, src.len()))),
|
||||
Some('\'') if ch(j + 1) == Some('\'') => {
|
||||
text.push('\'');
|
||||
j += 2;
|
||||
}
|
||||
Some('\'') => {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
text.push(c);
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Err(LexError::new("empty quoted identifier", Span::new(start, pos(j))));
|
||||
}
|
||||
out.push(Token { kind: TokenKind::QuotedIdent(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'[' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => return Err(LexError::new("unterminated bracketed identifier", Span::new(start, src.len()))),
|
||||
Some(']') if ch(j + 1) == Some(']') => {
|
||||
text.push(']');
|
||||
j += 2;
|
||||
}
|
||||
Some(']') => {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
text.push(c);
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Err(LexError::new("empty bracketed identifier", Span::new(start, pos(j))));
|
||||
}
|
||||
out.push(Token { kind: TokenKind::BracketIdent(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'0'..='9' | '.' if c != '.' || ch(i + 1).is_some_and(|d| d.is_ascii_digit()) => {
|
||||
let mut j = i;
|
||||
let mut text = String::new();
|
||||
// A digit-only literal is an Integer; a decimal point or exponent makes it a
|
||||
// Decimal. The sign is always a unary operator, never part of the token.
|
||||
let mut is_decimal = c == '.';
|
||||
if c == '.' {
|
||||
text.push_str("0.");
|
||||
j += 1;
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
} else {
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if ch(j) == Some('.') {
|
||||
is_decimal = true;
|
||||
text.push('.');
|
||||
j += 1;
|
||||
let fraction = j;
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if j == fraction {
|
||||
// `1.` / `1.e3`: keep the literal parseable.
|
||||
text.push('0');
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(ch(j), Some('e' | 'E')) {
|
||||
is_decimal = true;
|
||||
text.push('e');
|
||||
j += 1;
|
||||
if matches!(ch(j), Some('+' | '-')) {
|
||||
if let Some(sign) = ch(j) {
|
||||
text.push(sign);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
let digits = j;
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if j == digits {
|
||||
return Err(LexError::new("numeric literal has no exponent digits", Span::new(start, pos(j))));
|
||||
}
|
||||
}
|
||||
if ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
|
||||
return Err(LexError::new("invalid numeric literal", Span::new(start, pos(j + 1))));
|
||||
}
|
||||
let span = Span::new(start, pos(j));
|
||||
let kind = if is_decimal {
|
||||
let value = text.parse::<f64>().map_err(|_| LexError::new("invalid numeric literal", span))?;
|
||||
if !value.is_finite() {
|
||||
return Err(LexError::new("decimal literal is out of range", span));
|
||||
}
|
||||
TokenKind::Decimal(value)
|
||||
} else {
|
||||
let value =
|
||||
text.parse::<i64>().map_err(|_| LexError::new("integer literal is out of range for a 64-bit signed integer", span))?;
|
||||
TokenKind::Integer(value)
|
||||
};
|
||||
out.push(Token { kind, span });
|
||||
i = j;
|
||||
}
|
||||
c if c.is_alphabetic() || c == '_' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i;
|
||||
while ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
|
||||
if let Some(c) = ch(j) {
|
||||
text.push(c);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
// `dt` immediately followed by a double-quoted string is a date/time literal.
|
||||
// Whitespace between the prefix and the quote is not allowed, so `dt "..."` is
|
||||
// two tokens and fails to parse. The prefix is case-insensitive like other DAX
|
||||
// keywords; the printer canonicalises it to lowercase `dt`.
|
||||
if text.eq_ignore_ascii_case("dt") && ch(j) == Some('"') {
|
||||
let mut content = String::new();
|
||||
let mut k = j + 1;
|
||||
loop {
|
||||
match ch(k) {
|
||||
None => {
|
||||
return Err(LexError::new("unterminated date/time literal", Span::new(start, src.len())));
|
||||
}
|
||||
Some('"') => {
|
||||
k += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
content.push(c);
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let span = Span::new(start, pos(k));
|
||||
let value = parse_datetime_literal(&content).map_err(|message| LexError::new(message, span))?;
|
||||
out.push(Token { kind: TokenKind::DateTime(value), span });
|
||||
i = k;
|
||||
continue;
|
||||
}
|
||||
let kind = if text.eq_ignore_ascii_case("NOT") {
|
||||
TokenKind::Not
|
||||
} else if text.eq_ignore_ascii_case("IN") {
|
||||
TokenKind::In
|
||||
} else if text.eq_ignore_ascii_case("EVALUATE") {
|
||||
TokenKind::Evaluate
|
||||
} else {
|
||||
TokenKind::Ident(text)
|
||||
};
|
||||
out.push(Token { kind, span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'+' => {
|
||||
out.push(Token { kind: TokenKind::Plus, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'-' => {
|
||||
out.push(Token { kind: TokenKind::Minus, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'*' => {
|
||||
out.push(Token { kind: TokenKind::Star, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'/' => {
|
||||
out.push(Token { kind: TokenKind::Slash, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'^' => {
|
||||
out.push(Token { kind: TokenKind::Caret, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'&' if ch(i + 1) == Some('&') => {
|
||||
out.push(Token { kind: TokenKind::AndAnd, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'&' => {
|
||||
out.push(Token { kind: TokenKind::Amp, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'|' if ch(i + 1) == Some('|') => {
|
||||
out.push(Token { kind: TokenKind::OrOr, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'|' => return Err(LexError::new("unexpected `|`; the DAX logical OR operator is `||`", Span::new(start, pos(i + 1)))),
|
||||
'=' if ch(i + 1) == Some('=') => {
|
||||
out.push(Token { kind: TokenKind::StrictEq, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'=' if ch(i + 1) == Some('>') => {
|
||||
out.push(Token { kind: TokenKind::Arrow, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'=' => {
|
||||
out.push(Token { kind: TokenKind::Eq, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'<' if ch(i + 1) == Some('>') => {
|
||||
out.push(Token { kind: TokenKind::NotEq, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'<' if ch(i + 1) == Some('=') => {
|
||||
out.push(Token { kind: TokenKind::Le, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'<' => {
|
||||
out.push(Token { kind: TokenKind::Lt, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'>' if ch(i + 1) == Some('=') => {
|
||||
out.push(Token { kind: TokenKind::Ge, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'>' => {
|
||||
out.push(Token { kind: TokenKind::Gt, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'(' => {
|
||||
out.push(Token { kind: TokenKind::LParen, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
')' => {
|
||||
out.push(Token { kind: TokenKind::RParen, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'{' => {
|
||||
out.push(Token { kind: TokenKind::LBrace, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'}' => {
|
||||
out.push(Token { kind: TokenKind::RBrace, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
',' => {
|
||||
out.push(Token { kind: TokenKind::Comma, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
':' => {
|
||||
out.push(Token { kind: TokenKind::Colon, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
';' => {
|
||||
out.push(Token { kind: TokenKind::Semicolon, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'@' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
while ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
|
||||
if let Some(c) = ch(j) {
|
||||
text.push(c);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Err(LexError::new("expected a parameter name after `@`", Span::new(start, pos(j))));
|
||||
}
|
||||
out.push(Token { kind: TokenKind::AtName(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
other => {
|
||||
return Err(LexError::new(format!("unexpected character `{other}`"), Span::new(start, pos(i + 1))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out.push(Token { kind: TokenKind::Eof, span: Span::new(src.len(), src.len()) });
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Validates the content of a `dt"..."` literal and splits it into components.
|
||||
///
|
||||
/// Accepted forms are `YYYY-MM-DD`, `YYYY-MM-DDThh:mm:ss` and `YYYY-MM-DD hh:mm:ss`. Date and
|
||||
/// time components may be unpadded (`dt"2015-1-9T2:3:0"`), matching Microsoft's documented
|
||||
/// example. Timezone offsets, fractional seconds, time-only values and invalid calendar dates
|
||||
/// are rejected with a lexer error. The `dt` prefix itself is matched by the caller.
|
||||
fn parse_datetime_literal(text: &str) -> Result<DateTimeLiteral, String> {
|
||||
let (date, time) = if let Some((date, time)) = text.split_once('T') {
|
||||
(date, Some(time))
|
||||
} else if let Some((date, time)) = text.split_once(' ') {
|
||||
(date, Some(time))
|
||||
} else {
|
||||
(text, None)
|
||||
};
|
||||
|
||||
let (year, month, day) = parse_date(date)?;
|
||||
let (hour, minute, second) = match time {
|
||||
Some(time) => parse_time(time)?,
|
||||
None => (0, 0, 0),
|
||||
};
|
||||
Ok(DateTimeLiteral { year, month, day, hour, minute, second, has_time: time.is_some() })
|
||||
}
|
||||
|
||||
fn parse_date(text: &str) -> Result<(u32, u32, u32), String> {
|
||||
let mut parts = text.split('-');
|
||||
let year_text = parts.next().unwrap_or_default();
|
||||
let month_text = parts.next().unwrap_or_default();
|
||||
let day_text = parts.next().unwrap_or_default();
|
||||
if parts.next().is_some() || year_text.is_empty() || month_text.is_empty() || day_text.is_empty() {
|
||||
return Err("invalid date/time literal: the date must be YYYY-MM-DD".into());
|
||||
}
|
||||
if year_text.len() != 4 || month_text.len() > 2 || day_text.len() > 2 {
|
||||
return Err("invalid date/time literal: the date must be YYYY-MM-DD (unpadded month and day are allowed)".into());
|
||||
}
|
||||
let year = parse_component(year_text, "year")?;
|
||||
let month = parse_component(month_text, "month")?;
|
||||
let day = parse_component(day_text, "day")?;
|
||||
if year == 0 || year > 9999 {
|
||||
return Err("invalid date/time literal: the year must be between 0001 and 9999".into());
|
||||
}
|
||||
if !(1..=12).contains(&month) {
|
||||
return Err("invalid date/time literal: the month must be between 1 and 12".into());
|
||||
}
|
||||
// A date exists exactly when chrono can build it: that rejects day 0, 31 April and 29 February
|
||||
// of a common year without hand-written month lengths or leap-year math (AGENTS.md).
|
||||
if NaiveDate::from_ymd_opt(year as i32, month, day).is_none() {
|
||||
return Err("invalid date/time literal: the date is not a valid calendar date".into());
|
||||
}
|
||||
Ok((year, month, day))
|
||||
}
|
||||
|
||||
fn parse_time(text: &str) -> Result<(u32, u32, u32), String> {
|
||||
let mut parts = text.split(':');
|
||||
let hour_text = parts.next().unwrap_or_default();
|
||||
let minute_text = parts.next().unwrap_or_default();
|
||||
let second_text = parts.next().unwrap_or_default();
|
||||
if parts.next().is_some() || hour_text.is_empty() || minute_text.is_empty() || second_text.is_empty() {
|
||||
return Err("invalid date/time literal: the time must be hh:mm:ss".into());
|
||||
}
|
||||
if hour_text.len() > 2 || minute_text.len() > 2 || second_text.len() > 2 {
|
||||
return Err("invalid date/time literal: the time must be hh:mm:ss without fractional seconds".into());
|
||||
}
|
||||
let hour = parse_component(hour_text, "hour")?;
|
||||
let minute = parse_component(minute_text, "minute")?;
|
||||
let second = parse_component(second_text, "second")?;
|
||||
if hour > 23 || minute > 59 || second > 59 {
|
||||
return Err("invalid date/time literal: the time is out of range".into());
|
||||
}
|
||||
Ok((hour, minute, second))
|
||||
}
|
||||
|
||||
/// Parses one date/time component. Rejects signs, whitespace, fractional parts and everything
|
||||
/// else that is not an ASCII digit, so timezone offsets (`Z`, `+02:00`) and fractional seconds
|
||||
/// cannot slip through.
|
||||
fn parse_component(text: &str, unit: &str) -> Result<u32, String> {
|
||||
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(format!("invalid date/time literal: the {unit} must be digits"));
|
||||
}
|
||||
text.parse::<u32>().map_err(|_| format!("invalid date/time literal: the {unit} is out of range"))
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The DAX language: tokenizer, syntax tree, Pratt parser, canonical printer and static types.
|
||||
//!
|
||||
//! This crate covers the DAX expression grammar, the function catalog for every dax.guide category
|
||||
//! with static call validation, the static type surface (literal classification, inference and the documented
|
||||
//! operator result tables) and the DAX query statements: `DEFINE` (`MEASURE`, `COLUMN`, `TABLE`,
|
||||
//! `VAR`, `FUNCTION`, `MPARAMETER`), `EVALUATE`, `ORDER BY`, `START AT`, expression-level
|
||||
//! `VAR ... RETURN`, and `WITH VISUAL SHAPE` (`AXIS`, `GROUP`, `TOTAL`, `DENSIFY`). It also
|
||||
//! includes a model evaluator, a columnar model store and a PivotTable renderer. The evaluator materializes the model once into the columnar store and
|
||||
//! answers filtering, aggregates, `VALUES`/`DISTINCT`, relationship joins and pivot grouping from
|
||||
//! it; models that cannot be stored losslessly (ragged rows, promoted column types) and functions
|
||||
//! that need a row context still read the row-based `DataModel`.
|
||||
//!
|
||||
//! ```
|
||||
//! use gridcraft_dax::{parse_expression, print_expression};
|
||||
//!
|
||||
//! let expr = parse_expression("1 + 2 * 3")?;
|
||||
//! assert_eq!(print_expression(&expr), "1 + 2 * 3");
|
||||
//! # Ok::<(), gridcraft_dax::ParseError>(())
|
||||
//! ```
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
pub mod binder;
|
||||
pub mod eval;
|
||||
pub mod functions;
|
||||
pub mod integrity;
|
||||
pub mod lexer;
|
||||
pub mod model;
|
||||
pub mod parser;
|
||||
pub mod pivot;
|
||||
pub mod pivot_table;
|
||||
pub mod printer;
|
||||
pub mod references;
|
||||
pub mod storage;
|
||||
pub mod types;
|
||||
pub mod validate;
|
||||
pub mod value;
|
||||
|
||||
pub use ast::{
|
||||
Axis, AxisGroup, AxisKind, AxisOrderItem, BinaryOp, Call, ColumnDef, DateTimeLiteral, Define, Definition, Evaluate, Expr, ExprKind, FunctionDef,
|
||||
FunctionParam, Literal, MParameterDef, MeasureDef, Name, NameRef, NameStyle, OrderItem, ParameterSubtype, ParameterType, PassingMode, Query,
|
||||
SortDirection, Span, StartValue, TableDef, UnaryOp, VarDecl, VarDef, VisualShape,
|
||||
};
|
||||
pub use binder::{BindError, Binder, BoundExpr, BoundMeasure, BoundVariable, bind_formula};
|
||||
pub use eval::{Evaluator, FilterContext, StorageStats};
|
||||
pub use functions::{BlankPolicy, FunctionCategory, FunctionFlags, FunctionSpec, Overload, ParamKind, Parameter, ReturnType, catalog, lookup};
|
||||
pub use integrity::{
|
||||
Cardinality, IntegrityCheck, IntegrityFinding, IntegrityReport, MAX_REPORTED_CYCLES, MAX_REPORTED_KEYS, MAX_REPORTED_ROWS, RelationshipCheck,
|
||||
Severity, validate_model,
|
||||
};
|
||||
pub use lexer::{LexError, MAX_INPUT_LEN, MAX_QUERY_LEN, Token, TokenKind, tokenize};
|
||||
pub use model::{DataModel, Measure, ModelColumn, ModelError, ModelTable, Relationship, parse_measure};
|
||||
pub use parser::{MAX_DEPTH, ParseError, parse_expression, parse_query};
|
||||
pub use pivot::{PivotError, PivotField, pivot, pivot_cross, pivot_fields};
|
||||
pub use printer::{print_expression, print_query};
|
||||
pub use references::{column_ref, implicit_measure_formula, table_ref};
|
||||
pub use storage::{ColumnFootprint, MIN_ENCODING_SAVING, PackedCodes, SCAN_BATCH_ROWS, StorageFootprint, TableFootprint, ValueRef};
|
||||
pub use validate::{ValidationError, ValidationErrorKind, validate_call, validate_expression};
|
||||
pub use value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue};
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Tabular data-model metadata: tables, columns, relationships and measures.
|
||||
//!
|
||||
//! This is the binder/evaluator's model view. It deliberately does not implement XLSX storage:
|
||||
//! callers load the metadata from JSON or from a workbook adapter and parse the measure formulas
|
||||
//! with [`DataModel::parse_formulas`]. Rows are not part of this layer; the evaluator supplies
|
||||
//! table values.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::value::Scalar;
|
||||
use crate::{Expr, ParseError, parse_expression};
|
||||
|
||||
/// A table in the model. Column order is preserved because `RELATEDTABLE`, `ROW` and table
|
||||
/// constructors expose it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ModelTable {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub columns: Vec<ModelColumn>,
|
||||
/// Optional inline rows. Workbook adapters can fill these; the metadata-only binder ignores
|
||||
/// them. Each row has one scalar per column, in column order.
|
||||
#[serde(default)]
|
||||
pub rows: Vec<Vec<Scalar>>,
|
||||
}
|
||||
|
||||
/// A model column. `data_type` is the model's declared type name (`Int64`, `Double`, `String`,
|
||||
/// `DateTime`, `Boolean`, `Decimal`, ...); it is metadata, not a parsed [`crate::types::DataType`],
|
||||
/// because model type names and DAX expression types are not the same vocabulary.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ModelColumn {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub data_type: Option<String>,
|
||||
}
|
||||
|
||||
/// Model metadata the binder does not need: hidden columns, the marked date column and each
|
||||
/// column's default summarization. It travels inside the same model JSON document, on the table
|
||||
/// and column objects (`"date_column"`, `"hidden"`, `"summarize_by"`), so a model stays one file;
|
||||
/// the engine reads and validates it at the model boundary (`dataModel.load`) and reports it from
|
||||
/// `dataModel.status`.
|
||||
///
|
||||
/// The type doubles as the loader: unknown document keys (`rows`, `data_type`, `relationships`,
|
||||
/// `measures`, ...) are ignored, so a document written before these fields existed loads with
|
||||
/// every field at its default.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ModelMetadata {
|
||||
pub tables: Vec<TableMetadata>,
|
||||
}
|
||||
|
||||
/// One table's metadata slice of a model document.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct TableMetadata {
|
||||
pub name: String,
|
||||
/// The column marked as this table's date column, in the model's spelling.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub date_column: Option<String>,
|
||||
pub columns: Vec<ColumnMetadata>,
|
||||
}
|
||||
|
||||
/// One column's metadata slice of a model document.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ColumnMetadata {
|
||||
pub name: String,
|
||||
/// Hidden from the Data View and the field list (`dataModel.setColumnHidden`). Model
|
||||
/// metadata, as in Excel; the window's "Show Hidden" toggle is only a view setting.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub hidden: bool,
|
||||
/// Excel's "Summarize By" (`Sum`, `Average`, `Count`, `Min`, `Max`, `None`), canonicalized.
|
||||
/// Absent falls back to the type default: numbers sum, everything else counts.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub summarize_by: Option<String>,
|
||||
}
|
||||
|
||||
/// The canonical spelling of a `Summarize By` name, or `None` when it is not one. Names match
|
||||
/// case-insensitively and ignore spaces, hyphens and underscores, so `"do not summarize"`,
|
||||
/// `"DoNotSummarize"` and `"none"` all mean `None`.
|
||||
pub fn summarize_by_name(name: &str) -> Option<&'static str> {
|
||||
let key: String = name.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).collect::<String>().to_ascii_lowercase();
|
||||
match key.as_str() {
|
||||
"sum" => Some("Sum"),
|
||||
"average" | "avg" => Some("Average"),
|
||||
"count" => Some("Count"),
|
||||
"min" | "minimum" => Some("Min"),
|
||||
"max" | "maximum" => Some("Max"),
|
||||
"none" | "donotsummarize" => Some("None"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a serde field should be left out of the serialized JSON (its default).
|
||||
fn is_false(value: &bool) -> bool {
|
||||
!*value
|
||||
}
|
||||
|
||||
impl ModelMetadata {
|
||||
/// Parses and validates the metadata of a model JSON document.
|
||||
///
|
||||
/// The type itself is the loader: unknown document keys (`rows`, `data_type`,
|
||||
/// `relationships`, `measures`, ...) are ignored, so a document written before the metadata
|
||||
/// fields existed yields every table and column with default metadata.
|
||||
pub fn from_model_json(text: &str) -> Result<ModelMetadata, ModelError> {
|
||||
let mut metadata: ModelMetadata = serde_json::from_str(text).map_err(|error| ModelError::new(format!("invalid model JSON: {error}")))?;
|
||||
metadata.validate()?;
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Canonicalizes the names and rejects unknown summarizations and a date column that is not
|
||||
/// one of its table's columns. Duplicate table/column names are the [`DataModel`]'s check;
|
||||
/// they are rejected here too so a document cannot produce an ambiguous lookup.
|
||||
pub fn validate(&mut self) -> Result<(), ModelError> {
|
||||
let mut tables = BTreeMap::new();
|
||||
for table in &mut self.tables {
|
||||
if tables.insert(table.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate model table `{}`", table.name)));
|
||||
}
|
||||
let mut columns = BTreeMap::new();
|
||||
for column in &mut table.columns {
|
||||
if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name)));
|
||||
}
|
||||
if let Some(name) = column.summarize_by.clone() {
|
||||
let Some(canonical) = summarize_by_name(&name) else {
|
||||
return Err(ModelError::new(format!("column `{}` has unknown summarization `{name}`", column.name)));
|
||||
};
|
||||
column.summarize_by = Some(canonical.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(date) = table.date_column.clone() {
|
||||
let Some(column) = table.columns.iter().find(|column| column.name.eq_ignore_ascii_case(&date)) else {
|
||||
return Err(ModelError::new(format!("table `{}` marks unknown column `{date}` as its date column", table.name)));
|
||||
};
|
||||
table.date_column = Some(column.name.clone());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A table's metadata, matching names case-insensitively.
|
||||
pub fn table(&self, name: &str) -> Option<&TableMetadata> {
|
||||
self.tables.iter().find(|table| table.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// A table's metadata for editing.
|
||||
pub fn table_mut(&mut self, name: &str) -> Option<&mut TableMetadata> {
|
||||
self.tables.iter_mut().find(|table| table.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// A column's metadata, matching table and column names case-insensitively.
|
||||
pub fn column(&self, table: &str, column: &str) -> Option<&ColumnMetadata> {
|
||||
self.table(table)?.columns.iter().find(|entry| entry.name.eq_ignore_ascii_case(column))
|
||||
}
|
||||
|
||||
/// A column's metadata for editing.
|
||||
pub fn column_mut(&mut self, table: &str, column: &str) -> Option<&mut ColumnMetadata> {
|
||||
let table = self.table_mut(table)?;
|
||||
table.columns.iter_mut().find(|entry| entry.name.eq_ignore_ascii_case(column))
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-column relationship between two model tables.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Relationship {
|
||||
pub from_table: String,
|
||||
pub from_column: String,
|
||||
pub to_table: String,
|
||||
pub to_column: String,
|
||||
/// `true` when the relationship filters in both directions.
|
||||
#[serde(default)]
|
||||
pub bidirectional: bool,
|
||||
/// Inactive relationships can be activated by `USERELATIONSHIP`.
|
||||
#[serde(default)]
|
||||
pub inactive: bool,
|
||||
}
|
||||
|
||||
/// A measure definition. The formula is DAX text; [`DataModel::parse_formulas`] parses it into
|
||||
/// [`Measure::expr`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Measure {
|
||||
pub name: String,
|
||||
pub formula: String,
|
||||
/// The home table, used by `COUNTROWS()` without an argument and for field-list placement.
|
||||
#[serde(default)]
|
||||
pub table: Option<String>,
|
||||
#[serde(default)]
|
||||
pub format: Option<String>,
|
||||
#[serde(skip)]
|
||||
pub expr: Option<Expr>,
|
||||
}
|
||||
|
||||
/// A model definition loaded from JSON or another workbook adapter.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DataModel {
|
||||
#[serde(default)]
|
||||
pub tables: Vec<ModelTable>,
|
||||
#[serde(default)]
|
||||
pub relationships: Vec<Relationship>,
|
||||
#[serde(default)]
|
||||
pub measures: Vec<Measure>,
|
||||
}
|
||||
|
||||
/// A metadata or formula error found while preparing a model for binding.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct ModelError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ModelError {
|
||||
fn new(message: impl Into<String>) -> Self {
|
||||
ModelError { message: message.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl DataModel {
|
||||
/// Parses every measure formula and validates table/column/relationship names.
|
||||
///
|
||||
/// Names are compared case-insensitively. Duplicate table names, duplicate column names
|
||||
/// within a table, and relationships naming missing tables/columns are rejected.
|
||||
pub fn parse_formulas(&mut self) -> Result<(), ModelError> {
|
||||
let mut tables: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for (index, table) in self.tables.iter().enumerate() {
|
||||
let key = table.name.to_ascii_lowercase();
|
||||
if tables.insert(key, index).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate model table `{}`", table.name)));
|
||||
}
|
||||
let mut columns = BTreeMap::new();
|
||||
for column in &table.columns {
|
||||
if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for relationship in &self.relationships {
|
||||
self.require_column(&relationship.from_table, &relationship.from_column)?;
|
||||
self.require_column(&relationship.to_table, &relationship.to_column)?;
|
||||
}
|
||||
|
||||
let mut names = BTreeMap::new();
|
||||
for measure in &mut self.measures {
|
||||
// Measure names are compared case-insensitively everywhere else, so a duplicate would
|
||||
// silently hide the second formula.
|
||||
if names.insert(measure.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate measure `{}`", measure.name)));
|
||||
}
|
||||
let expr = parse_expression(&measure.formula).map_err(|error| ModelError::new(format!("measure `{}`: {error}", measure.name)))?;
|
||||
measure.expr = Some(expr);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The index of a table, ignoring case.
|
||||
pub fn table_index(&self, name: &str) -> Option<usize> {
|
||||
self.tables.iter().position(|table| table.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The index of a column within a table, ignoring case.
|
||||
pub fn column_index(&self, table: usize, name: &str) -> Option<usize> {
|
||||
self.tables.get(table)?.columns.iter().position(|column| column.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The index of a measure, ignoring case.
|
||||
pub fn measure_index(&self, name: &str) -> Option<usize> {
|
||||
self.measures.iter().position(|measure| measure.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// Tables that contain a column with this name.
|
||||
pub fn tables_with_column(&self, name: &str) -> Vec<usize> {
|
||||
self.tables
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, table)| table.columns.iter().any(|column| column.name.eq_ignore_ascii_case(name)))
|
||||
.map(|(index, _)| index)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn require_column(&self, table: &str, column: &str) -> Result<(), ModelError> {
|
||||
let Some(table_index) = self.table_index(table) else {
|
||||
return Err(ModelError::new(format!("relationship names missing table `{table}`")));
|
||||
};
|
||||
if self.column_index(table_index, column).is_none() {
|
||||
return Err(ModelError::new(format!("relationship names missing column `{column}` in table `{table}`")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of [`parse_expression`] for a measure, used by callers that want to surface the
|
||||
/// parse error separately from the model metadata.
|
||||
pub fn parse_measure(formula: &str) -> Result<Expr, ParseError> {
|
||||
parse_expression(formula)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The model JSON `docs/power-pivot.md` documents, written before the metadata fields existed.
|
||||
/// It must keep loading (the metadata parser ignores everything it does not own), and adding
|
||||
/// the fields must not change what the document means.
|
||||
const OLD_SCHEMA: &str = r#"{
|
||||
"tables": [{"name":"Sales","columns":[{"name":"Region","data_type":"String"},{"name":"Amount","data_type":"Double"}],
|
||||
"rows":[["East",10],["West",20]]}],
|
||||
"relationships": [],
|
||||
"measures": [{"name":"Total Sales","formula":"SUM(Sales[Amount])","table":"Sales"}]
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn old_schema_json_loads_with_default_metadata() {
|
||||
let mut model: DataModel = serde_json::from_str(OLD_SCHEMA).expect("old model JSON loads");
|
||||
model.parse_formulas().expect("old model JSON validates");
|
||||
assert_eq!(model.tables[0].columns.len(), 2, "unknown metadata keys never disturb the model");
|
||||
|
||||
let metadata = ModelMetadata::from_model_json(OLD_SCHEMA).expect("old model JSON has valid metadata");
|
||||
let table = metadata.table("sales").expect("the table is in the metadata");
|
||||
assert_eq!(table.date_column, None);
|
||||
assert!(!metadata.column("Sales", "amount").expect("column metadata").hidden);
|
||||
assert_eq!(metadata.column("Sales", "Amount").and_then(|column| column.summarize_by.clone()), None);
|
||||
|
||||
let written = serde_json::to_value(&metadata).expect("metadata serializes");
|
||||
assert!(written["tables"][0].get("date_column").is_none(), "an unmarked table writes no date column: {written}");
|
||||
assert!(written["tables"][0]["columns"][0].get("hidden").is_none(), "a visible column writes no hidden flag: {written}");
|
||||
assert!(written["tables"][0]["columns"][0].get("summarize_by").is_none(), "an absent summarization stays absent: {written}");
|
||||
let reloaded = ModelMetadata::from_model_json(&written.to_string()).expect("the written metadata reloads");
|
||||
assert_eq!(reloaded, metadata);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_metadata_is_read_from_the_model_document() {
|
||||
let json = r#"{
|
||||
"tables": [{"name":"Calendar","date_column":"date",
|
||||
"columns":[{"name":"Date","data_type":"DateTime"},{"name":"Secret","hidden":true,"summarize_by":"do not summarize"}],
|
||||
"rows":[[45292,null]]}],
|
||||
"relationships": [],
|
||||
"measures": []
|
||||
}"#;
|
||||
let mut model: DataModel = serde_json::from_str(json).expect("JSON with metadata loads");
|
||||
model.parse_formulas().expect("the model validates");
|
||||
let metadata = ModelMetadata::from_model_json(json).expect("the metadata validates");
|
||||
let table = metadata.table("Calendar").expect("a table");
|
||||
assert_eq!(table.date_column.as_deref(), Some("Date"), "the stored name takes the column's spelling");
|
||||
let secret = metadata.column("calendar", "SECRET").expect("column metadata");
|
||||
assert!(secret.hidden);
|
||||
assert_eq!(secret.summarize_by.as_deref(), Some("None"), "the summarization is canonicalized");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_naming_missing_columns_or_aggregates_is_rejected() {
|
||||
let bad_date = r#"{"tables":[{"name":"T","columns":[{"name":"A"}],"rows":[],"date_column":"Missing"}]}"#;
|
||||
assert!(ModelMetadata::from_model_json(bad_date).is_err(), "a date column that is not a column is rejected");
|
||||
|
||||
let bad_summary = r#"{"tables":[{"name":"T","columns":[{"name":"A","summarize_by":"median"}],"rows":[]}]}"#;
|
||||
assert!(ModelMetadata::from_model_json(bad_summary).is_err(), "an unknown summarization is rejected");
|
||||
|
||||
let duplicate = r#"{"tables":[{"name":"T","columns":[{"name":"A"},{"name":"a"}]}]}"#;
|
||||
assert!(ModelMetadata::from_model_json(duplicate).is_err(), "ambiguous column names are rejected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarize_by_names_match_loosely() {
|
||||
assert_eq!(summarize_by_name("SUM"), Some("Sum"));
|
||||
assert_eq!(summarize_by_name("average"), Some("Average"));
|
||||
assert_eq!(summarize_by_name("Do Not Summarize"), Some("None"));
|
||||
assert_eq!(summarize_by_name("median"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,878 @@
|
||||
//! Pratt parser: tokens → [`Expr`] / [`Query`].
|
||||
//!
|
||||
//! Binding powers encode the operator table (tighter binds first): parentheses and function
|
||||
//! calls; `^`; unary `+`/`-`; `*`/`/`; binary `+`/`-`; `&`; comparisons, which include `IN`; `NOT`;
|
||||
//! `&&`; `||`. Every operator is left-associative, including `^`: Microsoft's operator reference
|
||||
//! orders equal-precedence operators from left to right, so `2^3^2` is `(2^3)^2`.
|
||||
|
||||
use crate::ast::{
|
||||
Axis, AxisGroup, AxisKind, AxisOrderItem, BinaryOp, Call, ColumnDef, Define, Definition, Evaluate, Expr, ExprKind, FunctionDef, FunctionParam,
|
||||
Literal, MParameterDef, MeasureDef, Name, NameRef, OrderItem, ParameterSubtype, ParameterType, PassingMode, Query, SortDirection, Span,
|
||||
StartValue, TableDef, UnaryOp, VarDecl, VarDef, VisualShape,
|
||||
};
|
||||
use crate::lexer::{LexError, Token, TokenKind, tokenize};
|
||||
|
||||
/// Deepest expression nesting accepted. Bounds parser recursion (and the tree that later
|
||||
/// evaluation walks) at 256 levels.
|
||||
pub const MAX_DEPTH: usize = 256;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message} at bytes {}..{}", span.start, span.end)]
|
||||
pub struct ParseError {
|
||||
pub message: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl ParseError {
|
||||
fn new(message: impl Into<String>, span: Span) -> Self {
|
||||
ParseError { message: message.into(), span }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LexError> for ParseError {
|
||||
fn from(e: LexError) -> Self {
|
||||
ParseError { message: e.message, span: e.span }
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a DAX expression. A single leading `=` (as typed in some editors) is accepted and
|
||||
/// ignored.
|
||||
pub fn parse_expression(src: &str) -> Result<Expr, ParseError> {
|
||||
if src.len() > crate::MAX_INPUT_LEN {
|
||||
return Err(ParseError::new(
|
||||
format!("input is too long ({} bytes, limit {})", src.len(), crate::MAX_INPUT_LEN),
|
||||
crate::Span::new(0, src.len()),
|
||||
));
|
||||
}
|
||||
let tokens = tokenize(src)?;
|
||||
let mut parser = Parser { tokens, i: 0, depth: 0 };
|
||||
if matches!(parser.peek(), TokenKind::Eq) {
|
||||
parser.next();
|
||||
}
|
||||
let expr = parser.expr(0)?;
|
||||
parser.expect_eof()?;
|
||||
ensure_depth(&expr)?;
|
||||
Ok(expr)
|
||||
}
|
||||
|
||||
/// Parses a DAX query: an optional `DEFINE` block followed by one or more `EVALUATE` statements.
|
||||
///
|
||||
/// For the simple form `EVALUATE <expression>` the result has `define: None` and a single
|
||||
/// evaluation with empty `order_by`/`start_at`. An optional trailing `;` is accepted; it is not
|
||||
/// part of the grammar, only a recovery extension.
|
||||
///
|
||||
/// Statement keywords (`DEFINE`, `MEASURE`, `COLUMN`, `TABLE`, `VAR`, `RETURN`, `FUNCTION`,
|
||||
/// `MPARAMETER`, `ORDER BY`, `START AT`, `WITH VISUAL SHAPE`, `AXIS`, `GROUP`, `TOTAL`,
|
||||
/// `DENSIFY`, `ASC`, `DESC`) are recognised case-insensitively at the positions where they are
|
||||
/// expected. Definition bounds and statement bounds therefore come from those keywords, never
|
||||
/// from newlines.
|
||||
pub fn parse_query(src: &str) -> Result<Query, ParseError> {
|
||||
if src.len() > crate::MAX_QUERY_LEN {
|
||||
return Err(ParseError::new(
|
||||
format!("query is too long ({} bytes, limit {})", src.len(), crate::MAX_QUERY_LEN),
|
||||
crate::Span::new(0, src.len()),
|
||||
));
|
||||
}
|
||||
let tokens = tokenize(src)?;
|
||||
let mut parser = Parser { tokens, i: 0, depth: 0 };
|
||||
let query = parser.query()?;
|
||||
validate_query_depth(&query)?;
|
||||
Ok(query)
|
||||
}
|
||||
|
||||
/// Rejects an AST deeper than [`MAX_DEPTH`] even when parser recursion stayed shallow (for
|
||||
/// example a function call wrapped around a grouped chain).
|
||||
fn ensure_depth(expr: &Expr) -> Result<(), ParseError> {
|
||||
let depth = expr.depth();
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(ParseError::new(format!("expression is nested too deeply (limit {MAX_DEPTH})"), expr.span));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies the AST-depth bound to every expression in a query, not only to the last parsed
|
||||
/// `EVALUATE` expression.
|
||||
fn validate_query_depth(query: &Query) -> Result<(), ParseError> {
|
||||
if let Some(define) = &query.define {
|
||||
for item in &define.items {
|
||||
match item {
|
||||
Definition::Measure(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Column(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Table(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Var(def) => ensure_depth(&def.expr)?,
|
||||
Definition::MParameter(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Function(def) => {
|
||||
ensure_depth(&def.body)?;
|
||||
for param in &def.params {
|
||||
if let Some(default) = ¶m.default {
|
||||
ensure_depth(default)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for evaluate in &query.evaluates {
|
||||
ensure_depth(&evaluate.table)?;
|
||||
for item in &evaluate.order_by {
|
||||
ensure_depth(&item.expr)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn describe(kind: &TokenKind) -> String {
|
||||
match kind {
|
||||
TokenKind::Integer(n) => format!("integer literal `{n}`"),
|
||||
TokenKind::Decimal(n) => format!("decimal literal `{n}`"),
|
||||
TokenKind::DateTime(value) => format!("date/time literal `dt\"{value}\"`"),
|
||||
TokenKind::String(_) => "string literal".into(),
|
||||
TokenKind::Ident(s) => format!("`{s}`"),
|
||||
TokenKind::QuotedIdent(_) => "quoted identifier".into(),
|
||||
TokenKind::BracketIdent(_) => "bracketed identifier".into(),
|
||||
TokenKind::Not => "`NOT`".into(),
|
||||
TokenKind::In => "`IN`".into(),
|
||||
TokenKind::Evaluate => "`EVALUATE`".into(),
|
||||
TokenKind::Plus => "`+`".into(),
|
||||
TokenKind::Minus => "`-`".into(),
|
||||
TokenKind::Star => "`*`".into(),
|
||||
TokenKind::Slash => "`/`".into(),
|
||||
TokenKind::Caret => "`^`".into(),
|
||||
TokenKind::Amp => "`&`".into(),
|
||||
TokenKind::Eq => "`=`".into(),
|
||||
TokenKind::StrictEq => "`==`".into(),
|
||||
TokenKind::NotEq => "`<>`".into(),
|
||||
TokenKind::Lt => "`<`".into(),
|
||||
TokenKind::Gt => "`>`".into(),
|
||||
TokenKind::Le => "`<=`".into(),
|
||||
TokenKind::Ge => "`>=`".into(),
|
||||
TokenKind::AndAnd => "`&&`".into(),
|
||||
TokenKind::OrOr => "`||`".into(),
|
||||
TokenKind::Arrow => "`=>`".into(),
|
||||
TokenKind::Colon => "`:`".into(),
|
||||
TokenKind::AtName(name) => format!("parameter `@{name}`"),
|
||||
TokenKind::Semicolon => "`;`".into(),
|
||||
TokenKind::LParen => "`(`".into(),
|
||||
TokenKind::RParen => "`)`".into(),
|
||||
TokenKind::LBrace => "`{`".into(),
|
||||
TokenKind::RBrace => "`}`".into(),
|
||||
TokenKind::Comma => "`,`".into(),
|
||||
TokenKind::Eof => "end of input".into(),
|
||||
}
|
||||
}
|
||||
|
||||
struct Parser {
|
||||
tokens: Vec<Token>,
|
||||
i: usize,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn peek(&self) -> &TokenKind {
|
||||
self.tokens.get(self.i).map(|t| &t.kind).unwrap_or(&TokenKind::Eof)
|
||||
}
|
||||
|
||||
fn peek_span(&self) -> Span {
|
||||
self.tokens.get(self.i).map(|t| t.span).unwrap_or(Span::empty())
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Token {
|
||||
let token = self.tokens.get(self.i).cloned().unwrap_or(Token { kind: TokenKind::Eof, span: Span::empty() });
|
||||
if self.i < self.tokens.len() {
|
||||
self.i += 1;
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
fn error_here(&self, message: impl Into<String>) -> ParseError {
|
||||
ParseError::new(message, self.peek_span())
|
||||
}
|
||||
|
||||
fn expect(&mut self, kind: TokenKind, context: &str) -> Result<Token, ParseError> {
|
||||
if *self.peek() == kind {
|
||||
Ok(self.next())
|
||||
} else {
|
||||
Err(self.error_here(format!("expected {}, found {}; {context}", describe(&kind), describe(self.peek()))))
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_eof(&self) -> Result<(), ParseError> {
|
||||
match self.peek() {
|
||||
TokenKind::Eof => Ok(()),
|
||||
other => Err(self.error_here(format!("unexpected {} after expression", describe(other)))),
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_query_eof(&self) -> Result<(), ParseError> {
|
||||
match self.peek() {
|
||||
TokenKind::Eof => Ok(()),
|
||||
other => Err(self.error_here(format!("unexpected {} after the query", describe(other)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current token when it is a bare identifier, which is how statement keywords are
|
||||
/// lexed. Keywords are matched case-insensitively by their text.
|
||||
fn peek_word(&self) -> Option<&str> {
|
||||
match self.peek() {
|
||||
TokenKind::Ident(word) => Some(word),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn keyword_at(&self, word: &str) -> bool {
|
||||
self.peek_word().is_some_and(|text| text.eq_ignore_ascii_case(word))
|
||||
}
|
||||
|
||||
fn expect_keyword(&mut self, word: &str, context: &str) -> Result<Token, ParseError> {
|
||||
if self.keyword_at(word) {
|
||||
Ok(self.next())
|
||||
} else {
|
||||
Err(self.error_here(format!("expected `{word}`, found {}; {context}", describe(self.peek()))))
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Query statements
|
||||
// -------------------------------------------------------------------------------------
|
||||
|
||||
fn query(&mut self) -> Result<Query, ParseError> {
|
||||
let define = if self.keyword_at("DEFINE") { Some(self.define_block()?) } else { None };
|
||||
if !matches!(self.peek(), TokenKind::Evaluate) {
|
||||
return Err(self.error_here("a query needs at least one `EVALUATE` statement"));
|
||||
}
|
||||
let mut evaluates = Vec::new();
|
||||
while matches!(self.peek(), TokenKind::Evaluate) {
|
||||
evaluates.push(self.evaluate_statement()?);
|
||||
}
|
||||
// The documented grammar has no statement terminators. A trailing `;` is accepted as a
|
||||
// recovery extension only, never required.
|
||||
while matches!(self.peek(), TokenKind::Semicolon) {
|
||||
self.next();
|
||||
}
|
||||
self.expect_query_eof()?;
|
||||
Ok(Query { define, evaluates })
|
||||
}
|
||||
|
||||
fn define_block(&mut self) -> Result<Define, ParseError> {
|
||||
let keyword = self.next();
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let Some(word) = self.peek_word().map(str::to_owned) else {
|
||||
match self.peek() {
|
||||
TokenKind::Evaluate | TokenKind::Eof | TokenKind::Semicolon => break,
|
||||
other => {
|
||||
return Err(self.error_here(format!(
|
||||
"expected a DEFINE entry (MEASURE, COLUMN, TABLE, VAR, FUNCTION or MPARAMETER), found {}",
|
||||
describe(other)
|
||||
)));
|
||||
}
|
||||
}
|
||||
};
|
||||
if word.eq_ignore_ascii_case("MEASURE") {
|
||||
self.next();
|
||||
items.push(Definition::Measure(self.measure_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("COLUMN") {
|
||||
self.next();
|
||||
items.push(Definition::Column(self.column_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("TABLE") {
|
||||
self.next();
|
||||
items.push(Definition::Table(self.table_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("VAR") {
|
||||
self.next();
|
||||
items.push(Definition::Var(self.var_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("FUNCTION") {
|
||||
self.next();
|
||||
items.push(Definition::Function(self.function_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("MPARAMETER") {
|
||||
self.next();
|
||||
items.push(Definition::MParameter(self.mparameter_definition()?));
|
||||
} else {
|
||||
return Err(self.error_here(format!("expected a DEFINE entry (MEASURE, COLUMN, TABLE, VAR, FUNCTION or MPARAMETER), found `{word}`")));
|
||||
}
|
||||
}
|
||||
if items.is_empty() {
|
||||
return Err(ParseError::new("DEFINE needs at least one definition before `EVALUATE`", keyword.span));
|
||||
}
|
||||
Ok(Define { items })
|
||||
}
|
||||
|
||||
fn measure_definition(&mut self) -> Result<MeasureDef, ParseError> {
|
||||
let name = self.definition_name("measure")?;
|
||||
self.expect(TokenKind::Eq, "a MEASURE definition needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(MeasureDef { name, expr })
|
||||
}
|
||||
|
||||
fn column_definition(&mut self) -> Result<ColumnDef, ParseError> {
|
||||
let name = self.definition_name("column")?;
|
||||
self.expect(TokenKind::Eq, "a COLUMN definition needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(ColumnDef { name, expr })
|
||||
}
|
||||
|
||||
fn var_definition(&mut self) -> Result<VarDef, ParseError> {
|
||||
let name = self.variable_name()?;
|
||||
self.expect(TokenKind::Eq, "a query-scoped VAR needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(VarDef { name, expr })
|
||||
}
|
||||
|
||||
fn table_definition(&mut self) -> Result<TableDef, ParseError> {
|
||||
let name = self.table_name("table")?;
|
||||
self.expect(TokenKind::Eq, "a TABLE definition needs `=` before its table expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
let visual_shape = if self.keyword_at("WITH") { Some(self.visual_shape()?) } else { None };
|
||||
Ok(TableDef { name, expr, visual_shape })
|
||||
}
|
||||
|
||||
fn mparameter_definition(&mut self) -> Result<MParameterDef, ParseError> {
|
||||
let name = self.table_name("M parameter")?;
|
||||
self.expect(TokenKind::Eq, "an MPARAMETER definition needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(MParameterDef { name, expr })
|
||||
}
|
||||
|
||||
fn function_definition(&mut self) -> Result<FunctionDef, ParseError> {
|
||||
let name = self.table_name("function")?;
|
||||
self.expect(TokenKind::Eq, "a FUNCTION definition needs `=` before its parameter list")?;
|
||||
self.expect(TokenKind::LParen, "a FUNCTION definition needs a parenthesised parameter list")?;
|
||||
let mut params = Vec::new();
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
self.next();
|
||||
} else {
|
||||
loop {
|
||||
params.push(self.function_param()?);
|
||||
let token = self.next();
|
||||
match token.kind {
|
||||
TokenKind::Comma => {
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
return Err(self.error_here("expected a parameter after `,`"));
|
||||
}
|
||||
}
|
||||
TokenKind::RParen => break,
|
||||
other => {
|
||||
return Err(ParseError::new(format!("expected `,` or `)` in the parameter list, found {}", describe(&other)), token.span));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.expect(TokenKind::Arrow, "a FUNCTION definition needs `=>` before its body")?;
|
||||
let body = self.expr(0)?;
|
||||
Ok(FunctionDef { name, params, body })
|
||||
}
|
||||
|
||||
fn function_param(&mut self) -> Result<FunctionParam, ParseError> {
|
||||
let token = self.next();
|
||||
let name = match &token.kind {
|
||||
TokenKind::Ident(text) => Name::bare(text.clone()),
|
||||
other => return Err(ParseError::new(format!("expected a parameter name, found {}", describe(other)), token.span)),
|
||||
};
|
||||
let mut ty = None;
|
||||
let mut subtype = None;
|
||||
let mut passing = None;
|
||||
if matches!(self.peek(), TokenKind::Colon) {
|
||||
let colon = self.next();
|
||||
let mut annotated = false;
|
||||
while let Some(word) = self.peek_word().map(str::to_owned) {
|
||||
if let Some(parsed) = ParameterType::from_keyword(&word) {
|
||||
if ty.is_some() {
|
||||
return Err(self.error_here(format!("duplicate parameter type `{}`", parsed.keyword())));
|
||||
}
|
||||
if subtype.is_some() || passing.is_some() {
|
||||
return Err(self.error_here("the parameter type must come before its subtype and passing mode"));
|
||||
}
|
||||
ty = Some(parsed);
|
||||
} else if let Some(parsed) = ParameterSubtype::from_keyword(&word) {
|
||||
if subtype.is_some() {
|
||||
return Err(self.error_here(format!("duplicate parameter subtype `{}`", parsed.keyword())));
|
||||
}
|
||||
if passing.is_some() {
|
||||
return Err(self.error_here("the parameter subtype must come before its passing mode"));
|
||||
}
|
||||
subtype = Some(parsed);
|
||||
} else if let Some(parsed) = PassingMode::from_keyword(&word) {
|
||||
if passing.is_some() {
|
||||
return Err(self.error_here("duplicate parameter passing mode"));
|
||||
}
|
||||
passing = Some(parsed);
|
||||
} else {
|
||||
return Err(self.error_here(format!("unknown function parameter type `{word}`")));
|
||||
}
|
||||
self.next();
|
||||
annotated = true;
|
||||
}
|
||||
if !annotated {
|
||||
return Err(ParseError::new("expected a parameter type, subtype or passing mode after `:`", colon.span));
|
||||
}
|
||||
if subtype.is_some() && ty.is_some_and(|ty| ty != ParameterType::Scalar) {
|
||||
return Err(self.error_here("only SCALAR parameters accept a subtype"));
|
||||
}
|
||||
}
|
||||
let default = if matches!(self.peek(), TokenKind::Eq) {
|
||||
self.next();
|
||||
Some(self.expr(0)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(FunctionParam { name, ty, subtype, passing, default })
|
||||
}
|
||||
|
||||
fn evaluate_statement(&mut self) -> Result<Evaluate, ParseError> {
|
||||
self.next(); // EVALUATE
|
||||
let table = self.expr(0)?;
|
||||
let order_by = if self.keyword_at("ORDER") {
|
||||
self.next();
|
||||
self.expect_keyword("BY", "ORDER must be followed by BY")?;
|
||||
self.order_items()?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let start_at = if self.keyword_at("START") {
|
||||
let span = self.peek_span();
|
||||
self.next();
|
||||
self.expect_keyword("AT", "START must be followed by AT")?;
|
||||
if order_by.is_empty() {
|
||||
return Err(ParseError::new("START AT requires a preceding ORDER BY clause", span));
|
||||
}
|
||||
let values = self.start_values()?;
|
||||
if values.len() > order_by.len() {
|
||||
return Err(ParseError::new(format!("START AT has {} value(s) but ORDER BY has {} item(s)", values.len(), order_by.len()), span));
|
||||
}
|
||||
values
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
Ok(Evaluate { table, order_by, start_at })
|
||||
}
|
||||
|
||||
fn order_items(&mut self) -> Result<Vec<OrderItem>, ParseError> {
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let expr = self.expr(0)?;
|
||||
let direction = self.direction();
|
||||
items.push(OrderItem { expr, direction });
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
fn direction(&mut self) -> SortDirection {
|
||||
if self.keyword_at("ASC") {
|
||||
self.next();
|
||||
SortDirection::Asc
|
||||
} else if self.keyword_at("DESC") {
|
||||
self.next();
|
||||
SortDirection::Desc
|
||||
} else {
|
||||
SortDirection::Asc
|
||||
}
|
||||
}
|
||||
|
||||
fn start_values(&mut self) -> Result<Vec<StartValue>, ParseError> {
|
||||
let mut values = Vec::new();
|
||||
loop {
|
||||
values.push(self.start_value()?);
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
fn start_value(&mut self) -> Result<StartValue, ParseError> {
|
||||
let token = self.next();
|
||||
let negative = match &token.kind {
|
||||
TokenKind::Minus => Some(true),
|
||||
TokenKind::Plus => Some(false),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(negative) = negative {
|
||||
let literal = self.next();
|
||||
return match literal.kind {
|
||||
TokenKind::Integer(value) => Ok(StartValue::Literal(Literal::Integer(if negative { -value } else { value }))),
|
||||
TokenKind::Decimal(value) => Ok(StartValue::Literal(Literal::Decimal(if negative { -value } else { value }))),
|
||||
other => Err(ParseError::new(format!("a signed START AT value must be a numeric literal, found {}", describe(&other)), literal.span)),
|
||||
};
|
||||
}
|
||||
match token.kind {
|
||||
TokenKind::Integer(value) => Ok(StartValue::Literal(Literal::Integer(value))),
|
||||
TokenKind::Decimal(value) => Ok(StartValue::Literal(Literal::Decimal(value))),
|
||||
TokenKind::DateTime(value) => Ok(StartValue::Literal(Literal::DateTime(value))),
|
||||
TokenKind::String(value) => Ok(StartValue::Literal(Literal::String(value))),
|
||||
TokenKind::AtName(name) => Ok(StartValue::Parameter(Name::bare(name))),
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("TRUE") => Ok(StartValue::Literal(Literal::Boolean(true))),
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("FALSE") => Ok(StartValue::Literal(Literal::Boolean(false))),
|
||||
other => Err(ParseError::new(format!("expected a literal or @parameter in START AT, found {}", describe(&other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
fn visual_shape(&mut self) -> Result<VisualShape, ParseError> {
|
||||
self.next(); // WITH
|
||||
self.expect_keyword("VISUAL", "WITH must be followed by VISUAL SHAPE")?;
|
||||
self.expect_keyword("SHAPE", "WITH VISUAL SHAPE is a single clause")?;
|
||||
let mut axes = Vec::new();
|
||||
while self.keyword_at("AXIS") {
|
||||
let span = self.peek_span();
|
||||
let axis = self.axis()?;
|
||||
if axes.iter().any(|existing: &Axis| existing.kind == axis.kind) {
|
||||
return Err(ParseError::new(format!("duplicate AXIS {} clause", axis.kind.keyword()), span));
|
||||
}
|
||||
axes.push(axis);
|
||||
}
|
||||
if axes.is_empty() {
|
||||
return Err(self.error_here("WITH VISUAL SHAPE needs at least one AXIS ROWS or AXIS COLUMNS clause"));
|
||||
}
|
||||
let densify = if self.keyword_at("DENSIFY") {
|
||||
self.next();
|
||||
let value = self.next();
|
||||
match value.kind {
|
||||
TokenKind::String(text) => Some(text),
|
||||
other => {
|
||||
return Err(ParseError::new(format!("DENSIFY needs a double-quoted column name, found {}", describe(&other)), value.span));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(VisualShape { axes, densify })
|
||||
}
|
||||
|
||||
fn axis(&mut self) -> Result<Axis, ParseError> {
|
||||
self.next(); // AXIS
|
||||
let kind_token = self.next();
|
||||
let kind = match &kind_token.kind {
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("ROWS") => AxisKind::Rows,
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("COLUMNS") => AxisKind::Columns,
|
||||
other => {
|
||||
return Err(ParseError::new(format!("expected `ROWS` or `COLUMNS` after AXIS, found {}", describe(other)), kind_token.span));
|
||||
}
|
||||
};
|
||||
let mut groups = Vec::new();
|
||||
while self.keyword_at("GROUP") {
|
||||
self.next();
|
||||
let mut columns = vec![self.column_ref("GROUP")?];
|
||||
while matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
columns.push(self.column_ref("GROUP")?);
|
||||
}
|
||||
self.expect_keyword("TOTAL", "each GROUP needs a TOTAL column")?;
|
||||
let total = self.column_ref("TOTAL")?;
|
||||
groups.push(AxisGroup { columns, total });
|
||||
}
|
||||
if groups.is_empty() {
|
||||
return Err(self.error_here("AXIS needs at least one GROUP ... TOTAL level"));
|
||||
}
|
||||
self.expect_keyword("ORDER", "each AXIS needs an ORDER BY clause")?;
|
||||
self.expect_keyword("BY", "each AXIS needs an ORDER BY clause")?;
|
||||
let mut order_by = Vec::new();
|
||||
loop {
|
||||
let column = self.column_ref("ORDER BY")?;
|
||||
let direction = self.direction();
|
||||
order_by.push(AxisOrderItem { column, direction });
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Axis { kind, groups, order_by })
|
||||
}
|
||||
|
||||
/// A table name in a definition: a bare identifier or a single-quoted name.
|
||||
fn table_name(&mut self, what: &str) -> Result<Name, ParseError> {
|
||||
let token = self.next();
|
||||
match &token.kind {
|
||||
TokenKind::Ident(text) => Ok(Name::bare(text.clone())),
|
||||
TokenKind::QuotedIdent(text) => Ok(Name::quoted(text.clone())),
|
||||
other => Err(ParseError::new(format!("expected a {what} name, found {}", describe(other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `<table>[<name>]`, the name of a MEASURE or COLUMN definition.
|
||||
fn definition_name(&mut self, kind: &str) -> Result<NameRef, ParseError> {
|
||||
let table = self.table_name(kind)?;
|
||||
let token = self.next();
|
||||
match &token.kind {
|
||||
TokenKind::BracketIdent(text) => Ok(NameRef::qualified(table, Name::bracketed(text.clone()))),
|
||||
other => Err(ParseError::new(format!("expected a bracketed {kind} name after the table name, found {}", describe(other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable name: a plain identifier, never quoted or bracketed.
|
||||
fn variable_name(&mut self) -> Result<Name, ParseError> {
|
||||
let token = self.next();
|
||||
match &token.kind {
|
||||
TokenKind::Ident(text) => Ok(Name::bare(text.clone())),
|
||||
TokenKind::QuotedIdent(_) | TokenKind::BracketIdent(_) => {
|
||||
Err(ParseError::new("variable names cannot be quoted or bracketed", token.span))
|
||||
}
|
||||
other => Err(ParseError::new(format!("expected a variable name, found {}", describe(other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A column reference: `[Column]`, `Table[Column]` or `'Table'[Column]`.
|
||||
fn column_ref(&mut self, context: &str) -> Result<NameRef, ParseError> {
|
||||
let token = self.next();
|
||||
let table = match &token.kind {
|
||||
TokenKind::BracketIdent(text) => return Ok(NameRef::unqualified(Name::bracketed(text.clone()))),
|
||||
TokenKind::Ident(text) => Name::bare(text.clone()),
|
||||
TokenKind::QuotedIdent(text) => Name::quoted(text.clone()),
|
||||
other => {
|
||||
return Err(ParseError::new(format!("expected a column reference in {context}, found {}", describe(other)), token.span));
|
||||
}
|
||||
};
|
||||
let column = self.next();
|
||||
match &column.kind {
|
||||
TokenKind::BracketIdent(text) => Ok(NameRef::qualified(table, Name::bracketed(text.clone()))),
|
||||
other => Err(ParseError::new(format!("expected a bracketed column name after the table name, found {}", describe(other)), column.span)),
|
||||
}
|
||||
}
|
||||
|
||||
fn enter(&mut self) -> Result<(), ParseError> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return Err(self.error_here(format!("expression is nested too deeply (limit {MAX_DEPTH})")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn leave(&mut self) {
|
||||
self.depth = self.depth.saturating_sub(1);
|
||||
}
|
||||
|
||||
fn binary_op(&self) -> Option<BinaryOp> {
|
||||
match self.peek() {
|
||||
TokenKind::Plus => Some(BinaryOp::Add),
|
||||
TokenKind::Minus => Some(BinaryOp::Sub),
|
||||
TokenKind::Star => Some(BinaryOp::Mul),
|
||||
TokenKind::Slash => Some(BinaryOp::Div),
|
||||
TokenKind::Caret => Some(BinaryOp::Pow),
|
||||
TokenKind::Amp => Some(BinaryOp::Concat),
|
||||
TokenKind::Eq => Some(BinaryOp::Eq),
|
||||
TokenKind::StrictEq => Some(BinaryOp::StrictEq),
|
||||
TokenKind::NotEq => Some(BinaryOp::Ne),
|
||||
TokenKind::Lt => Some(BinaryOp::Lt),
|
||||
TokenKind::Gt => Some(BinaryOp::Gt),
|
||||
TokenKind::Le => Some(BinaryOp::Le),
|
||||
TokenKind::Ge => Some(BinaryOp::Ge),
|
||||
TokenKind::AndAnd => Some(BinaryOp::And),
|
||||
TokenKind::OrOr => Some(BinaryOp::Or),
|
||||
TokenKind::In => Some(BinaryOp::In),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expr(&mut self, min_bp: u8) -> Result<Expr, ParseError> {
|
||||
self.enter()?;
|
||||
let mut lhs = self.prefix()?;
|
||||
let mut lhs_depth = lhs.depth();
|
||||
while let Some(op) = self.binary_op() {
|
||||
let bp = op.precedence();
|
||||
if bp < min_bp {
|
||||
break;
|
||||
}
|
||||
self.next();
|
||||
// Every binary operator is left-associative (DAX orders equal precedence left to right).
|
||||
let next_min = if op.is_right_associative() { bp } else { bp + 1 };
|
||||
let rhs = self.expr(next_min)?;
|
||||
// Grouped expressions return their inner tree without a parenthesis node, so the
|
||||
// depth must come from the AST itself, not from the parser's recursion frames.
|
||||
let depth = lhs_depth.max(rhs.depth());
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err(self.error_here(format!("expression is nested too deeply (limit {MAX_DEPTH})")));
|
||||
}
|
||||
lhs_depth = depth + 1;
|
||||
let span = lhs.span.to(rhs.span);
|
||||
lhs = Expr::new(ExprKind::Binary { op, left: Box::new(lhs), right: Box::new(rhs) }, span);
|
||||
}
|
||||
self.leave();
|
||||
Ok(lhs)
|
||||
}
|
||||
|
||||
fn prefix(&mut self) -> Result<Expr, ParseError> {
|
||||
let token = self.next();
|
||||
match token.kind {
|
||||
TokenKind::Integer(n) => Ok(Expr::literal(Literal::Integer(n), token.span)),
|
||||
TokenKind::Decimal(n) => Ok(Expr::literal(Literal::Decimal(n), token.span)),
|
||||
TokenKind::DateTime(value) => Ok(Expr::literal(Literal::DateTime(value), token.span)),
|
||||
TokenKind::String(s) => Ok(Expr::literal(Literal::String(s), token.span)),
|
||||
TokenKind::Ident(word) => {
|
||||
if word.eq_ignore_ascii_case("VAR") {
|
||||
return self.var_return(token.span);
|
||||
}
|
||||
if word.eq_ignore_ascii_case("RETURN") {
|
||||
return Err(ParseError::new("RETURN without a preceding VAR declaration", token.span));
|
||||
}
|
||||
self.prefix_ident(word, token.span)
|
||||
}
|
||||
TokenKind::QuotedIdent(word) => {
|
||||
let name = Name::quoted(word);
|
||||
if let TokenKind::BracketIdent(_) = self.peek() {
|
||||
self.qualified_name(name, token.span)
|
||||
} else {
|
||||
Ok(Expr::new(ExprKind::Name(NameRef::unqualified(name)), token.span))
|
||||
}
|
||||
}
|
||||
TokenKind::BracketIdent(word) => Ok(Expr::new(ExprKind::Name(NameRef::unqualified(Name::bracketed(word))), token.span)),
|
||||
TokenKind::Not => {
|
||||
let operand = self.expr(UnaryOp::Not.precedence())?;
|
||||
let span = token.span.to(operand.span);
|
||||
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Not, expr: Box::new(operand) }, span))
|
||||
}
|
||||
TokenKind::Plus => {
|
||||
let operand = self.expr(UnaryOp::Plus.precedence())?;
|
||||
let span = token.span.to(operand.span);
|
||||
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Plus, expr: Box::new(operand) }, span))
|
||||
}
|
||||
TokenKind::Minus => {
|
||||
let operand = self.expr(UnaryOp::Neg.precedence())?;
|
||||
let span = token.span.to(operand.span);
|
||||
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Neg, expr: Box::new(operand) }, span))
|
||||
}
|
||||
TokenKind::LParen => self.paren(token.span),
|
||||
TokenKind::LBrace => self.table(token.span),
|
||||
_ => Err(ParseError::new(format!("expected expression, found {}", describe(&token.kind)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
fn prefix_ident(&mut self, word: String, span: Span) -> Result<Expr, ParseError> {
|
||||
if let TokenKind::BracketIdent(_) = self.peek() {
|
||||
return self.qualified_name(Name::bare(word), span);
|
||||
}
|
||||
if matches!(self.peek(), TokenKind::LParen) {
|
||||
return self.call(Name::bare(word), span);
|
||||
}
|
||||
if word.eq_ignore_ascii_case("TRUE") {
|
||||
return Ok(Expr::literal(Literal::Boolean(true), span));
|
||||
}
|
||||
if word.eq_ignore_ascii_case("FALSE") {
|
||||
return Ok(Expr::literal(Literal::Boolean(false), span));
|
||||
}
|
||||
Ok(Expr::new(ExprKind::Name(NameRef::unqualified(Name::bare(word))), span))
|
||||
}
|
||||
|
||||
/// Parses `VAR <name> = <expr> ... RETURN <expr>`.
|
||||
///
|
||||
/// The declaration values and the `RETURN` body stop at the next statement or definition
|
||||
/// keyword because a bare identifier is never an infix operator, so no newline or terminator
|
||||
/// is needed. A nested `VAR ... RETURN ...` as a declaration value or body parses recursively.
|
||||
fn var_return(&mut self, start: Span) -> Result<Expr, ParseError> {
|
||||
let mut vars = Vec::new();
|
||||
// The leading `VAR` has already been consumed by `prefix`; each iteration parses one
|
||||
// declaration and continues only when another `VAR` follows the value expression.
|
||||
loop {
|
||||
let name = self.variable_name()?;
|
||||
self.expect(TokenKind::Eq, "a VAR declaration needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
vars.push(VarDecl { name, expr });
|
||||
if !self.keyword_at("VAR") {
|
||||
break;
|
||||
}
|
||||
self.next();
|
||||
}
|
||||
if !self.keyword_at("RETURN") {
|
||||
return Err(self.error_here("VAR declarations must be followed by RETURN <expression>"));
|
||||
}
|
||||
self.next();
|
||||
let body = self.expr(0)?;
|
||||
let span = start.to(body.span);
|
||||
Ok(Expr::new(ExprKind::VarReturn { vars, body: Box::new(body) }, span))
|
||||
}
|
||||
|
||||
/// Consumes a bracketed column that follows a table name.
|
||||
fn qualified_name(&mut self, table: Name, table_span: Span) -> Result<Expr, ParseError> {
|
||||
let column = self.next();
|
||||
let TokenKind::BracketIdent(text) = column.kind else {
|
||||
return Err(ParseError::new("expected bracketed column name", column.span));
|
||||
};
|
||||
let span = table_span.to(column.span);
|
||||
Ok(Expr::new(ExprKind::Name(NameRef::qualified(table, Name::bracketed(text))), span))
|
||||
}
|
||||
|
||||
fn call(&mut self, name: Name, name_span: Span) -> Result<Expr, ParseError> {
|
||||
self.expect(TokenKind::LParen, "function calls need `(` after the name")?;
|
||||
let mut args = Vec::new();
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
let close = self.next();
|
||||
return Ok(Expr::new(ExprKind::Call(Call { name, args }), name_span.to(close.span)));
|
||||
}
|
||||
let close_span = loop {
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
return Err(self.error_here("expected an argument after `,`"));
|
||||
}
|
||||
args.push(self.expr(0)?);
|
||||
let token = self.next();
|
||||
match token.kind {
|
||||
TokenKind::Comma => {}
|
||||
TokenKind::RParen => break token.span,
|
||||
_ => {
|
||||
return Err(ParseError::new(
|
||||
format!("expected `,` or `)` in call to `{}`, found {}", name.text, describe(&token.kind)),
|
||||
token.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(Expr::new(ExprKind::Call(Call { name, args }), name_span.to(close_span)))
|
||||
}
|
||||
|
||||
/// `( expr )` is grouping (parentheses are not AST nodes), `( a, b, ... )` is a row
|
||||
/// constructor.
|
||||
fn paren(&mut self, open: Span) -> Result<Expr, ParseError> {
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
let close = self.next();
|
||||
return Err(ParseError::new("empty parentheses are not an expression", open.to(close.span)));
|
||||
}
|
||||
let first = self.expr(0)?;
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
let mut items = vec![first];
|
||||
while matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
if matches!(self.peek(), TokenKind::RParen | TokenKind::Eof) {
|
||||
return Err(self.error_here("expected an expression after `,` in a row constructor"));
|
||||
}
|
||||
items.push(self.expr(0)?);
|
||||
}
|
||||
let close = self.expect(TokenKind::RParen, "row constructors end with `)`")?;
|
||||
return Ok(Expr::new(ExprKind::Tuple(items), open.to(close.span)));
|
||||
}
|
||||
let close = self.expect(TokenKind::RParen, "parentheses end with `)`")?;
|
||||
Ok(Expr::new(first.kind, open.to(close.span)))
|
||||
}
|
||||
|
||||
fn table(&mut self, open: Span) -> Result<Expr, ParseError> {
|
||||
let mut items = Vec::new();
|
||||
if matches!(self.peek(), TokenKind::RBrace) {
|
||||
let close = self.next();
|
||||
return Ok(Expr::new(ExprKind::Table(items), open.to(close.span)));
|
||||
}
|
||||
loop {
|
||||
if matches!(self.peek(), TokenKind::RBrace | TokenKind::Eof) {
|
||||
return Err(self.error_here("expected a value in the table constructor"));
|
||||
}
|
||||
items.push(self.expr(0)?);
|
||||
match self.next().kind {
|
||||
TokenKind::Comma => {
|
||||
if matches!(self.peek(), TokenKind::RBrace) {
|
||||
return Err(self.error_here("expected a value after `,` in the table constructor"));
|
||||
}
|
||||
}
|
||||
TokenKind::RBrace => break,
|
||||
_ => {
|
||||
return Err(ParseError::new(
|
||||
"expected `,` or `}` in the table constructor",
|
||||
self.tokens.get(self.i.saturating_sub(1)).map(|t| t.span).unwrap_or(open),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let close_span = self.tokens.get(self.i.saturating_sub(1)).map(|t| t.span).unwrap_or(open);
|
||||
Ok(Expr::new(ExprKind::Table(items), open.to(close_span)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Minimal pivot grouping over the in-memory model.
|
||||
//!
|
||||
//! A pivot groups a table by one or more column references and evaluates a measure once per
|
||||
//! group. This is the integration point a workbook/PivotTable adapter can call; the full
|
||||
//! PivotTable layout engine remains outside this crate.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::binder::{BindError, Binder, BoundExpr};
|
||||
use crate::eval::{Evaluator, FilterContext};
|
||||
use crate::model::DataModel;
|
||||
use crate::pivot_table::DEFAULT_MAX_CELLS;
|
||||
use crate::value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue};
|
||||
use crate::{Expr, parse_expression};
|
||||
|
||||
/// One grouping field.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PivotField {
|
||||
pub table: usize,
|
||||
pub column: usize,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Evaluates a measure grouped by the supplied row fields (no column fields).
|
||||
pub fn pivot(model: &DataModel, measure: &str, row_fields: &[PivotField]) -> Result<TableValue, PivotError> {
|
||||
pivot_cross(model, measure, row_fields, &[])
|
||||
}
|
||||
|
||||
/// Evaluates a measure grouped by row fields and optional column fields.
|
||||
///
|
||||
/// The result has one column per row field followed by one measure column per distinct column
|
||||
/// group. With no column fields the result is the usual grouped table. Group order is ascending;
|
||||
/// BLANK is a group of its own. Missing combinations are BLANK.
|
||||
pub fn pivot_cross(model: &DataModel, measure: &str, row_fields: &[PivotField], column_fields: &[PivotField]) -> Result<TableValue, PivotError> {
|
||||
let evaluator = Evaluator::new(model)?;
|
||||
let table_index = model
|
||||
.measure_index(measure)
|
||||
.and_then(|index| model.measures.get(index))
|
||||
.and_then(|measure| measure.table.as_deref())
|
||||
.and_then(|table| model.table_index(table));
|
||||
let Some(table_index) = table_index else {
|
||||
return Err(PivotError::Eval(EvalError::new(format!(
|
||||
"measure `{measure}` has no home table; give the measure a home table, or set `PivotTable::source_table` and render through `PivotTable` instead of `pivot`/`pivot_cross`"
|
||||
))));
|
||||
};
|
||||
let source = model.tables.get(table_index).ok_or_else(|| PivotError::Eval(EvalError::new("missing table")))?;
|
||||
|
||||
let mut row_groups: BTreeMap<Vec<ScalarKey>, Vec<Scalar>> = BTreeMap::new();
|
||||
let mut column_groups: BTreeMap<Vec<ScalarKey>, Vec<Scalar>> = BTreeMap::new();
|
||||
for row in &source.rows {
|
||||
let row_values = group_values(row, row_fields, table_index)?;
|
||||
row_groups.entry(row_values.iter().map(crate::value::distinct_key).collect()).or_insert(row_values);
|
||||
if !column_fields.is_empty() {
|
||||
let column_values = group_values(row, column_fields, table_index)?;
|
||||
column_groups.entry(column_values.iter().map(crate::value::distinct_key).collect()).or_insert(column_values);
|
||||
}
|
||||
}
|
||||
if column_fields.is_empty() {
|
||||
column_groups.insert(Vec::new(), Vec::new());
|
||||
}
|
||||
if row_groups.len().checked_mul(column_groups.len()).is_none_or(|cells| cells > DEFAULT_MAX_CELLS) {
|
||||
return Err(PivotError::Eval(EvalError::new(format!(
|
||||
"pivot would materialize {} rows x {} columns, over the limit of {} cells",
|
||||
row_groups.len(),
|
||||
column_groups.len(),
|
||||
DEFAULT_MAX_CELLS
|
||||
))));
|
||||
}
|
||||
|
||||
let mut columns = row_fields.iter().map(|field| TableColumn { name: field.name.clone() }).collect::<Vec<_>>();
|
||||
let column_headers: Vec<(Vec<ScalarKey>, Vec<Scalar>)> = column_groups.into_iter().collect();
|
||||
if column_fields.is_empty() {
|
||||
columns.push(TableColumn { name: measure.to_string() });
|
||||
} else {
|
||||
for (_, values) in &column_headers {
|
||||
// Headers show calendar text for dates and whole numbers without `.0`, as Excel does.
|
||||
columns.push(TableColumn { name: values.iter().map(|value| value.to_dax_text()).collect::<Vec<_>>().join(" | ") });
|
||||
}
|
||||
}
|
||||
|
||||
let mut rows = Vec::with_capacity(row_groups.len());
|
||||
for (row_key, row_values) in row_groups {
|
||||
let mut out = row_values;
|
||||
for (column_key, _) in &column_headers {
|
||||
let mut filters = FilterContext::default();
|
||||
for (field, key) in row_fields.iter().zip(&row_key) {
|
||||
crate::pivot_table::narrow_to_key(&mut filters, field.table, field.column, key);
|
||||
}
|
||||
for (field, key) in column_fields.iter().zip(column_key) {
|
||||
crate::pivot_table::narrow_to_key(&mut filters, field.table, field.column, key);
|
||||
}
|
||||
out.push(evaluator.evaluate_measure(measure, filters)?);
|
||||
}
|
||||
rows.push(out);
|
||||
}
|
||||
Ok(TableValue::new(columns, rows))
|
||||
}
|
||||
|
||||
fn group_values(row: &[Scalar], fields: &[PivotField], table_index: usize) -> Result<Vec<Scalar>, PivotError> {
|
||||
let mut values = Vec::with_capacity(fields.len());
|
||||
for field in fields {
|
||||
if field.table != table_index {
|
||||
return Err(PivotError::Eval(EvalError::new("pivot fields must belong to the measure table")));
|
||||
}
|
||||
values.push(row.get(field.column).cloned().unwrap_or(Scalar::Blank));
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
/// Parses field references such as `Sales[Region]` against the model.
|
||||
pub fn pivot_fields(model: &DataModel, fields: &[String]) -> Result<Vec<PivotField>, PivotError> {
|
||||
let binder = Binder::new(model);
|
||||
let mut out = Vec::with_capacity(fields.len());
|
||||
for field in fields {
|
||||
let expr: Expr = parse_expression(field).map_err(|error| PivotError::Bind(BindError { message: error.message, span: error.span }))?;
|
||||
let bound = binder.bind_expression(&expr)?;
|
||||
let BoundExpr::Column { table, column } = bound else {
|
||||
return Err(PivotError::Bind(BindError { message: format!("pivot field `{field}` is not a column reference"), span: expr.span }));
|
||||
};
|
||||
let name =
|
||||
model.tables.get(table).and_then(|table| table.columns.get(column)).map(|column| column.name.clone()).unwrap_or_else(|| field.clone());
|
||||
out.push(PivotField { table, column, name });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PivotError {
|
||||
#[error(transparent)]
|
||||
Bind(#[from] BindError),
|
||||
#[error(transparent)]
|
||||
Eval(#[from] EvalError),
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user