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
use crate::{
    artifacts::{
        ast::SourceLocation,
        visitor::{Visitor, Walk},
        ContractDefinitionPart, Error, ExternalInlineAssemblyReference, Identifier, IdentifierPath,
        MemberAccess, Source, SourceUnit, SourceUnitPart, Sources,
    },
    error::SolcError,
    resolver::parse::SolData,
    utils, ConfigurableArtifacts, Graph, Project, ProjectCompileOutput, ProjectPathsConfig, Result,
};
use itertools::Itertools;
use std::{
    collections::{HashMap, HashSet},
    hash::Hash,
    path::{Path, PathBuf},
};

/// Alternative of `SourceLocation` which includes path of the file.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct ItemLocation {
    path: PathBuf,
    start: usize,
    end: usize,
}

impl ItemLocation {
    fn try_from_source_loc(src: &SourceLocation, path: PathBuf) -> Option<Self> {
        let start = src.start?;
        let end = start + src.length?;

        Some(ItemLocation { path, start, end })
    }

    fn length(&self) -> usize {
        self.end - self.start
    }
}

/// Visitor exploring AST and collecting all references to declarations via `Identifier` and
/// `IdentifierPath` nodes.
///
/// It also collects `MemberAccess` parts. So, if we have `X.Y` expression, loc and AST ID will be
/// saved for Y only.
///
/// That way, even if we have a long `MemberAccess` expression (a.b.c.d) then the first member (a)
/// will be collected as either `Identifier` or `IdentifierPath`, and all subsequent parts (b, c, d)
/// will be collected as `MemberAccess` parts.
struct ReferencesCollector {
    path: PathBuf,
    references: HashMap<isize, HashSet<ItemLocation>>,
}

impl ReferencesCollector {
    fn process_referenced_declaration(&mut self, id: isize, src: &SourceLocation) {
        if let Some(loc) = ItemLocation::try_from_source_loc(src, self.path.clone()) {
            self.references.entry(id).or_default().insert(loc);
        }
    }
}

impl Visitor for ReferencesCollector {
    fn visit_identifier(&mut self, identifier: &Identifier) {
        if let Some(id) = identifier.referenced_declaration {
            self.process_referenced_declaration(id, &identifier.src);
        }
    }

    fn visit_identifier_path(&mut self, path: &IdentifierPath) {
        self.process_referenced_declaration(path.referenced_declaration, &path.src);
    }

    fn visit_member_access(&mut self, access: &MemberAccess) {
        if let Some(referenced_declaration) = access.referenced_declaration {
            if let (Some(src_start), Some(src_length)) = (access.src.start, access.src.length) {
                let name_length = access.member_name.len();
                // Accessed member name is in the last name.len() symbols of the expression.
                let start = src_start + src_length - name_length;
                let end = start + name_length;

                self.references.entry(referenced_declaration).or_default().insert(ItemLocation {
                    start,
                    end,
                    path: self.path.to_path_buf(),
                });
            }
        }
    }

    fn visit_external_assembly_reference(&mut self, reference: &ExternalInlineAssemblyReference) {
        self.process_referenced_declaration(reference.declaration as isize, &reference.src);
    }
}

/// Updates to be applied to the sources.
/// source_path -> (start, end, new_value)
type Updates = HashMap<PathBuf, HashSet<(usize, usize, String)>>;

pub struct FlatteningResult<'a> {
    /// Updated source in the order they shoud be written to the output file.
    sources: Vec<String>,
    /// Pragmas that should be present in the target file.
    pragmas: Vec<String>,
    /// License identifier that should be present in the target file.
    license: Option<&'a str>,
}

impl<'a> FlatteningResult<'a> {
    fn new(
        flattener: &Flattener,
        mut updates: Updates,
        pragmas: Vec<String>,
        license: Option<&'a str>,
    ) -> Self {
        let mut sources = Vec::new();

        for path in &flattener.ordered_sources {
            let mut content = flattener.sources.get(path).unwrap().content.as_bytes().to_vec();
            let mut offset: isize = 0;
            if let Some(updates) = updates.remove(path) {
                let mut updates = updates.iter().collect::<Vec<_>>();
                updates.sort_by_key(|(start, _, _)| *start);
                for (start, end, new_value) in updates {
                    let start = (*start as isize + offset) as usize;
                    let end = (*end as isize + offset) as usize;

                    content.splice(start..end, new_value.bytes());
                    offset += new_value.len() as isize - (end - start) as isize;
                }
            }
            let content = format!(
                "// {}\n{}",
                path.strip_prefix(&flattener.project_root).unwrap_or(path).display(),
                String::from_utf8(content).unwrap()
            );
            sources.push(content);
        }

        Self { sources, pragmas, license }
    }

    fn get_flattened_target(&self) -> String {
        let mut result = String::new();

        if let Some(license) = &self.license {
            result.push_str(&format!("{}\n", license));
        }
        for pragma in &self.pragmas {
            result.push_str(&format!("{}\n", pragma));
        }
        for source in &self.sources {
            result.push_str(&format!("\n\n{}", source));
        }

        format!("{}\n", utils::RE_THREE_OR_MORE_NEWLINES.replace_all(&result, "\n\n").trim())
    }
}

/// Context for flattening. Stores all sources and ASTs that are in scope of the flattening target.
pub struct Flattener {
    /// Target file to flatten.
    target: PathBuf,
    /// Sources including only target and it dependencies (imports of any depth).
    sources: Sources,
    /// Vec of (path, ast) pairs.
    asts: Vec<(PathBuf, SourceUnit)>,
    /// Sources in the order they should be written to the output file.
    ordered_sources: Vec<PathBuf>,
    /// Project root directory.
    project_root: PathBuf,
}

impl Flattener {
    /// Compilation output is expected to contain all artifacts for all sources.
    /// Flattener caller is expected to resolve all imports of target file, compile them and pass
    /// into this function.
    pub fn new(
        project: &Project,
        output: &ProjectCompileOutput<Error, ConfigurableArtifacts>,
        target: &Path,
    ) -> Result<Self> {
        let input_files = output
            .artifacts_with_files()
            .map(|(file, _, _)| PathBuf::from(file))
            .collect::<HashSet<_>>()
            .into_iter()
            .collect::<Vec<_>>();

        let sources = Source::read_all_files(input_files)?;
        let graph = Graph::resolve_sources(&project.paths, sources)?;

        let ordered_sources = collect_ordered_deps(&target.to_path_buf(), &project.paths, &graph)?;

        #[cfg(windows)]
        let ordered_sources = {
            let mut sources = ordered_sources;
            use path_slash::PathBufExt;
            for p in &mut sources {
                *p = PathBuf::from(p.to_slash_lossy().to_string());
            }
            sources
        };

        let sources = Source::read_all(&ordered_sources)?;

        // Convert all ASTs from artifacts to strongly typed ASTs
        let mut asts: Vec<(PathBuf, SourceUnit)> = Vec::new();
        for (path, ast) in output.artifacts_with_files().filter_map(|(path, _, artifact)| {
            if let Some(ast) = artifact.ast.as_ref() {
                if sources.contains_key(Path::new(path)) {
                    return Some((path, ast));
                }
            }
            None
        }) {
            asts.push((PathBuf::from(path), serde_json::from_str(&serde_json::to_string(ast)?)?));
        }

        Ok(Flattener {
            target: target.into(),
            sources,
            asts,
            ordered_sources,
            project_root: project.root().clone(),
        })
    }

    /// Flattens target file and returns the result as a string
    ///
    /// Flattening process includes following steps:
    /// 1. Find all file-level definitions and rename references to them via aliased or qualified
    ///    imports.
    /// 2. Find all duplicates among file-level definitions and rename them to avoid conflicts.
    /// 3. Remove all imports.
    /// 4. Remove all pragmas except for the ones in the target file.
    /// 5. Remove all license identifiers except for the one in the target file.
    pub fn flatten(&self) -> String {
        let mut updates = Updates::new();

        let top_level_names = self.rename_top_level_definitions(&mut updates);
        self.rename_contract_level_types_references(&top_level_names, &mut updates);
        self.remove_qualified_imports(&mut updates);
        self.update_inheritdocs(&top_level_names, &mut updates);

        self.remove_imports(&mut updates);
        let target_pragmas = self.process_pragmas(&mut updates);
        let target_license = self.process_licenses(&mut updates);

        self.flatten_result(updates, target_pragmas, target_license).get_flattened_target()
    }

    fn flatten_result<'a>(
        &'a self,
        updates: Updates,
        target_pragmas: Vec<String>,
        target_license: Option<&'a str>,
    ) -> FlatteningResult<'_> {
        FlatteningResult::new(self, updates, target_pragmas, target_license)
    }

    /// Finds and goes over all references to file-level definitions and updates them to match
    /// definition name. This is needed for two reasons:
    /// 1. We want to rename all aliased or qualified imports.
    /// 2. We want to find any duplicates and rename them to avoid conflicts.
    ///
    /// If we find more than 1 declaration with the same name, it's name is getting changed.
    /// Two Counter contracts will be renamed to Counter_0 and Counter_1
    ///
    /// Returns mapping from top-level declaration id to its name (possibly updated)
    fn rename_top_level_definitions(&self, updates: &mut Updates) -> HashMap<usize, String> {
        let top_level_definitions = self.collect_top_level_definitions();
        let references = self.collect_references();

        let mut top_level_names = HashMap::new();

        for (name, ids) in top_level_definitions {
            let mut definition_name = name.to_string();
            let needs_rename = ids.len() > 1;

            let mut ids = ids.clone().into_iter().collect::<Vec<_>>();
            if needs_rename {
                // `loc.path` is expected to be different for each id because there can't be 2
                // top-level eclarations with the same name in the same file.
                //
                // Sorting by index loc.path in sorted files to make the renaming process
                // deterministic.
                ids.sort_by_key(|(_, loc)| {
                    self.ordered_sources.iter().position(|p| p == &loc.path).unwrap()
                });
            }
            for (i, (id, loc)) in ids.iter().enumerate() {
                if needs_rename {
                    definition_name = format!("{}_{}", name, i);
                }
                updates.entry(loc.path.clone()).or_default().insert((
                    loc.start,
                    loc.end,
                    definition_name.clone(),
                ));
                if let Some(references) = references.get(&(*id as isize)) {
                    for loc in references {
                        updates.entry(loc.path.clone()).or_default().insert((
                            loc.start,
                            loc.end,
                            definition_name.clone(),
                        ));
                    }
                }

                top_level_names.insert(*id, definition_name.clone());
            }
        }
        top_level_names
    }

    /// This is not very clean, but in most cases effective enough method to remove qualified
    /// imports from sources.
    ///
    /// Every qualified import part is an `Identifier` with `referencedDeclaration` field matching
    /// ID of one of the import directives.
    ///
    /// This approach works by firstly collecting all IDs of import directives, and then looks for
    /// any references of them. Once the reference is found, it's full length is getting removed
    /// from source + 1 charater ('.')
    ///
    /// This should work correctly for vast majority of cases, however there are situations for
    /// which such approach won't work, most of which are related to code being formatted in an
    /// uncommon way.
    fn remove_qualified_imports(&self, updates: &mut Updates) {
        let imports_ids = self
            .asts
            .iter()
            .flat_map(|(_, ast)| {
                ast.nodes.iter().filter_map(|node| match node {
                    SourceUnitPart::ImportDirective(directive) => Some(directive.id),
                    _ => None,
                })
            })
            .collect::<HashSet<_>>();

        let references = self.collect_references();

        for (id, locs) in references {
            if !imports_ids.contains(&(id as usize)) {
                continue;
            }

            for loc in locs {
                updates.entry(loc.path).or_default().insert((
                    loc.start,
                    loc.end + 1,
                    "".to_string(),
                ));
            }
        }
    }

    /// Here we are going through all references to items defined in scope of contracts and updating
    /// them to be using correct parent contract name.
    ///
    /// This will only operate on references from `IdentifierPath` nodes.
    fn rename_contract_level_types_references(
        &self,
        top_level_names: &HashMap<usize, String>,
        updates: &mut Updates,
    ) {
        let contract_level_definitions = self.collect_contract_level_definitions();

        for (path, ast) in &self.asts {
            for node in &ast.nodes {
                let mut collector =
                    ReferencesCollector { path: self.target.clone(), references: HashMap::new() };

                node.walk(&mut collector);

                let references = collector.references;

                for (id, locs) in references {
                    if let Some((name, contract_id)) =
                        contract_level_definitions.get(&(id as usize))
                    {
                        for loc in &locs {
                            // If child item is referenced directly by it's name it's either defined
                            // in the same contract or in one of it's base contracts, so we don't
                            // have to change anything.
                            // Comparing lengths is enough because such items cannot be aliased.
                            if loc.length() == name.len() {
                                continue;
                            }
                            // If it was referenced somehow else, we rename it to `Parent.Child`
                            // format.
                            let parent_name = top_level_names.get(contract_id).unwrap();
                            updates.entry(path.clone()).or_default().insert((
                                loc.start,
                                loc.end,
                                format!("{}.{}", parent_name, name),
                            ));
                        }
                    }
                }
            }
        }
    }

    /// Finds all @inheritdoc tags in natspec comments and tries replacing them.
    ///
    /// We will either replace contract name or remove @inheritdoc tag completely to avoid
    /// generating invalid source code.
    fn update_inheritdocs(&self, top_level_names: &HashMap<usize, String>, updates: &mut Updates) {
        trace!("updating @inheritdoc tags");
        for (path, ast) in &self.asts {
            // Collect all exported symbols for this source unit
            // @inheritdoc value is either one of those or qualified import path which we don't
            // support
            let exported_symbols = ast
                .exported_symbols
                .iter()
                .filter_map(
                    |(name, ids)| {
                        if !ids.is_empty() {
                            Some((name.as_str(), ids[0]))
                        } else {
                            None
                        }
                    },
                )
                .collect::<HashMap<_, _>>();

            // Collect all docs in all contracts
            let docs = ast
                .nodes
                .iter()
                .filter_map(|node| match node {
                    SourceUnitPart::ContractDefinition(d) => Some(d),
                    _ => None,
                })
                .flat_map(|contract| {
                    contract.nodes.iter().filter_map(|node| match node {
                        ContractDefinitionPart::EventDefinition(event) => {
                            event.documentation.as_ref()
                        }
                        ContractDefinitionPart::ErrorDefinition(error) => {
                            error.documentation.as_ref()
                        }
                        ContractDefinitionPart::FunctionDefinition(func) => {
                            func.documentation.as_ref()
                        }
                        ContractDefinitionPart::VariableDeclaration(var) => {
                            var.documentation.as_ref()
                        }
                        _ => None,
                    })
                });

            docs.for_each(|doc| {
                let src_start = doc.src.start.unwrap();
                let src_end = src_start + doc.src.length.unwrap();

                // Documentation node has `text` field, however, it does not contain
                // slashes and we can't use if to find positions.
                let content: &str = &self.sources.get(path).unwrap().content[src_start..src_end];
                let tag_len = "@inheritdoc".len();

                if let Some(tag_start) = content.find("@inheritdoc") {
                    trace!("processing doc with content {:?}", content);
                    if let Some(name_start) = content[tag_start + tag_len..]
                        .find(|c| c != ' ')
                        .map(|p| p + tag_start + tag_len)
                    {
                        let name_end = content[name_start..]
                            .find([' ', '\n', '*', '/'])
                            .map(|p| p + name_start)
                            .unwrap_or(content.len());

                        let name = &content[name_start..name_end];
                        trace!("found name {name}");

                        let mut new_name = None;

                        if let Some(ast_id) = exported_symbols.get(name) {
                            if let Some(name) = top_level_names.get(ast_id) {
                                new_name = Some(name);
                            } else {
                                trace!(identifiers=?top_level_names, "ast id {ast_id} cannot be matched to top-level identifier");
                            }
                        }

                        if let Some(new_name) = new_name {
                            trace!("updating tag value with {new_name}");
                            updates.entry(path.to_path_buf()).or_default().insert((
                                src_start + name_start,
                                src_start + name_end,
                                new_name.to_string(),
                            ));
                        } else {
                            trace!("name is unknown, removing @inheritdoc tag");
                            updates.entry(path.to_path_buf()).or_default().insert((
                                src_start + tag_start,
                                src_start + name_end,
                                "".to_string(),
                            ));
                        }
                    }
                }
            });
        }
    }

    /// Processes all ASTs and collects all top-level definitions in the form of
    /// a mapping from name to (definition id, source location)
    fn collect_top_level_definitions(&self) -> HashMap<&String, HashSet<(usize, ItemLocation)>> {
        self.asts
            .iter()
            .flat_map(|(path, ast)| {
                ast.nodes
                    .iter()
                    .filter_map(|node| match node {
                        SourceUnitPart::ContractDefinition(contract) => Some((
                            &contract.name,
                            contract.id,
                            &contract.src,
                            &contract.name_location,
                        )),
                        SourceUnitPart::EnumDefinition(enum_) => {
                            Some((&enum_.name, enum_.id, &enum_.src, &enum_.name_location))
                        }
                        SourceUnitPart::StructDefinition(struct_) => {
                            Some((&struct_.name, struct_.id, &struct_.src, &struct_.name_location))
                        }
                        SourceUnitPart::FunctionDefinition(func) => {
                            Some((&func.name, func.id, &func.src, &func.name_location))
                        }
                        SourceUnitPart::VariableDeclaration(var) => {
                            Some((&var.name, var.id, &var.src, &var.name_location))
                        }
                        SourceUnitPart::UserDefinedValueTypeDefinition(type_) => {
                            Some((&type_.name, type_.id, &type_.src, &type_.name_location))
                        }
                        _ => None,
                    })
                    .map(|(name, id, src, maybe_name_src)| {
                        let loc = match maybe_name_src {
                            Some(src) => {
                                ItemLocation::try_from_source_loc(src, path.clone()).unwrap()
                            }
                            None => {
                                // Find location of name in source
                                let content: &str = &self.sources.get(path).unwrap().content;
                                let start = src.start.unwrap();
                                let end = start + src.length.unwrap();

                                let name_start = content[start..end].find(name).unwrap();
                                let name_end = name_start + name.len();

                                ItemLocation {
                                    path: path.clone(),
                                    start: start + name_start,
                                    end: start + name_end,
                                }
                            }
                        };

                        (name, (id, loc))
                    })
            })
            .fold(HashMap::new(), |mut acc, (name, (id, item_location))| {
                acc.entry(name).or_default().insert((id, item_location));
                acc
            })
    }

    /// Collect all contract-level definitions in the form of a mapping from definition id to
    /// (definition name, contract id)
    fn collect_contract_level_definitions(&self) -> HashMap<usize, (&String, usize)> {
        self.asts
            .iter()
            .flat_map(|(_, ast)| {
                ast.nodes.iter().filter_map(|node| match node {
                    SourceUnitPart::ContractDefinition(contract) => {
                        Some((contract.id, &contract.nodes))
                    }
                    _ => None,
                })
            })
            .flat_map(|(contract_id, nodes)| {
                nodes.iter().filter_map(move |node| match node {
                    ContractDefinitionPart::EnumDefinition(enum_) => {
                        Some((enum_.id, (&enum_.name, contract_id)))
                    }
                    ContractDefinitionPart::ErrorDefinition(error) => {
                        Some((error.id, (&error.name, contract_id)))
                    }
                    ContractDefinitionPart::EventDefinition(event) => {
                        Some((event.id, (&event.name, contract_id)))
                    }
                    ContractDefinitionPart::StructDefinition(struct_) => {
                        Some((struct_.id, (&struct_.name, contract_id)))
                    }
                    ContractDefinitionPart::FunctionDefinition(function) => {
                        Some((function.id, (&function.name, contract_id)))
                    }
                    ContractDefinitionPart::VariableDeclaration(variable) => {
                        Some((variable.id, (&variable.name, contract_id)))
                    }
                    ContractDefinitionPart::UserDefinedValueTypeDefinition(value_type) => {
                        Some((value_type.id, (&value_type.name, contract_id)))
                    }
                    _ => None,
                })
            })
            .collect()
    }

    /// Collects all references to any declaration in the form of a mapping from declaration id to
    /// set of source locations it appears in
    fn collect_references(&self) -> HashMap<isize, HashSet<ItemLocation>> {
        self.asts
            .iter()
            .flat_map(|(path, ast)| {
                let mut collector =
                    ReferencesCollector { path: path.clone(), references: HashMap::new() };
                ast.walk(&mut collector);
                collector.references
            })
            .fold(HashMap::new(), |mut acc, (id, locs)| {
                acc.entry(id).or_default().extend(locs);
                acc
            })
    }

    /// Removes all imports from all sources.
    fn remove_imports(&self, updates: &mut Updates) {
        for loc in self.collect_imports() {
            updates.entry(loc.path.clone()).or_default().insert((
                loc.start,
                loc.end,
                "".to_string(),
            ));
        }
    }

    // Collects all imports locations.
    fn collect_imports(&self) -> HashSet<ItemLocation> {
        self.asts
            .iter()
            .flat_map(|(path, ast)| {
                ast.nodes.iter().filter_map(|node| match node {
                    SourceUnitPart::ImportDirective(import) => {
                        ItemLocation::try_from_source_loc(&import.src, path.clone())
                    }
                    _ => None,
                })
            })
            .collect()
    }

    /// Removes all pragma directives from all sources. Returns Vec with experimental and combined
    /// version pragmas (if present).
    fn process_pragmas(&self, updates: &mut Updates) -> Vec<String> {
        let mut experimental = None;

        let pragmas = self.collect_pragmas();
        let mut version_pragmas = Vec::new();

        for loc in &pragmas {
            let pragma_content = self.read_location(loc);
            if pragma_content.contains("experimental") {
                if experimental.is_none() {
                    experimental = Some(self.read_location(loc).to_string());
                }
            } else if pragma_content.contains("solidity") {
                version_pragmas.push(pragma_content);
            }

            updates.entry(loc.path.clone()).or_default().insert((
                loc.start,
                loc.end,
                "".to_string(),
            ));
        }

        let mut pragmas = Vec::new();

        if let Some(version_pragma) = combine_version_pragmas(version_pragmas) {
            pragmas.push(version_pragma);
        }

        if let Some(pragma) = experimental {
            pragmas.push(pragma);
        }

        pragmas
    }

    // Collects all pragma directives locations.
    fn collect_pragmas(&self) -> HashSet<ItemLocation> {
        self.asts
            .iter()
            .flat_map(|(path, ast)| {
                ast.nodes.iter().filter_map(|node| match node {
                    SourceUnitPart::PragmaDirective(import) => {
                        ItemLocation::try_from_source_loc(&import.src, path.clone())
                    }
                    _ => None,
                })
            })
            .collect()
    }

    /// Removes all license identifiers from all sources. Returns licesnse identifier from target
    /// file, if any.
    fn process_licenses(&self, updates: &mut Updates) -> Option<&str> {
        let mut target_license = None;

        for loc in &self.collect_licenses() {
            if loc.path == self.target {
                target_license = Some(self.read_location(loc));
            }
            updates.entry(loc.path.clone()).or_default().insert((
                loc.start,
                loc.end,
                "".to_string(),
            ));
        }

        target_license
    }

    // Collects all SPDX-License-Identifier locations.
    fn collect_licenses(&self) -> HashSet<ItemLocation> {
        self.sources
            .iter()
            .flat_map(|(path, source)| {
                let mut licenses = HashSet::new();
                if let Some(license_start) = source.content.find("SPDX-License-Identifier:") {
                    let start =
                        source.content[..license_start].rfind('\n').map(|i| i + 1).unwrap_or(0);
                    let end = start
                        + source.content[start..]
                            .find('\n')
                            .unwrap_or(source.content.len() - start);
                    licenses.insert(ItemLocation { path: path.clone(), start, end });
                }
                licenses
            })
            .collect()
    }

    // Reads value from the given location of a source file.
    fn read_location(&self, loc: &ItemLocation) -> &str {
        let content: &str = &self.sources.get(&loc.path).unwrap().content;
        &content[loc.start..loc.end]
    }
}

/// Performs DFS to collect all dependencies of a target
fn collect_deps<C>(
    path: &PathBuf,
    paths: &ProjectPathsConfig<C>,
    graph: &Graph,
    deps: &mut HashSet<PathBuf>,
) -> Result<()> {
    if deps.insert(path.clone()) {
        let target_dir = path.parent().ok_or_else(|| {
            SolcError::msg(format!("failed to get parent directory for \"{}\"", path.display()))
        })?;

        let node_id = graph
            .files()
            .get(path)
            .ok_or_else(|| SolcError::msg(format!("cannot resolve file at {}", path.display())))?;

        for import in &graph.node(*node_id).data.imports {
            let path = paths.resolve_import(target_dir, import.data().path())?;
            collect_deps(&path, paths, graph, deps)?;
        }
    }
    Ok(())
}

/// We want to make order in which sources are written to resulted flattened file
/// deterministic.
///
/// We can't just sort files alphabetically as it might break compilation, because Solidity
/// does not allow base class definitions to appear after derived contract
/// definitions.
///
/// Instead, we sort files by the number of their dependencies (imports of any depth) in ascending
/// order. If files have the same number of dependencies, we sort them alphabetically.
/// Target file is always placed last.
pub fn collect_ordered_deps<C>(
    path: &PathBuf,
    paths: &ProjectPathsConfig<C>,
    graph: &Graph,
) -> Result<Vec<PathBuf>> {
    let mut deps = HashSet::new();
    collect_deps(path, paths, graph, &mut deps)?;

    // Remove path prior counting dependencies
    // It will be added later to the end of resulted Vec
    deps.remove(path);

    let mut paths_with_deps_count = Vec::new();
    for path in deps {
        let mut path_deps = HashSet::new();
        collect_deps(&path, paths, graph, &mut path_deps)?;
        paths_with_deps_count.push((path_deps.len(), path));
    }

    paths_with_deps_count.sort();

    let mut ordered_deps =
        paths_with_deps_count.into_iter().map(|(_, path)| path).collect::<Vec<_>>();

    ordered_deps.push(path.clone());

    Ok(ordered_deps)
}

pub fn combine_version_pragmas(pragmas: Vec<&str>) -> Option<String> {
    let mut versions = pragmas
        .into_iter()
        .filter_map(|p| {
            SolData::parse_version_req(
                p.replace("pragma", "").replace("solidity", "").replace(';', "").trim(),
            )
            .ok()
        })
        .flat_map(|req| req.comparators)
        .collect::<HashSet<_>>()
        .into_iter()
        .map(|comp| comp.to_string())
        .collect::<Vec<_>>();

    versions.sort();

    if !versions.is_empty() {
        return Some(format!("pragma solidity {};", versions.iter().format(" ")));
    }

    None
}