twust_macro 1.1.0

Zero-config Static type-checker for Tailwind CSS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
/*
 * Author: Oyelowo Oyedayo
 * Email: oyelowo.oss@gmail.com
 * Copyright (c) 2023 Oyelowo Oyedayo
 * Licensed under the MIT license
 */

use nom::{
    branch::alt,
    bytes::complete::{tag, take_until, take_while1},
    character::complete::{digit1, multispace0, multispace1},
    combinator::{all_consuming, not, opt, recognize},
    multi::separated_list0,
    number,
    sequence::{preceded, tuple},
    IResult,
};
use std::collections::HashSet;
use syn::{parse_macro_input, LitStr};
mod config;
mod plugins;
mod tailwind;
use tailwind::{
    colorful::COLORFUL_BASECLASSES, lengthy::LENGTHY, modifiers::get_modifiers,
    tailwind_config::CustomisableClasses, valid_baseclass_names::VALID_BASECLASS_NAMES,
};

use config::{get_classes, noconfig::UNCONFIGURABLE, read_tailwind_config};
use proc_macro::TokenStream;
use tailwind::signable::SIGNABLES;

fn setup(input: &LitStr) -> Result<(Vec<String>, Vec<String>), TokenStream> {
    let config = &(match read_tailwind_config() {
        Ok(config) => config,
        Err(e) => {
            return Err(syn::Error::new_spanned(
                input,
                format!("Error reading Tailwind config: {}", e),
            )
            .to_compile_error()
            .into());
        }
    });
    let modifiers = get_modifiers(config);
    let valid_class_names = get_classes(config);
    let is_unconfigurable = |classes: &CustomisableClasses, action_type_str: &str| {
        serde_json::to_value(classes)
            .expect("Unable to convert to value")
            .as_object()
            .expect("Unable to convert to object")
            .iter()
            .any(|(key, value)| {
                if UNCONFIGURABLE.contains(&key.as_str()) && !value.is_null() {
                    panic!("You cannot {action_type_str} the key: {key} in tailwind.config.json",);
                }
                false
            })
    };
    is_unconfigurable(&config.theme.overrides, "override");
    is_unconfigurable(&config.theme.extend, "extend");
    Ok((modifiers, valid_class_names))
}

fn get_classes_straight() -> HashSet<String> {
    HashSet::from_iter(get_classes(
        &read_tailwind_config().expect("Problem getting classes"),
    ))
}

fn is_valid_classname(class_name: &str) -> bool {
    get_classes_straight().contains(class_name)
}

fn is_valid_modifier(modifier: &str) -> bool {
    let modifiers: HashSet<String> = HashSet::from_iter(get_modifiers(
        &read_tailwind_config().expect("Problem getting modifiers"),
    ));
    modifiers.contains(modifier)
}

fn parse_predefined_tw_classname(input: &str) -> IResult<&str, ()> {
    let (input, class_name) = recognize(|i| {
        // Considering a Tailwind class consists of alphanumeric, dashes, and slash
        nom::bytes::complete::is_a(
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-./",
        )(i)
    })(input)?;

    let is_signable = SIGNABLES.iter().any(|s| {
        class_name
            .strip_prefix('-')
            .unwrap_or(class_name)
            .starts_with(s)
    });

    if is_signable && is_valid_classname(class_name.strip_prefix('-').unwrap_or(class_name))
        || !is_signable && is_valid_classname(class_name)
    {
        Ok((input, ()))
    } else {
        Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )))
    }
}

fn is_ident_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '-'
}

fn is_lengthy_classname(class_name: &str) -> bool {
    LENGTHY.contains(&class_name.strip_prefix('-').unwrap_or(class_name))
}

// Custom number parser that handles optional decimals and signs, and scientific notation
fn float_strict(input: &str) -> IResult<&str, f64> {
    let (input, number) = recognize(tuple((
        opt(alt((tag("-"), tag("+")))),
        digit1,
        opt(preceded(tag("."), digit1)),
        opt(tuple((
            alt((tag("e"), tag("E"))),
            opt(alt((tag("-"), tag("+")))),
            digit1,
        ))),
    )))(input)?;

    let float_val: f64 = number.parse().unwrap();
    Ok((input, float_val))
}

fn parse_length_unit(input: &str) -> IResult<&str, String> {
    let (input, number) = float_strict(input)?;
    let (input, unit) = {
        // px|em|rem|%|cm|mm|in|pt|pc|vh|vw|vmin|vmax
        alt((
            tag("px"),
            tag("em"),
            tag("rem"),
            tag("%"),
            tag("cm"),
            tag("mm"),
            tag("in"),
            tag("pt"),
            tag("pc"),
            tag("vh"),
            tag("vw"),
            tag("vmin"),
            tag("vmax"),
            // TODO: Should i allow unitless values? Would need something like this in caller
            // location if so:
            // let (input, _) = alt((parse_length_unit, parse_number))(input)?;
            tag(""),
        ))
    }(input)?;
    Ok((input, format!("{}{}", number, unit)))
}

// text-[22px]
fn lengthy_arbitrary_classname(input: &str) -> IResult<&str, ()> {
    let (input, class_name) = take_until("-[")(input)?;
    let (input, _) = if is_lengthy_classname(class_name) {
        Ok((input, ()))
    } else {
        Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )))
    }?;

    // arbitrary value
    let (input, _) = tag("-")(input)?;
    let (input, _) = tag("[")(input)?;
    // is number
    let (input, _) = parse_length_unit(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// #bada55
fn parse_hex_color(input: &str) -> IResult<&str, String> {
    let (input, _) = tag("#")(input)?;
    let (input, color) = take_while1(|c: char| c.is_ascii_hexdigit())(input)?;
    let (input, _) = if color.chars().count() == 3 || color.chars().count() == 6 {
        Ok((input, ()))
    } else {
        Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )))
    }?;
    let color = format!("#{}", color);
    Ok((input, color))
}

fn parse_u8(input: &str) -> IResult<&str, u8> {
    let (input, num) = number::complete::double(input)?;
    let input = match num as u32 {
        0..=255 => input,
        _ => {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Tag,
            )))
        }
    };
    Ok((input, num as u8))
}

// rgb(255, 255, 255) rgb(255_255_255)
fn parse_rgb_color(input: &str) -> IResult<&str, String> {
    let (input, _) = tag("rgb(")(input)?;
    let (input, r) = parse_u8(input)?;
    let (input, _) = alt((tag(","), tag("_")))(input)?;
    let (input, g) = parse_u8(input)?;
    let (input, _) = alt((tag(","), tag("_")))(input)?;
    let (input, b) = parse_u8(input)?;
    let (input, _) = tag(")")(input)?;
    let color = format!("rgb({}, {}, {})", r, g, b);
    Ok((input, color))
}

// rgba(255, 255, 255, 0.5) rgba(255_255_255_0.5)
fn parse_rgba_color(input: &str) -> IResult<&str, String> {
    let (input, _) = tag("rgba(")(input)?;
    let (input, r) = parse_u8(input)?;
    let (input, _) = alt((tag(","), tag("_")))(input)?;
    let (input, g) = parse_u8(input)?;
    let (input, _) = alt((tag(","), tag("_")))(input)?;
    let (input, b) = parse_u8(input)?;
    let (input, _) = alt((tag(","), tag("_")))(input)?;
    let (input, a) = number::complete::double(input)?;
    let (input, _) = tag(")")(input)?;
    let color = format!("rgba({}, {}, {}, {})", r, g, b, a);
    Ok((input, color))
}

fn is_colorful_baseclass(class_name: &str) -> bool {
    COLORFUL_BASECLASSES.contains(&class_name)
}

// text-[#bada55]
fn colorful_arbitrary_baseclass(input: &str) -> IResult<&str, ()> {
    let (input, class_name) = take_until("-[")(input)?;
    let (input, _) = if is_colorful_baseclass(class_name) {
        Ok((input, ()))
    } else {
        Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )))
    }?;

    // arbitrary value
    let (input, _) = tag("-")(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = alt((parse_hex_color, parse_rgb_color, parse_rgba_color))(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// e.g: [mask-type:alpha]
fn kv_pair_classname(input: &str) -> IResult<&str, ()> {
    let (input, _) = tag("[")(input)?;
    let (input, _) = take_while1(is_ident_char)(input)?;
    let (input, _) = tag(":")(input)?;
    let (input, _) = take_until("]")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// before:content-['Festivus']
fn arbitrary_content(input: &str) -> IResult<&str, ()> {
    let (input, _) = tag("content-['")(input)?;
    let (input, _) = take_until("']")(input)?;
    let (input, _) = tag("']")(input)?;
    Ok((input, ()))
}

// content-[>] content-[<]
fn arbitrary_with_arrow(input: &str) -> IResult<&str, ()> {
    let (input, _) = take_while1(is_ident_char)(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = alt((tag(">"), tag("<")))(input)?;
    let (input, _) = take_until("]")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// bg-black/25
fn predefined_colorful_opacity(input: &str) -> IResult<&str, ()> {
    let input = if COLORFUL_BASECLASSES
        .iter()
        .any(|cb| input.trim().starts_with(cb))
    {
        input
    } else {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    };
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '/')(input)?;
    // let (input, _) = take_until("/")(input)?;
    let (input, _) = tag("/")(input)?;

    let (input, num) = number::complete::double(input)?;
    let input = match num as u8 {
        0..=100 => input,
        _ => {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Tag,
            )))
        }
    };

    Ok((input, ()))
}

// bg-black/[27] bg-black/[27%]
fn arbitrary_opacity(input: &str) -> IResult<&str, ()> {
    let input = if COLORFUL_BASECLASSES
        .iter()
        .any(|cb| input.trim().starts_with(cb))
    {
        input
    } else {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    };
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '/')(input)?;
    let (input, _) = tag("/")(input)?;
    let (input, _) = tag("[")(input)?;
    // 0-100 integer
    let (input, num) = number::complete::double(input)?;
    let input = match num as u8 {
        0..=100 => input,
        _ => {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Tag,
            )))
        }
    };
    let (input, _) = opt(tag("%"))(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// bg-[url('/img/down-arrow.svg')]
fn bg_arbitrary_url(input: &str) -> IResult<&str, ()> {
    // prefixed by baseclass
    let input = if COLORFUL_BASECLASSES
        .iter()
        .any(|cb| input.trim().starts_with(cb))
    {
        input
    } else {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    };
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '[')(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = tag("url('")(input)?;
    let (input, _) = take_until("')")(input)?;
    let (input, _) = tag("')")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// grid-cols-[fit-content(theme(spacing.32))]
fn arbitrary_css_value(input: &str) -> IResult<&str, ()> {
    // is prefixed by valid base class
    // take until -[
    let (input, base_class) = take_until("-[")(input)?;
    let input = if VALID_BASECLASS_NAMES
        .iter()
        .any(|cb| base_class.trim().eq(*cb))
    {
        input
    } else {
        return Err(nom::Err::Error(nom::error::Error::new(
            base_class,
            nom::error::ErrorKind::Tag,
        )));
    };
    let (input, _) = tag("-[")(input)?;
    let (input, _) = not(alt((
        tag("--"),
        tag("var(--"),
        // <ident>:var(--
    )))(input)?;
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '(')(input)?;
    let (input, _) = tag("(")(input)?;
    let (input, _) = take_until(")]")(input)?;

    // allow anything inthe brackets
    let (input, _) = take_until("]")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// bg-[--my-color]
fn arbitrary_css_var(input: &str) -> IResult<&str, ()> {
    // is prefixed by valid base class
    let input = if VALID_BASECLASS_NAMES
        .iter()
        .any(|cb| input.trim().starts_with(cb))
    {
        input
    } else {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    };
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '[')(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = tag("--")(input)?;
    let (input, _) = take_while1(|char| is_ident_char(char) && char != ']')(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}
// text-[var(--my-var)]
fn arbitrary_css_var2(input: &str) -> IResult<&str, ()> {
    // is prefixed by valid base class
    let input = if VALID_BASECLASS_NAMES
        .iter()
        .any(|cb| input.trim().starts_with(cb))
    {
        input
    } else {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    };
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '[')(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = tag("var(--")(input)?;
    let (input, _) = take_while1(|char| is_ident_char(char) && char != ')')(input)?;
    let (input, _) = tag(")]")(input)?;
    Ok((input, ()))
}

// text-[length:var(--my-var)]
fn arbitrary_css_var3(input: &str) -> IResult<&str, ()> {
    // is prefixed by valid base class
    let input = if VALID_BASECLASS_NAMES
        .iter()
        .any(|cb| input.trim().starts_with(cb))
    {
        input
    } else {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    };
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '[')(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = take_while1(|char| is_ident_char(char) && char != ':')(input)?;
    let (input, _) = tag(":")(input)?;
    let (input, _) = tag("var(--")(input)?;
    let (input, _) = take_while1(|char| is_ident_char(char) && char != ')')(input)?;
    let (input, _) = tag(")]")(input)?;
    Ok((input, ()))
}

// group/edit
fn arbitrary_group_classname(input: &str) -> IResult<&str, ()> {
    let (input, _) = alt((tag("group"),))(input)?;
    let (input, _) = tag("/")(input)?;
    let (input, _) = take_while1(is_ident_char)(input)?;
    Ok((input, ()))
}

fn parse_single_tw_classname(input: &str) -> IResult<&str, ()> {
    alt((
        // bg-[url('/what_a_rush.png')]
        bg_arbitrary_url,
        // bg-black/25
        predefined_colorful_opacity,
        // group/edit
        arbitrary_group_classname,
        // bg-black/[27]
        arbitrary_opacity,
        // btn
        parse_predefined_tw_classname,
        // [mask-type:luminance] [mask-type:alpha]
        kv_pair_classname,
        // text-[22px]
        lengthy_arbitrary_classname,
        // text-[#bada55]
        colorful_arbitrary_baseclass,
        // before:content-['Festivus']
        arbitrary_content,
        // content-[>] content-[<]
        arbitrary_with_arrow,
        // bg-[--my-color]
        arbitrary_css_var,
        // text-[var(--my-var)]
        arbitrary_css_var2,
        // text-[length:var(--my-var)]
        arbitrary_css_var3,
        // grid-cols-[fit-content(theme(spacing.32))]
        arbitrary_css_value,
    ))(input)
}

// hover:underline
fn predefined_modifier(input: &str) -> IResult<&str, ()> {
    let (input, modifier) = recognize(|i| {
        // Assuming a Tailwind class consists of alphanumeric, dashes, and colons
        nom::bytes::complete::is_a(
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-",
        )(i)
    })(input)?;

    if is_valid_modifier(modifier) {
        Ok((input, ()))
    } else {
        Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )))
    }
}

// predefined special modifiers e.g peer-checked:p-4 group-hover:visible
fn predefined_special_modifier(input: &str) -> IResult<&str, ()> {
    let (input, _) = alt((
        // peer-checked:p-4
        tuple((tag("peer-"), predefined_modifier)),
        // group-hover:visible
        tuple((tag("group-"), predefined_modifier)),
    ))(input)?;
    Ok((input, ()))
}

// [&:nth-child(3)]:underline
// [&_p]:mt-4
fn arbitrary_front_selector_modifier(input: &str) -> IResult<&str, ()> {
    let (input, _) = tag("[&")(input)?;
    let (input, _) = take_until("]")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// group-[:nth-of-type(3)_&]:block
fn arbitrary_back_selector_modifier(input: &str) -> IResult<&str, ()> {
    let (input, _) = take_while1(|char| is_ident_char(char) && char != '[')(input)?;
    let (input, _) = tag("-[")(input)?;
    let (input, _) = take_until("&]")(input)?;
    let (input, _) = tag("&]")(input)?;
    Ok((input, ()))
}

// [@supports(display:grid)]:grid
fn arbitrary_at_supports_rule_modifier(input: &str) -> IResult<&str, ()> {
    let (input, _) = tag("[@supports(")(input)?;
    let (input, _) = take_until(")")(input)?;
    let (input, _) = tag(")]")(input)?;
    Ok((input, ()))
}

// [@media(any-hover:hover){&:hover}]:opacity-100
fn arbitrary_at_media_rule_modifier(input: &str) -> IResult<&str, ()> {
    // starts with [@media and ends with ]
    let (input, _) = tag("[@media(")(input)?;
    let (input, _) = take_until("]")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// group/edit invisible hover:bg-slate-200 group-hover/item:visible
fn group_peer_modifier(input: &str) -> IResult<&str, ()> {
    let (input, _) = alt((
        tuple((tag("group-"), predefined_modifier)),
        // https://tailwindcss.com/docs/hover-focus-and-other-states#differentiating-peers
        // peer-checked/published:text-sky-500
        tuple((tag("peer-"), predefined_modifier)),
    ))(input)?;
    let (input, _) = tag("/")(input)?;
    let (input, _) = take_while1(is_ident_char)(input)?;
    Ok((input, ()))
}

// hidden group-[.is-published]:block
// group-[:nth-of-type(3)_&]:block
// peer-[.is-dirty]:peer-required:block hidden
// hidden peer-[:nth-of-type(3)_&]:block
fn group_modifier_selector(input: &str) -> IResult<&str, ()> {
    let (input, _) = alt((tag("group"), tag("peer")))(input)?;
    let (input, _) = tag("-[")(input)?;
    let (input, _) = take_until("]")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// supports-[backdrop-filter]
fn supports_arbitrary(input: &str) -> IResult<&str, ()> {
    let (input, _) = tag("supports-[")(input)?;
    let (input, _) = take_until("]")(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// aria-[sort=ascending]:bg-[url('/img/down-arrow.svg')]
// aria-[sort=descending]:bg-[url('/img/up-arrow.svg')]
// group-data-[selected=Right]:w-[30px]
// group-aria-[main-page=false]/main:hidden / group-data-[main-page=false]/main:hidden
fn aria_or_data_arbitrary(input: &str) -> IResult<&str, ()> {
    let (input, _) = opt(tag("group-"))(input)?;
    let (input, _) = alt((tag("aria-["), tag("data-[")))(input)?;
    let (input, _) = take_while1(is_ident_char)(input)?;
    let (input, _) = tag("=")(input)?;
    let (input, _) = take_while1(is_ident_char)(input)?;
    let (input, _) = tag("]")(input)?;
    let (input, _) = opt(tuple((tag("/"), take_while1(is_ident_char))))(input)?;
    Ok((input, ()))
}

// data-[size=large]:p-8
fn data_arbitrary(input: &str) -> IResult<&str, ()> {
    let (input, _) = tag("data-[")(input)?;
    let (input, _) = take_while1(is_ident_char)(input)?;
    let (input, _) = tag("=")(input)?;
    let (input, _) = take_while1(is_ident_char)(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// min-[320px]:text-center max-[600px]:bg-sky-300
fn min_max_arbitrary_modifier(input: &str) -> IResult<&str, ()> {
    let (input, _) = alt((tag("min-"), tag("max-")))(input)?;
    let (input, _) = tag("[")(input)?;
    let (input, _) = parse_length_unit(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((input, ()))
}

// *:overflow-scroll
fn wildcard_modifier(input: &str) -> IResult<&str, ()> {
    let (input, _) = tag("*")(input)?;
    Ok((input, ()))
}

fn modifier(input: &str) -> IResult<&str, ()> {
    alt((
        group_modifier_selector,
        group_peer_modifier,
        predefined_special_modifier,
        arbitrary_front_selector_modifier,
        arbitrary_back_selector_modifier,
        arbitrary_at_supports_rule_modifier,
        arbitrary_at_media_rule_modifier,
        predefined_modifier,
        supports_arbitrary,
        aria_or_data_arbitrary,
        data_arbitrary,
        min_max_arbitrary_modifier,
        wildcard_modifier,
    ))(input)
}

fn modifiers_chained(input: &str) -> IResult<&str, ()> {
    let (input, _modifiers) = separated_list0(tag(":"), modifier)(input)?;
    Ok((input, ()))
}

fn parse_tw_full_classname(input: &str) -> IResult<&str, Vec<&str>> {
    let (input, _class_names) = tuple((
        opt(tuple((modifiers_chained, tag(":")))),
        parse_single_tw_classname,
    ))(input)?;

    Ok((input, vec![]))
}

// Edge cases
// [&:nth-child(3)]:underline
// lg:[&:nth-child(3)]:hover:underline
// [&_p]:mt-4
// flex [@supports(display:grid)]:grid
// [@media(any-hover:hover){&:hover}]:opacity-100
// group/edit invisible hover:bg-slate-200 group-hover/item:visible
// hidden group-[.is-published]:block
// group-[:nth-of-type(3)_&]:block
// peer-checked/published:text-sky-500
// peer-[.is-dirty]:peer-required:block hidden
// hidden peer-[:nth-of-type(3)_&]:block
// after:content-['*'] after:ml-0.5 after:text-red-500 block text-sm font-medium text-slate-700
// before:content-[''] before:block
// bg-black/75 supports-[backdrop-filter]:bg-black/25 supports-[backdrop-filter]:backdrop-blur
// aria-[sort=ascending]:bg-[url('/img/down-arrow.svg')] aria-[sort=descending]:bg-[url('/img/up-arrow.svg')]
// group-aria-[sort=ascending]:rotate-0 group-aria-[sort=descending]:rotate-180
// data-[size=large]:p-8
// open:bg-white dark:open:bg-slate-900 open:ring-1 open:ring-black/5 dark:open:ring-white/10 open:shadow-lg p-6 rounded-lg
// lg:[&:nth-child(3)]:hover:underline
// min-[320px]:text-center max-[600px]:bg-sky-300
// top-[117px] lg:top-[344px]
// bg-[#bada55] text-[22px] before:content-['Festivus']
// grid grid-cols-[fit-content(theme(spacing.32))]
// bg-[--my-color]
// [mask-type:luminance] hover:[mask-type:alpha]
// [--scroll-offset:56px] lg:[--scroll-offset:44px]
// lg:[&:nth-child(3)]:hover:underline
// bg-[url('/what_a_rush.png')]
// before:content-['hello\_world']
// text-[22px]
// text-[#bada55]
// text-[var(--my-var)]
// text-[length:var(--my-var)]
// text-[color:var(--my-var)]
fn parse_class_names(input: &str) -> IResult<&str, Vec<&str>> {
    let (input, _) = multispace0(input)?;
    let (input, _class_names) = separated_list0(multispace1, parse_tw_full_classname)(input)?;
    let (input, _) = multispace0(input)?;

    Ok((input, vec![]))
}

fn parse_top(input: &str) -> IResult<&str, Vec<&str>> {
    all_consuming(parse_class_names)(input)
}

fn parse_single_top(input: &str) -> IResult<&str, Vec<&str>> {
    all_consuming(parse_tw_full_classname)(input)
}

#[proc_macro]
pub fn twust_many_classes(raw_input: TokenStream) -> TokenStream {
    let r_input = raw_input.clone();
    let input_original = parse_macro_input!(r_input as LitStr);
    let (_modifiers, _valid_class_names) = match setup(&input_original) {
        Ok(value) => value,
        Err(value) => {
            return syn::Error::new_spanned(input_original, value)
                .to_compile_error()
                .into()
        }
    };
    let full_classnames = input_original.value();

    let (_input, _class_names) = match parse_top(&full_classnames) {
        Ok(value) => value,
        Err(value) => {
            return syn::Error::new_spanned(input_original, value)
                .to_compile_error()
                .into()
        }
    };

    quote::quote! {
        #input_original
    }
    .into()
}

#[proc_macro]
pub fn twust_one_class(raw_input: TokenStream) -> TokenStream {
    let r_input = raw_input.clone();
    let input_original = parse_macro_input!(r_input as LitStr);
    let (_modifiers, _valid_class_names) = match setup(&input_original) {
        Ok(value) => value,
        Err(value) => {
            return syn::Error::new_spanned(input_original, value)
                .to_compile_error()
                .into()
        }
    };
    let full_classnames = input_original.value();

    let (_input, _class_names) = match parse_single_top(&full_classnames) {
        Ok(value) => value,
        Err(value) => {
            return syn::Error::new_spanned(input_original, value)
                .to_compile_error()
                .into()
        }
    };

    quote::quote! {
        #input_original
    }
    .into()
}

// // Requires featues = full. Dont need it, can just use macrorules
// #[proc_macro]
// pub fn tws(raw_input: TokenStream) -> TokenStream {
//     let input = parse_macro_input!(raw_input as Expr);
//
//     let mut all_classnames = Vec::new();
//
//     match input {
//         Expr::Array(array) => {
//             for expr in array.elems.iter() {
//                 if let Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit_str), .. }) = expr {
//                     all_classnames.push(lit_str.value());
//                 } else {
//                     return syn::Error::new_spanned(expr, "Expected string literals in the array")
//                         .to_compile_error()
//                         .into();
//                 }
//             }
//         }
//         Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit_str), .. }) => {
//             all_classnames.push(lit_str.value());
//         }
//         _ => {
//             return syn::Error::new_spanned(input, "Expected a string literal or an array of string literals")
//                 .to_compile_error()
//                 .into();
//         }
//     }
//
//     let concatenated = all_classnames.join(" ");
//
//     quote::quote! {
//         #concatenated
//     }
//     .into()
// }