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

use anyhow::{anyhow, Context, Error, Result};
use clang::{Clang, CompilationDatabase, Index, TranslationUnit, Usr};
use codemap::CodeMap;
use thiserror::Error;

use std::collections::BTreeMap;
use std::convert::{TryFrom, TryInto};
use std::path::{Path, PathBuf};

// TODO: check for use of Extend instead of loop+insert

#[derive(Debug, Default)]
struct TopLevel {
    namespaces: BTreeMap<Usr, Described<Namespace>>,
    variables: BTreeMap<Usr, Described<Variable>>,
    structs: BTreeMap<Usr, Described<Struct>>,
    functions: BTreeMap<Usr, Described<Function>>,
    typedefs: BTreeMap<Usr, Described<Typedef>>,
}

/*
enum TopLevelEntry<'a, T> {
    Vacant {
        parent: &'a mut Described<Namespace>,
    },
    /// Vacant, but no semantic parent
    TopLevel,
    Occupied {
        entity: &'a mut Described<T>,
    },
    Error,
}
*/

impl TopLevel {
    // Somehow has a lifetime issue I can't get my head around
    /*
    fn entry<'a, T>(&'a mut self, path: &::clang::Entity) -> Result<TopLevelEntry<'a, T>>
    where
        T: ClangEntity + FromNamespaceParent + FromTopLevel,
    {
        let usr = path.get_usr().ok_or_else(|| anyhow!("no usr"))?;
        if let Some(parent_path) = parent(&path) {
            let parent_entry = self.entry::<Namespace>(&parent_path)?;
            if let TopLevelEntry::Occupied {
                entity: namespace_parent,
            } = parent_entry
            {
                Ok(match T::from_namespace_parent(namespace_parent, &usr) {
                    None => TopLevelEntry::Vacant {
                        parent: namespace_parent,
                    },
                    Some(entity) => TopLevelEntry::Occupied { entity },
                })
            } else {
                panic!("Wut");
            }
        } else {
            Ok(match T::from_toplevel(self, &usr) {
                Some(entity) => TopLevelEntry::Occupied { entity },
                None => TopLevelEntry::TopLevel,
            })
        }
    }
    */

    fn get_entity_mut(&mut self, path: clang::Entity) -> Option<&mut dyn ClangEntity> {
        let usr = path.get_usr()?;
        if let Some(parent_path) = parent(path) {
            let parent = self.get_entity_mut(parent_path)?;
            Some(match path.get_kind().try_into().ok()? {
                ClangEntityKind::Namespace => {
                    &mut parent.get_member_namespaces()?.get_mut(&usr)?.entity
                }
                ClangEntityKind::Variable(_) => {
                    &mut parent.get_member_variables()?.get_mut(&usr)?.entity
                }
                ClangEntityKind::Function(_) => {
                    &mut parent.get_member_functions()?.get_mut(&usr)?.entity
                }
                ClangEntityKind::Struct(_) => {
                    &mut parent.get_member_structs()?.get_mut(&usr)?.entity
                }
                ClangEntityKind::Typedef => {
                    &mut parent.get_member_typedefs()?.get_mut(&usr)?.entity
                }
            })
        } else {
            Some(match path.get_kind().try_into().ok()? {
                ClangEntityKind::Namespace => &mut self.namespaces.get_mut(&usr)?.entity,
                ClangEntityKind::Variable(_) => &mut self.variables.get_mut(&usr)?.entity,
                ClangEntityKind::Struct(_) => &mut self.structs.get_mut(&usr)?.entity,
                ClangEntityKind::Function(_) => &mut self.functions.get_mut(&usr)?.entity,
                ClangEntityKind::Typedef => &mut self.typedefs.get_mut(&usr)?.entity,
            })
        }
    }

    fn get_namespace_mut(&mut self, path: clang::Entity) -> Option<&mut Described<Namespace>> {
        let usr = path.get_usr()?;

        if let Some(parent_path) = parent(path) {
            let parent = self.get_entity_mut(parent_path)?;
            parent.get_member_namespaces()?.get_mut(&usr)
        } else {
            self.namespaces.get_mut(&usr)
        }
    }

    fn insert<T>(&mut self, path: clang::Entity, entity: Described<T>) -> Result<()>
    where
        T: ClangEntity + std::fmt::Debug,
        Self: TopLevelManipulation<T>,
        Namespace: NamespaceParentManipulation<T>,
    {
        let usr = path.get_usr().ok_or_else(|| anyhow!("no usr"))?;
        if let Some(parent_path) = parent(path) {
            if let Some(parent_namespace) = self.get_namespace_mut(parent_path) {
                parent_namespace
                    .entity
                    .get_members_mut()
                    // Namespace should be able to contain every kind of entity
                    .unwrap()
                    .insert(usr, entity);
                Ok(())
            } else {
                Err(anyhow!(
                    "has parent: {:?} but no parent in tree",
                    parent_path
                ))
            }
        } else {
            self.insert_toplevel(usr, entity);
            Ok(())
        }
    }
}

// Like .get_semantic_parent(), but return none if the parent is the translation unit
fn parent(libclang_entity: clang::Entity) -> Option<clang::Entity> {
    match libclang_entity.get_semantic_parent() {
        Some(parent) => {
            if parent.get_kind() != clang::EntityKind::TranslationUnit {
                Some(parent)
            } else {
                None
            }
        }
        None => {
            warn!("get_semantic_parent() returned None");
            None
        }
    }
}

trait TopLevelManipulation<T: ClangEntity> {
    fn insert_toplevel(&mut self, usr: Usr, entity: Described<T>);
}

impl TopLevelManipulation<Namespace> for TopLevel {
    fn insert_toplevel(&mut self, usr: Usr, entity: Described<Namespace>) {
        self.namespaces.insert(usr, entity);
    }
}

impl TopLevelManipulation<Variable> for TopLevel {
    fn insert_toplevel(&mut self, usr: Usr, entity: Described<Variable>) {
        self.variables.insert(usr, entity);
    }
}

impl TopLevelManipulation<Function> for TopLevel {
    fn insert_toplevel(&mut self, usr: Usr, entity: Described<Function>) {
        self.functions.insert(usr, entity);
    }
}

impl TopLevelManipulation<Struct> for TopLevel {
    fn insert_toplevel(&mut self, usr: Usr, entity: Described<Struct>) {
        self.structs.insert(usr, entity);
    }
}

impl TopLevelManipulation<Typedef> for TopLevel {
    fn insert_toplevel(&mut self, usr: Usr, entity: Described<Typedef>) {
        self.typedefs.insert(usr, entity);
    }
}

/*
trait FromTopLevel: ClangEntity + Sized {
    fn from_toplevel<'a>(toplevel: &'a mut TopLevel, usr: &Usr) -> Option<&'a mut Described<Self>>;
}

impl FromTopLevel for Namespace {
    fn from_toplevel<'a>(toplevel: &'a mut TopLevel, usr: &Usr) -> Option<&'a mut Described<Self>> {
        toplevel.namespaces.get_mut(usr)
    }
}

impl FromTopLevel for Variable {
    fn from_toplevel<'a>(toplevel: &'a mut TopLevel, usr: &Usr) -> Option<&'a mut Described<Self>> {
        toplevel.variables.get_mut(usr)
    }
}

impl FromTopLevel for Function {
    fn from_toplevel<'a>(toplevel: &'a mut TopLevel, usr: &Usr) -> Option<&'a mut Described<Self>> {
        toplevel.functions.get_mut(usr)
    }
}

impl FromTopLevel for Struct {
    fn from_toplevel<'a>(toplevel: &'a mut TopLevel, usr: &Usr) -> Option<&'a mut Described<Self>> {
        toplevel.structs.get_mut(usr)
    }
}
*/

pub(crate) fn parse_compile_commands(
    config: &Config,
    codemap: &mut CodeMap,
) -> Result<BTreeMap<EntityId, Entity>> {
    let clang = Clang::new().unwrap();
    let index = Index::new(
        &clang, /* exclude from pch = */ false, /* print diagnostics = */ false,
    );

    debug!("Extra libclang argument: {:?}", config.extra_args);

    debug!(
        "Loading compile commands from: {:?}",
        config.compile_commands_location
    );
    let database =
        CompilationDatabase::from_directory(&config.compile_commands_location).map_err(|()| {
            CompileCommandsLoadError {
                path: config.compile_commands_location.clone(),
            }
        })?;

    let toplevel_directory = std::env::current_dir().context("Cannot read current directory")?;

    let mut entities = TopLevel::default();

    for command in database.get_all_compile_commands().get_commands() {
        let directory = command.get_directory();
        trace!("Changing directory to: {:?}", directory);
        std::env::set_current_dir(&directory)
            .with_context(|| format!("Cannot change current directory to: {:?}", directory))?;

        let filename = command.get_filename();

        let file_map = codemap.add_file(
            filename
                .to_str()
                .context("File is not valid UTF-8")?
                .to_owned(),
            std::fs::read_to_string(&filename)
                .with_context(|| format!("Cannot readfile: {:?}", filename))?,
        );

        trace!("Parsing file: {:?}", filename);
        // The file name is passed as an argument in the compile commands
        let mut parser = index.parser("");
        parser.skip_function_bodies(true);

        let mut clang_arguments = command.get_arguments();
        clang_arguments.extend_from_slice(&config.extra_args);
        trace!("Parsing with libclang arguments: {:?}", clang_arguments);
        parser.arguments(&clang_arguments);

        parse_unit(
            &parser
                .parse()
                .with_context(|| format!("Could not parse file: {:?}", filename))?,
            &mut entities,
            &toplevel_directory,
            file_map.span,
            &codemap,
        )?;

        trace!("Changing directory to: {:?}", toplevel_directory);
        std::env::set_current_dir(&toplevel_directory).with_context(|| {
            format!(
                "Cannot change current directory to: {:?}",
                toplevel_directory
            )
        })?;
    }

    Ok(entities.into())
}

pub(crate) fn parse_file<T>(
    path: T,
    config: &Config,
    codemap: &mut CodeMap,
) -> Result<BTreeMap<EntityId, Entity>>
where
    T: Into<PathBuf>,
    T: AsRef<Path>,
    T: ToString,
{
    let clang = Clang::new().unwrap();
    let index = Index::new(&clang, true, false);

    // as provided in the command line
    let filename = path.to_string();
    let file_map = codemap.add_file(filename.clone(), std::fs::read_to_string(&path)?);

    let path = path.as_ref().canonicalize()?;
    let toplevel_directory = std::env::current_dir().context("Cannot read current directory")?;

    let maybe_commands = CompilationDatabase::from_directory(&config.compile_commands_location)
        .and_then(|database| database.get_compile_commands(&path))
        .ok();
    let maybe_command = maybe_commands
        .as_ref()
        .and_then(|commands| commands.get_commands().pop());

    let mut clang_arguments = maybe_command
        .map(|command| command.get_arguments())
        .unwrap_or_default();
    clang_arguments.extend_from_slice(&config.extra_args);

    if let Some(command) = maybe_command {
        let directory = command.get_directory();
        trace!("Changing directory to: {:?}", directory);
        std::env::set_current_dir(&directory)
            .with_context(|| format!("Cannot change current directory to: {:?}", directory))?;
    }

    let mut parser = index.parser("");
    parser.skip_function_bodies(true);

    parser.arguments(&clang_arguments);

    trace!("Parsing with libclang arguments: {:?}", clang_arguments);

    let mut entities = TopLevel::default();

    parse_unit(
        &parser
            .parse()
            .with_context(|| format!("Could not parse file: {:?}", filename))?,
        &mut entities,
        &toplevel_directory,
        file_map.span,
        &codemap,
    )?;

    trace!("Changing directory to: {:?}", toplevel_directory);
    std::env::set_current_dir(&toplevel_directory).with_context(|| {
        format!(
            "Cannot change current directory to: {:?}",
            toplevel_directory
        )
    })?;

    Ok(entities.into())
}

fn parse_unit(
    trans_unit: &TranslationUnit,
    entities: &mut TopLevel,
    base_dir: impl AsRef<Path>,
    file_span: codemap::Span,
    codemap: &CodeMap,
) -> Result<()> {
    trans_unit.get_entity().visit_children(|entity, _parent| {
        if is_in_system_header(entity, &base_dir) {
            trace!("Entity is in system header, skipping: {:?}", entity);
            return clang::EntityVisitResult::Continue;
        }

        // TODO: wrap this callback in another function so that we can use the
        // "?" operator instead of all these `match`es
        let usr = match entity.get_usr() {
            Some(usr) => usr,
            None => return clang::EntityVisitResult::Continue,
        };
        trace!("Entity with USR = {:?}", usr);
        debug!("Parsing toplevel entity: {:?}", entity);

        add_entity(entity, entities, file_span, codemap)
    });

    use codemap_diagnostic::{ColorConfig, Emitter};

    let mut emitter = Emitter::stderr(ColorConfig::Auto, Some(&codemap));

    for diagnostic in trans_unit.get_diagnostics().iter() {
        warn!("{}", diagnostic);
        /*
        let main_diag = match clang_diag_to_codemap_diag(&diagnostic, file_span) {
            Some(diag) => diag,
            None => continue,
        };

        let sub_diags = diagnostic
            .get_children()
            .into_iter()
            .filter_map(|diagnostic| clang_diag_to_codemap_diag(&diagnostic, file_span));

        let fix_it_diags = diagnostic
            .get_fix_its()
            .into_iter()
            .map(|fix_it| clang_fix_it_to_codemap_diag(&fix_it, file_span));

        emitter.emit(
            &std::iter::once(main_diag)
                .chain(sub_diags)
                .chain(fix_it_diags)
                .collect::<Vec<_>>(),
        );
        */
    }

    Ok(())
}

fn is_in_system_header(entity: clang::Entity, base_dir: impl AsRef<Path>) -> bool {
    if entity.is_in_system_header() {
        true
    } else if let Some(location) = entity.get_location() {
        if let Some(file) = location.get_file_location().file {
            // !file
            //     .get_path()
            //     .canonicalize()
            //     .unwrap()
            //     .starts_with(base_dir)
            false
        } else {
            // Not defined in a file? probably shouldn't document
            true
        }
    } else {
        // Not defined anywhere? probably shouldn't document
        true
    }
}

// Entries encountered in the toplevel lexical context
fn add_entity(
    libclang_entity: clang::Entity,
    toplevel: &mut TopLevel,
    file_span: codemap::Span,
    codemap: &CodeMap,
) -> clang::EntityVisitResult {
    if libclang_entity.get_usr().is_none() {
        return clang::EntityVisitResult::Continue;
    };

    let kind = match ClangEntityKind::try_from(libclang_entity.get_kind()) {
        Ok(kind) => kind,
        Err(err) => {
            use codemap_diagnostic::{
                ColorConfig, Diagnostic, Emitter, Level, SpanLabel, SpanStyle,
            };
            let spans = if let Some(range) = libclang_entity.get_range() {
                // TODO: add every file parsed in this translation unit to the
                // codemap, so we can properly report errors
                if !range.is_in_main_file() {
                    vec![]
                } else {
                    let begin = range.get_start().get_file_location().offset as u64;
                    let end = range.get_end().get_file_location().offset as u64;

                    vec![SpanLabel {
                        span: file_span.subspan(begin, end),
                        label: None,
                        style: SpanStyle::Primary,
                    }]
                }
            } else {
                vec![]
            };

            let diag = Diagnostic {
                level: Level::Warning,
                message: format!("{}", err),
                code: None,
                spans,
            };

            let mut emitter = Emitter::stderr(ColorConfig::Auto, Some(codemap));
            emitter.emit(&[diag]);

            return clang::EntityVisitResult::Continue;
        }
    };

    if let Some(in_tree_entity) = toplevel.get_entity_mut(libclang_entity) {
        // if current.has_documentation && !tree.has_documentation {
        //     append_documentation
        // }
    } else {
        //if libclang_entity.is_definition() {
        // TODO: This probably means that you can't put documentation in forward declarations.
        // TODO: Ad-hoc toplevel functions are not documented
        //
        // This seems restrictive, but since there can be multiple declarations but only one definition,
        // you should probably put your documentation on the definition anyway?
        //
        // Also, skipping forward declarations allows us to not have to insert, then update the tree
        // when we see the definition.

        let result = match kind {
            ClangEntityKind::Namespace => {
                if libclang_entity.get_name().is_some() {
                    Described::<Namespace>::try_from(libclang_entity)
                        .and_then(|namespace| toplevel.insert(libclang_entity, namespace))
                } else {
                    Ok(())
                }
            }
            ClangEntityKind::Variable(_) => Described::<Variable>::try_from(libclang_entity)
                .and_then(|variable| toplevel.insert(libclang_entity, variable)),
            ClangEntityKind::Struct(_) => Described::<Struct>::try_from(libclang_entity)
                .and_then(|r#struct| toplevel.insert(libclang_entity, r#struct)),
            ClangEntityKind::Function(_) => Described::<Function>::try_from(libclang_entity)
                .and_then(|function| toplevel.insert(libclang_entity, function)),
            ClangEntityKind::Typedef => Described::<Typedef>::try_from(libclang_entity)
                .and_then(|function| toplevel.insert(libclang_entity, function)),
        };
        // TODO: check result

        if let Err(err) = result {
            error!("{}: {:?}", err, libclang_entity);
            return ::clang::EntityVisitResult::Continue;
        }
    }

    if kind == ClangEntityKind::Namespace && libclang_entity.get_name().is_some() {
        // Recurse here since namespace definitions are allowed to change between translation units.
        ::clang::EntityVisitResult::Recurse
    } else {
        ::clang::EntityVisitResult::Continue
    }
}

impl From<TopLevel> for BTreeMap<EntityId, Entity> {
    fn from(toplevel: TopLevel) -> Self {
        toplevel
            .namespaces
            .into_iter()
            .map(|(usr, entity)| (EntityId(usr.0), entity.into()))
            .chain(
                toplevel
                    .variables
                    .into_iter()
                    .map(|(usr, entity)| (EntityId(usr.0), entity.into())),
            )
            .chain(
                toplevel
                    .structs
                    .into_iter()
                    .map(|(usr, entity)| (EntityId(usr.0), entity.into())),
            )
            .chain(
                toplevel
                    .functions
                    .into_iter()
                    .map(|(usr, entity)| (EntityId(usr.0), entity.into())),
            )
            .chain(
                toplevel
                    .typedefs
                    .into_iter()
                    .map(|(usr, entity)| (EntityId(usr.0), entity.into())),
            )
            .collect()
    }
}

impl<'a, T> TryFrom<clang::Entity<'a>> for Described<T>
where
    T: TryFrom<clang::Entity<'a>, Error = Error>,
{
    type Error = Error;

    fn try_from(entity: clang::Entity<'a>) -> Result<Self, Error> {
        Ok(Described::<T> {
            description: get_description(entity)?,
            entity: T::try_from(entity)?,
        })
    }
}

impl<'a> TryFrom<clang::Entity<'a>> for Namespace {
    type Error = Error;

    fn try_from(entity: clang::Entity) -> Result<Self, Error> {
        match entity.get_kind().try_into() {
            Ok(ClangEntityKind::Namespace) => {}
            _ => panic!("Trying to parse a non-variable into a variable"),
        }
        debug!("Parsing Namespace: {:?}", entity);

        // Do not recurse here, but recurse in the main loop, since namespace
        // definitions is allowed to change between translation units

        Ok(Namespace {
            member_namespaces: Default::default(),
            member_variables: Default::default(),
            member_structs: Default::default(),
            member_functions: Default::default(),
            member_typedefs: Default::default(),
        })
    }
}

impl<'a> TryFrom<clang::Entity<'a>> for Variable {
    type Error = Error;

    fn try_from(entity: clang::Entity) -> Result<Self, Error> {
        let variable_kind;
        match entity.get_kind().try_into() {
            Ok(ClangEntityKind::Variable(kind)) => {
                variable_kind = kind;
            }
            _ => panic!("Trying to parse a non-variable into a variable"),
        }
        debug!("Parsing Variable: {:?}", entity);

        let r#type = entity.get_type().unwrap().get_display_name();
        trace!("Variable has type: {:?}", r#type);

        Ok(Variable {
            r#type,
            kind: variable_kind,
        })
    }
}

impl<'a> TryFrom<clang::Entity<'a>> for Struct {
    type Error = Error;

    fn try_from(entity: clang::Entity) -> Result<Self, Error> {
        let struct_kind;
        match entity.get_kind().try_into() {
            Ok(ClangEntityKind::Struct(kind)) => {
                struct_kind = kind;
            }
            _ => panic!("Trying to parse a non-struct into a struct"),
        }
        debug!("Parsing Struct: {:?}", entity);

        let mut member_variables = BTreeMap::new();
        let mut member_structs = BTreeMap::new();
        let mut member_functions = BTreeMap::new();
        let mut member_typedefs = BTreeMap::new();

        for child in entity.get_children() {
            trace!("Struct has child: {:?}", child);

            let kind = child.get_kind();

            match kind {
                ::clang::EntityKind::AccessSpecifier | ::clang::EntityKind::BaseSpecifier => {
                    continue
                }
                _ => {}
            }

            let mut parse_child = || -> Result<()> {
                match kind.try_into() {
                    Ok(ClangEntityKind::Variable(_)) => {
                        let child_usr = child
                            .get_usr()
                            .ok_or_else(|| anyhow!("no usr for: {:?}", child))?;
                        member_variables.insert(child_usr, Described::<Variable>::try_from(child)?);
                    }
                    Ok(ClangEntityKind::Struct(_)) => {
                        let child_usr: Usr = child
                            .get_usr()
                            .ok_or_else(|| anyhow!("no usr for: {:?}", child))?;
                        member_structs.insert(child_usr, Described::<Struct>::try_from(child)?);
                    }
                    Ok(ClangEntityKind::Function(_)) => {
                        let child_usr = child
                            .get_usr()
                            .ok_or_else(|| anyhow!("no usr for: {:?}", child))?;
                        member_functions.insert(child_usr, Described::<Function>::try_from(child)?);
                    }
                    Ok(ClangEntityKind::Typedef) => {
                        let child_usr = child
                            .get_usr()
                            .ok_or_else(|| anyhow!("no usr for: {:?}", child))?;
                        member_typedefs.insert(child_usr, Described::<Typedef>::try_from(child)?);
                    }
                    Ok(other) => warn!("Unsupported child of struct {:?}: {:?}", other, child),
                    Err(err) => info!("Error while parsing entity {:?}: {}", child, err),
                }

                Ok(())
            };

            match parse_child() {
                Ok(()) => {}
                Err(err) => {
                    warn!("Error while parsing child {:?}: {}", child, err);
                }
            }
        }

        Ok(Struct {
            kind: struct_kind,
            member_functions,
            member_structs,
            member_variables,
            member_typedefs,
        })
    }
}

impl<'a> TryFrom<clang::Entity<'a>> for Function {
    type Error = Error;

    fn try_from(entity: clang::Entity) -> Result<Self, Error> {
        let function_kind;
        match entity.get_kind().try_into() {
            Ok(ClangEntityKind::Function(kind)) => {
                function_kind = kind;
            }
            _ => panic!("Trying to parse a non-function into a function"),
        }
        debug!("Parsing Function: {:?}", entity);

        let return_type = entity.get_result_type().unwrap().get_display_name();
        trace!("Function has return type: {:?}", return_type);
        let arguments = entity
            .get_arguments()
            // TODO: this seems weird, but it fixes a None for a function that takes only a
            // variadic argument from its own template declaration.
            .unwrap_or_else(|| vec![])
            .into_iter()
            .map(|arg| {
                let name = arg
                    .get_display_name()
                    .unwrap_or_else(|| String::from("unnamed"));
                let r#type = arg.get_type().unwrap().get_display_name();
                trace!("Function has argument {:?} of type {:?}", name, r#type);
                FunctionArgument { name, r#type }
            })
            .collect();

        Ok(Function {
            kind: function_kind,
            arguments,
            return_type,
        })
    }
}

impl<'a> TryFrom<clang::Entity<'a>> for Typedef {
    type Error = Error;

    fn try_from(entity: clang::Entity) -> Result<Self, Error> {
        match entity.get_kind().try_into() {
            Ok(ClangEntityKind::Typedef) => {}
            _ => panic!("Trying to parse a non-typedef into a typedef"),
        }
        debug!("Parsing typedef: {:?}", entity);

        // TODO: unwrap (and unwrap in other similar places too)
        let referee = entity
            .get_typedef_underlying_type()
            .ok_or_else(|| anyhow!("No underlying type"))?
            .get_display_name();

        Ok(Typedef { referee })
    }
}

fn get_description(entity: clang::Entity) -> Result<Description> {
    let name = entity
        .get_display_name()
        .ok_or_else(|| anyhow!("Entity has no name: {:?}", entity))?;

    // TODO: is that the best?
    if let (Some(brief), Some(comment)) = (entity.get_comment_brief(), entity.get_comment()) {
        Ok(Description {
            name,
            brief,
            detailed: parse_comment(comment),
        })
    } else {
        Ok(Description {
            name,
            brief: String::new(),
            detailed: String::new(),
        })
    }
}

pub fn parse_comment(raw: String) -> String {
    #[derive(Debug)]
    enum CommentStyle {
        // Comments of type `/**` or `/*!`
        Starred,
        // Comments of type `///`
        SingleLine,
    }

    let mut chars = raw.chars();
    let style = match &chars.as_str()[..3] {
        "/*!" | "/**" => CommentStyle::Starred,
        "///" => CommentStyle::SingleLine,
        _ => panic!("Comment is empty or doesn't start with either `///`, `/**`, or `/*!`"),
    };

    chars.nth(2);

    let mut result = String::new();

    'parse_loop: loop {
        let maybe_space = chars.next();
        let mut empty_line = false;
        match maybe_space {
            // TODO: Warn on empty comments
            None => break,
            Some(' ') => {}
            Some('\n') => {
                empty_line = true;
                result.push('\n');
            }
            Some(ch) => result.push(ch),
        }

        if !empty_line {
            let rest = chars.as_str();
            match rest.find('\n') {
                None => {
                    result.push_str(rest);
                    break;
                }
                Some(position) => {
                    result.push_str(&rest[..=position]);
                    chars.nth(position);
                }
            }
        }

        // Beginning of the line
        let first_non_ws_ch = 'ws_loop: loop {
            let maybe_whitespace = chars.next();
            match maybe_whitespace {
                None => break 'parse_loop,
                Some(ch) if ch.is_whitespace() => continue,
                Some(ch) => break 'ws_loop ch,
            }
        };

        match style {
            CommentStyle::Starred if first_non_ws_ch == '*' => {
                if &chars.as_str()[..1] == "/" {
                    break;
                }
            }
            CommentStyle::Starred => result.push(first_non_ws_ch),
            CommentStyle::SingleLine => {
                assert!(first_non_ws_ch == '/');
                let rest = chars.as_str();
                if &rest[..2] == "//" {
                    chars.nth(1);
                } else if &rest[..1] == "/" {
                    chars.nth(0);
                } else {
                    panic!("Could not parse comment");
                }
            }
        }
    }

    result
}

#[derive(Debug, Clone, Error)]
#[error("Failed to load 'compile_commands.json' at path: {:?}", path)]
pub(crate) struct CompileCommandsLoadError {
    path: PathBuf,
}