From 5de0ba055cef7f2dc5451b1eaf0857deb77ae009 Mon Sep 17 00:00:00 2001 From: Akshay Date: Sun, 24 Oct 2021 13:24:52 +0530 Subject: add support for json out --- lib/Cargo.toml | 10 ++++++++++ lib/src/lib.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) (limited to 'lib') diff --git a/lib/Cargo.toml b/lib/Cargo.toml index e9e9e69..e9bca06 100644 --- a/lib/Cargo.toml +++ b/lib/Cargo.toml @@ -11,3 +11,13 @@ if_chain = "1.0" macros = { path = "../macros" } lazy_static = "1.0" rowan = "0.12.5" +serde_json = { version = "1.0.68", optional = true } + +[dependencies.serde] +version = "1.0.130" +features = [ "derive" ] +optional = true + +[features] +default = [] +json-out = [ "serde", "serde_json" ] diff --git a/lib/src/lib.rs b/lib/src/lib.rs index d8a3859..bde039f 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -6,8 +6,12 @@ pub use lints::LINTS; use rnix::{SyntaxElement, SyntaxKind, TextRange}; use std::{convert::Into, default::Default}; +#[cfg(feature = "json-out")] +use serde::{Serialize, ser::{SerializeStruct, Serializer}}; + /// Report generated by a lint #[derive(Debug, Default)] +#[cfg_attr(feature = "json-out", derive(Serialize))] pub struct Report { /// General information about this lint and where it applies. pub note: &'static str, @@ -95,6 +99,27 @@ impl Diagnostic { } } +#[cfg(feature = "json-out")] +impl Serialize for Diagnostic { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Diagnostic", 3)?; + let at = { + let start = usize::from(self.at.start()); + let end = usize::from(self.at.end()); + (start, end) + }; + s.serialize_field("at", &at)?; + s.serialize_field("message", &self.message)?; + if let Some(suggestion) = &self.suggestion { + s.serialize_field("suggestion", suggestion)?; + } + s.end() + } +} + /// Suggested fix for a diagnostic, the fix is provided as a syntax element. /// Look at `make.rs` to construct fixes. #[derive(Debug)] @@ -119,6 +144,25 @@ impl Suggestion { } } +#[cfg(feature = "json-out")] +impl Serialize for Suggestion { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Suggestion", 2)?; + let at = { + let start = usize::from(self.at.start()); + let end = usize::from(self.at.end()); + (start, end) + }; + let fix = self.fix.to_string(); + s.serialize_field("at", &at)?; + s.serialize_field("fix", &fix)?; + s.end() + } +} + /// Lint logic is defined via this trait. Do not implement manually, /// look at the `lint` attribute macro instead for implementing rules pub trait Rule { -- cgit v1.2.3