ion/format/
function.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 */
6
7use std::fmt;
8use std::fmt::{Display, Formatter};
9
10use colored::Colorize as _;
11use indent::indent_by;
12
13use crate::format::Config;
14use crate::{Context, Function};
15
16/// Formats a [function](Function), using the given [configuration](Config).
17///
18/// ### Format
19/// ```js
20/// function <#name>(<#arguments, ...>) {
21///   <#body>
22/// }
23/// ```
24pub fn format_function<'cx>(cx: &'cx Context, cfg: Config, function: &'cx Function<'cx>) -> FunctionDisplay<'cx> {
25	FunctionDisplay { cx, function, cfg }
26}
27
28#[must_use]
29pub struct FunctionDisplay<'cx> {
30	cx: &'cx Context,
31	function: &'cx Function<'cx>,
32	cfg: Config,
33}
34
35impl Display for FunctionDisplay<'_> {
36	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
37		if let Some(func) = self.function.to_string(self.cx) {
38			let spaces = 2 * (self.cfg.indentation + self.cfg.depth);
39			write!(
40				f,
41				"{}",
42				indent_by(spaces as usize, func).color(self.cfg.colours.function)
43			)
44		} else {
45			Ok(())
46		}
47	}
48}