From 36823d7804df68bf48c6d000c602e7f473437d3c Mon Sep 17 00:00:00 2001 From: Nick Rolfe Date: Thu, 22 Oct 2020 11:10:05 +0100 Subject: [PATCH] Move deserialization to node_types module; propagate errors to caller --- generator/src/main.rs | 28 +++++++++++----------------- generator/src/node_types.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 17 deletions(-) diff --git a/generator/src/main.rs b/generator/src/main.rs index c4a39f50192..121865b7be8 100644 --- a/generator/src/main.rs +++ b/generator/src/main.rs @@ -8,19 +8,6 @@ use std::fs::File; use std::io::LineWriter; use std::path::PathBuf; -fn read_node_types(language: &Language) -> Option> { - let json_data = match std::fs::read_to_string(&language.node_types_path) { - Ok(s) => s, - Err(_) => return None, - }; - let nodes: Vec = match serde_json::from_str(&json_data) { - Ok(n) => n, - Err(_) => return None, - }; - - Some(nodes) -} - /// Given a tree-sitter node type's (kind, named) pair, returns a single string /// representing the (unescaped) name we'll use to refer to corresponding QL /// type. @@ -301,12 +288,19 @@ fn main() { node_types_path: PathBuf::from("tree-sitter-ruby/src/node-types.json"), dbscheme_path: PathBuf::from("ruby.dbscheme"), }; - match read_node_types(&ruby) { - None => { - println!("Failed to read node types"); + match node_types::read(&ruby.node_types_path) { + Err(e) => { + println!( + "Failed to read '{}': {}", + match ruby.node_types_path.to_str() { + None => "", + Some(p) => p, + }, + e + ); std::process::exit(1); } - Some(nodes) => { + Ok(nodes) => { let mut dbscheme_entries = convert_nodes(&nodes); dbscheme_entries.push(create_location_entry()); dbscheme_entries.push(create_source_location_prefix_entry()); diff --git a/generator/src/node_types.rs b/generator/src/node_types.rs index faee47e410e..f8c06f29c67 100644 --- a/generator/src/node_types.rs +++ b/generator/src/node_types.rs @@ -1,5 +1,7 @@ use serde::Deserialize; use std::collections::BTreeMap; +use std::fmt; +use std::path::Path; #[derive(Deserialize)] pub struct NodeInfo { @@ -37,3 +39,36 @@ impl Default for FieldInfo { } } } + +pub enum Error { + IOError(std::io::Error), + JsonError(serde_json::error::Error), +} + +impl From for Error { + fn from(error: std::io::Error) -> Self { + Error::IOError(error) + } +} + +impl From for Error { + fn from(error: serde_json::Error) -> Self { + Error::JsonError(error) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::IOError(e) => write!(f, "{}", e), + Error::JsonError(e) => write!(f, "{}", e), + } + } +} + +/// Deserializes the node types from the JSON at the given `path`. +pub fn read(path: &Path) -> Result, Error> { + let json_data = std::fs::read_to_string(path)?; + let node_types: Vec = serde_json::from_str(&json_data)?; + Ok(node_types) +}