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
//! The main public API for compilation
use std::{
io::Write,
path::{Path, PathBuf},
};
use crate::{
parse::{FileSystemResolver, SourceResolver},
DiagnosticSet, GlyphMap,
};
use super::{error::CompilerError, Compilation, FeatureProvider, Opts, VariationInfo};
const DEFAULT_N_MESSAGES_TO_PRINT: usize = 100;
/// A builder-style entry point for the compiler.
///
/// This is intended as the principal public API for this crate.
///
/// ```no_run
/// # use fea_rs::{Compiler, compile::{NopFeatureProvider, NopVariationInfo}};
/// # fn make_glyph_map() -> fea_rs::GlyphMap { todo!() }
/// let glyph_map = make_glyph_map();
/// let my_font_bytes = Compiler::<'_, NopFeatureProvider, NopVariationInfo>::new("path/to/features.fea", &glyph_map)
/// .verbose(true)
/// .compile_binary().unwrap();
/// ```
pub struct Compiler<'a, F: FeatureProvider, V: VariationInfo> {
root_path: PathBuf,
project_root: Option<PathBuf>,
glyph_map: &'a GlyphMap,
// variable fonts only
var_info: Option<&'a V>,
feature_writer: Option<&'a F>,
// this is not in `Opts` because it is specific to the compiler struct;
// if you're compiling manually you are responsible for handling warnings.
print_warnings: bool,
max_n_errors: usize,
opts: Opts,
resolver: Option<Box<dyn SourceResolver>>,
}
impl<'a, F: FeatureProvider, V: VariationInfo> Compiler<'a, F, V> {
/// Configure a new compilation run with a root source and a glyph map.
///
/// In the general case, `root_path` will be a path to a feature file on disk;
/// however you may compile from memory by passing a custom [`SourceResolver`]
/// to the [`with_resolver`] method, in which case `root_path` can be any
/// identifier that your resolver will resolve.
///
/// [`with_resolver`]: Self::with_resolver
pub fn new(root_path: impl Into<PathBuf>, glyph_map: &'a GlyphMap) -> Self {
Compiler {
root_path: root_path.into(),
glyph_map,
var_info: None,
feature_writer: None,
opts: Default::default(),
print_warnings: false,
resolver: Default::default(),
project_root: Default::default(),
max_n_errors: DEFAULT_N_MESSAGES_TO_PRINT,
}
}
/// Provide a custom `SourceResolver`, for mapping paths to their contents.
pub fn with_resolver(mut self, resolver: impl SourceResolver + 'static) -> Self {
self.resolver = Some(Box::new(resolver));
self
}
/// Provide [`VariationInfo`], necessary when compiling features for a variable font.
pub fn with_variable_info(mut self, var_info: &'a V) -> Self {
self.var_info = Some(var_info);
self
}
/// Provide [`FeatureProvider`] to provide additional features during compilation
pub fn with_feature_writer(mut self, feature_writer: &'a F) -> Self {
self.feature_writer = Some(feature_writer);
self
}
/// Specify verbosity.
///
/// When verbose is true, we will print all warnings.
#[deprecated(since = "0.14.1", note = "use print_warnings method instead")]
pub fn verbose(self, verbose: bool) -> Self {
self.print_warnings(verbose)
}
/// Indicate whether or not warnings should be printed (default is `false`)
pub fn print_warnings(mut self, warnings: bool) -> Self {
self.print_warnings = warnings;
self
}
/// Specify an explicit project root.
///
/// This is useful in cases where import resolution is based on an explicit
/// base directory, such as when dealing with certain source formats.
pub fn with_project_root(mut self, project_root: impl Into<PathBuf>) -> Self {
self.project_root = Some(project_root.into());
self
}
/// Specify additional compiler options.
pub fn with_opts(mut self, opts: Opts) -> Self {
self.opts = opts;
self
}
/// Parse, validate and compile this source.
///
/// This returns a `Compilation` object that contains all of the features
/// and lookups generated during compilation. If you would like to go directly
/// to a binary font, you can use [`compile_binary`] instead.
///
/// [`compile_binary`]: Self::compile_binary
pub fn compile(self) -> Result<Compilation, CompilerError> {
let resolver = self.resolver.unwrap_or_else(|| {
let project_root = self.project_root.unwrap_or_else(|| {
Path::new(&self.root_path)
.parent()
.map(PathBuf::from)
.unwrap_or_default()
});
Box::new(FileSystemResolver::new(project_root))
});
let (tree, diagnostics) =
crate::parse::ParseContext::parse(self.root_path, Some(self.glyph_map), resolver)?
.generate_parse_tree();
print_warnings_return_errors(diagnostics, self.print_warnings, self.max_n_errors)
.map_err(CompilerError::ParseFail)?;
let diagnostics = super::validate(&tree, self.glyph_map, self.var_info);
print_warnings_return_errors(diagnostics, self.print_warnings, self.max_n_errors)
.map_err(CompilerError::ValidationFail)?;
let mut ctx = super::CompilationCtx::new(
self.glyph_map,
tree.source_map(),
self.var_info,
self.feature_writer,
self.opts,
);
ctx.compile(&tree.typed_root());
// we 'take' the errors here because it's easier for us to handle the
// warnings using our helper method.
let messages = std::mem::take(&mut ctx.errors);
let diagnostics = DiagnosticSet::new(messages, &tree, self.max_n_errors);
print_warnings_return_errors(diagnostics, self.print_warnings, self.max_n_errors)
.map_err(CompilerError::CompilationFail)?;
Ok(ctx.build().unwrap().0) // we've taken the errors, so this can't fail
}
/// Compile to a binary font.
pub fn compile_binary(self) -> Result<Vec<u8>, CompilerError> {
let glyph_map = self.glyph_map;
Ok(self.compile()?.to_binary(glyph_map)?)
}
}
fn print_warnings_return_errors(
mut diagnostics: DiagnosticSet,
print_warnings: bool,
max_to_print: usize,
) -> Result<(), DiagnosticSet> {
diagnostics.set_max_to_print(max_to_print);
let warnings = diagnostics.split_off_warnings();
if let Some(warnings) = warnings {
if print_warnings {
// get around a CI check denying eprintln
let _ = writeln!(std::io::stderr(), "{}", warnings.display());
}
}
if diagnostics.is_empty() {
Ok(())
} else {
Err(diagnostics)
}
}