1use cm_fidl_validator::error::ErrorList;
6use cm_types::ParseError;
7use fidl_fuchsia_component_decl as fdecl;
8use std::path::{Path, PathBuf};
9use std::str::Utf8Error;
10use std::sync::Arc;
11use std::{error, fmt, io};
12
13#[derive(PartialEq, Clone, Debug, Eq, Hash, PartialOrd, Ord, Default)]
15pub struct Location {
16 pub line: usize,
18
19 pub column: usize,
21}
22
23#[derive(Debug)]
25pub enum Error {
26 DuplicateRights(String),
27 InvalidArgs(String),
28 Io(io::Error),
29 FidlEncoding(fidl::Error),
30 Merge {
31 err: String,
32 origin: Option<Arc<PathBuf>>,
33 },
34 MissingRights(String),
35 Parse {
36 err: String,
37 location: Option<Location>,
38 filename: Option<String>,
39 },
40 Validate {
41 err: String,
42 filename: Option<String>,
43 },
44 ValidateContext {
45 err: String,
46 origin: Option<Arc<PathBuf>>,
47 },
48 ValidateContexts {
49 err: String,
50 origins: Vec<Arc<PathBuf>>,
51 },
52 FidlValidator {
53 errs: ErrorList,
54 },
55 Internal(String),
56 Utf8(Utf8Error),
57 RestrictedFeature(String),
59}
60
61impl error::Error for Error {}
62
63impl Error {
64 pub fn invalid_args(err: impl Into<String>) -> Self {
65 Self::InvalidArgs(err.into())
66 }
67
68 pub fn parse(
69 err: impl fmt::Display,
70 location: Option<Location>,
71 filename: Option<&Path>,
72 ) -> Self {
73 Self::Parse {
74 err: err.to_string(),
75 location,
76 filename: filename.map(|f| f.to_string_lossy().into_owned()),
77 }
78 }
79
80 pub fn merge(err: impl fmt::Display, origin: Option<Arc<PathBuf>>) -> Self {
81 Self::Merge { err: err.to_string(), origin }
82 }
83
84 pub fn validate(err: impl fmt::Display) -> Self {
85 Self::Validate { err: err.to_string(), filename: None }
86 }
87
88 pub fn validate_context(err: impl fmt::Display, origin: Option<Arc<PathBuf>>) -> Self {
89 Self::ValidateContext { err: err.to_string(), origin }
90 }
91 pub fn validate_contexts(err: impl fmt::Display, origins: Vec<Arc<PathBuf>>) -> Self {
92 Self::ValidateContexts { err: err.to_string(), origins }
93 }
94
95 pub fn fidl_validator(errs: ErrorList) -> Self {
96 Self::FidlValidator { errs }
97 }
98
99 pub fn duplicate_rights(err: impl Into<String>) -> Self {
100 Self::DuplicateRights(err.into())
101 }
102
103 pub fn missing_rights(err: impl Into<String>) -> Self {
104 Self::MissingRights(err.into())
105 }
106
107 pub fn internal(err: impl Into<String>) -> Self {
108 Self::Internal(err.into())
109 }
110
111 pub fn json5(err: json5format::Error, file: Option<&Path>) -> Self {
112 match err {
113 json5format::Error::Configuration(errstr) => Error::Internal(errstr),
114 json5format::Error::Parse(location, errstr) => match location {
115 Some(location) => Error::parse(
116 errstr,
117 Some(Location { line: location.line, column: location.col }),
118 file,
119 ),
120 None => Error::parse(errstr, None, file),
121 },
122 json5format::Error::Internal(location, errstr) => match location {
123 Some(location) => Error::Internal(format!("{}: {}", location, errstr)),
124 None => Error::Internal(errstr),
125 },
126 json5format::Error::TestFailure(location, errstr) => match location {
127 Some(location) => {
128 Error::Internal(format!("{}: Test failure: {}", location, errstr))
129 }
130 None => Error::Internal(format!("Test failure: {}", errstr)),
131 },
132 }
133 }
134
135 pub fn with_origin(self, origin: Arc<PathBuf>) -> Self {
136 match self {
137 Error::ValidateContext { err, .. } => {
138 Error::ValidateContext { err, origin: Some(origin) }
139 }
140 _ => Error::ValidateContext { err: self.to_string(), origin: Some(origin) },
141 }
142 }
143}
144
145impl fmt::Display for Error {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 match &self {
148 Error::DuplicateRights(err) => write!(f, "Duplicate rights: {}", err),
149 Error::InvalidArgs(err) => write!(f, "Invalid args: {}", err),
150 Error::Io(err) => write!(f, "IO error: {}", err),
151 Error::FidlEncoding(err) => write!(f, "Fidl encoding error: {}", err),
152 Error::Merge { err, origin } => {
153 let mut prefix = String::new();
154
155 if let Some(origin) = origin {
156 prefix.push_str(&format!("{:?}:", origin));
157 }
158
159 if !prefix.is_empty() {
160 write!(f, "Error merging at {} {}", prefix, err)
161 } else {
162 write!(f, "{}", err)
163 }
164 }
165 Error::MissingRights(err) => write!(f, "Missing rights: {}", err),
166 Error::Parse { err, location, filename } => {
167 let mut prefix = String::new();
168 if let Some(filename) = filename {
169 prefix.push_str(&format!("{}:", filename));
170 }
171 if let Some(location) = location {
172 if !err.starts_with(" -->") {
179 prefix.push_str(&format!("{}:{}:", location.line, location.column));
180 }
181 }
182 if !prefix.is_empty() {
183 write!(f, "Error at {} {}", prefix, err)
184 } else {
185 write!(f, "{}", err)
186 }
187 }
188 Error::Validate { err, filename } => {
189 let mut prefix = String::new();
190 if let Some(filename) = filename {
191 prefix.push_str(&format!("{}:", filename));
192 }
193 if !prefix.is_empty() {
194 write!(f, "Error at {} {}", prefix, err)
195 } else {
196 write!(f, "{}", err)
197 }
198 }
199 Error::ValidateContext { err, origin } => {
200 let mut prefix = String::new();
201
202 if let Some(origin) = origin {
203 prefix.push_str(&format!("{:?}:", origin));
204 }
205
206 if !prefix.is_empty() {
207 write!(f, "Error at {} {}", prefix, err)
208 } else {
209 write!(f, "{}", err)
210 }
211 }
212 Error::ValidateContexts { err, origins } => {
213 let mut prefix = String::new();
214
215 for origin in origins {
216 if !prefix.is_empty() {
217 prefix.push_str(", and ");
218 }
219
220 prefix.push_str(&format!("{:?}:", origin));
221 }
222
223 if !prefix.is_empty() {
224 write!(f, "Error at {} {}", prefix, err)
225 } else {
226 write!(f, "{}", err)
227 }
228 }
229 Error::FidlValidator { errs } => format_multiple_fidl_validator_errors(errs, f),
230 Error::Internal(err) => write!(f, "Internal error: {}", err),
231 Error::Utf8(err) => write!(f, "UTF8 error: {}", err),
232 Error::RestrictedFeature(feature) => write!(
233 f,
234 "Use of restricted feature \"{}\". To opt-in, see https://fuchsia.dev/go/components/restricted-features",
235 feature
236 ),
237 }
238 }
239}
240
241fn format_multiple_fidl_validator_errors(e: &ErrorList, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 use cm_fidl_validator::error::Error as CmFidlError;
255 let mut found_internal_errors = false;
256 for e in e.errs.iter() {
257 match e {
258 CmFidlError::DifferentAvailabilityInAggregation(availability_list) => {
259 let comma_separated = availability_list
261 .0
262 .iter()
263 .map(|s| match s {
264 fdecl::Availability::Required => "\"required\"".to_string(),
265 fdecl::Availability::Optional => "\"optional\"".to_string(),
266 fdecl::Availability::SameAsTarget => "\"same_as_target\"".to_string(),
267 fdecl::Availability::Transitional => "\"transitional\"".to_string(),
268 })
269 .collect::<Vec<_>>()
270 .join(", ");
271
272 write!(
273 f,
274 "All sources that feed into an aggregation operation should have the same availability. "
275 )?;
276 write!(f, "Got [ {comma_separated} ].")?;
277 }
278 _ => {
279 write!(f, "Internal error: {}\n", e)?;
280 found_internal_errors = true;
281 }
282 }
283 }
284
285 if found_internal_errors {
286 write!(
287 f,
288 "This reflects error(s) in the `.cml` file. \
289Unfortunately, for some of them, cmc cannot provide more details at this time.
290Please file a bug at https://bugs.fuchsia.dev/p/fuchsia/issues/entry?template=ComponentFramework \
291with the cml in question, so we can work on better error reporting."
292 )?;
293 }
294
295 Ok(())
296}
297
298impl From<io::Error> for Error {
299 fn from(err: io::Error) -> Self {
300 Error::Io(err)
301 }
302}
303
304impl From<Utf8Error> for Error {
305 fn from(err: Utf8Error) -> Self {
306 Error::Utf8(err)
307 }
308}
309
310impl From<serde_json::error::Error> for Error {
311 fn from(err: serde_json::error::Error) -> Self {
312 use serde_json::error::Category;
313 match err.classify() {
314 Category::Io | Category::Eof => Error::Io(err.into()),
315 Category::Syntax => {
316 let line = err.line();
317 let column = err.column();
318 Error::parse(err, Some(Location { line, column }), None)
319 }
320 Category::Data => Error::validate(err),
321 }
322 }
323}
324
325impl From<fidl::Error> for Error {
326 fn from(err: fidl::Error) -> Self {
327 Error::FidlEncoding(err)
328 }
329}
330
331impl From<ParseError> for Error {
332 fn from(err: ParseError) -> Self {
333 match err {
334 ParseError::InvalidValue => Self::internal("invalid value"),
335 ParseError::InvalidComponentUrl { details } => {
336 Self::internal(&format!("invalid component url: {details}"))
337 }
338 ParseError::TooLong => Self::internal("too long"),
339 ParseError::Empty => Self::internal("empty"),
340 ParseError::InvalidSegment => Self::internal("invalid path segment"),
341 ParseError::NoLeadingSlash => Self::internal("missing leading slash"),
342 }
343 }
344}
345
346impl TryFrom<serde_json5::Error> for Location {
347 type Error = &'static str;
348 fn try_from(e: serde_json5::Error) -> Result<Self, Self::Error> {
349 match e {
350 serde_json5::Error::Message { location: Some(l), .. } => {
351 Ok(Location { line: l.line, column: l.column })
352 }
353 _ => Err("location unavailable"),
354 }
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 use anyhow::format_err;
362 use assert_matches::assert_matches;
363 use cm_types as cm;
364
365 #[test]
366 fn test_syntax_error_message() {
367 let result = serde_json::from_str::<cm::Name>("foo").map_err(Error::from);
368 assert_matches!(result, Err(Error::Parse { .. }));
369 }
370
371 #[test]
372 fn test_validation_error_message() {
373 let result = serde_json::from_str::<cm::Name>("\"foo$\"").map_err(Error::from);
374 assert_matches!(result, Err(Error::Validate { .. }));
375 }
376
377 #[test]
378 fn test_parse_error() {
379 let result = Error::parse(format_err!("oops"), None, None);
380 assert_eq!(format!("{}", result), "oops");
381
382 let result = Error::parse(format_err!("oops"), Some(Location { line: 2, column: 3 }), None);
383 assert_eq!(format!("{}", result), "Error at 2:3: oops");
384
385 let result = Error::parse(
386 format_err!("oops"),
387 Some(Location { line: 2, column: 3 }),
388 Some(&Path::new("test.cml")),
389 );
390 assert_eq!(format!("{}", result), "Error at test.cml:2:3: oops");
391
392 let result = Error::parse(
393 format_err!(" --> pest error"),
394 Some(Location { line: 42, column: 42 }),
395 Some(&Path::new("test.cml")),
396 );
397 assert_eq!(format!("{}", result), "Error at test.cml: --> pest error");
398 }
399
400 #[test]
401 fn test_validation_error() {
402 let mut result = Error::validate(format_err!("oops"));
403 assert_eq!(format!("{}", result), "oops");
404
405 if let Error::Validate { filename, .. } = &mut result {
406 *filename = Some("test.cml".to_string());
407 }
408 assert_eq!(format!("{}", result), "Error at test.cml: oops");
409 }
410
411 #[test]
412 fn test_format_multiple_fidl_validator_errors() {
413 use cm_fidl_validator::error::{AvailabilityList, Error as CmFidlError};
414
415 let error = Error::FidlValidator {
416 errs: ErrorList {
417 errs: vec![CmFidlError::DifferentAvailabilityInAggregation(AvailabilityList(
418 vec![fdecl::Availability::Required, fdecl::Availability::Optional],
419 ))],
420 },
421 };
422 assert_eq!(
423 format!("{error}"),
424 "All sources that feed into an aggregation operation should \
425 have the same availability. Got [ \"required\", \"optional\" ]."
426 );
427 }
428}