java_lang/tree/node/
compilation_unit.rs

1use std::fmt::{Display, Formatter, Result as FmtResult};
2use super::{ImportDeclaration, ModuleDeclaration, PackageDeclaration, TopLevelClassOrInterfaceDeclaration};
3
4/// CompilationUnitDeclaration表示一个编译单元,它是Java程序语法语法的终极符号。
5/// 它可以是普通编译单元或模块编译单元。
6#[derive(Debug)]
7pub enum CompilationUnitDeclaration<'a> {
8    /// 表示一个普通编译单元。
9    /// 它由可选的包声明、import声明和顶层类或接口声明组成。
10    Ordinary {
11        /// 可选的包声明,指定编译单元所属的包的完全限定名。
12        package: Option<PackageDeclaration<'a>>,
13        /// Import声明,允许使用简单名称引用其他包中的类和接口。
14        imports: Vec<ImportDeclaration<'a>>,
15        /// 类和接口的顶层声明。
16        top_level_class_or_interfaces: Vec<TopLevelClassOrInterfaceDeclaration<'a>>,
17    },
18    /// 表示一个模块编译单元。
19    /// 它由import声明和模块声明组成。
20    Modular {
21        /// Import声明,允许在模块声明中引用此模块和其它模块中的包中的类和接口。
22        imports: Vec<ImportDeclaration<'a>>,
23        /// 模块声明,指定编译单元所属的模块。
24        module: ModuleDeclaration<'a>,
25    },
26}
27
28impl<'a> CompilationUnitDeclaration<'a> {
29    /// 获取包声明
30    pub fn package(&self) -> Option<&PackageDeclaration> {
31        if let Self::Ordinary {
32            package: Some(package),
33            ..
34        } = self
35        {
36            return Some(package);
37        }
38        None
39    }
40
41    /// 获取导入声明
42    pub fn imports(&self) -> &[ImportDeclaration] {
43        match self {
44            Self::Ordinary { imports, .. } | Self::Modular { imports, .. } => imports,
45        }
46    }
47}
48
49impl<'a> Display for CompilationUnitDeclaration<'a> {
50    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
51        if let Some(package) = self.package() {
52            Display::fmt(package, f)?;
53        }
54        for i in self.imports() {
55            Display::fmt(&i, f)?;
56            write!(f, "\n")?;
57        }
58        if let Self::Ordinary {
59            top_level_class_or_interfaces,
60            ..
61        } = self
62        {
63            for i in top_level_class_or_interfaces {
64                Display::fmt(&i, f)?;
65                write!(f, "\n")?;
66            }
67        }
68        if let Self::Modular { module, .. } = self {
69            Display::fmt(module, f)?;
70        }
71
72        Ok(())
73    }
74}
75