You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by jr...@apache.org on 2020/11/06 02:11:38 UTC

[incubator-tvm] 14/21: Format and cleanup

This is an automated email from the ASF dual-hosted git repository.

jroesch pushed a commit to branch cargo-build
in repository https://gitbox.apache.org/repos/asf/incubator-tvm.git

commit 04a9779359380ae383405f5f72a66e79631ee2d5
Author: Jared Roesch <jr...@octoml.ai>
AuthorDate: Fri Oct 16 16:31:37 2020 -0700

    Format and cleanup
---
 python/tvm/ir/diagnostics/__init__.py   |  1 +
 rust/compiler-ext/src/lib.rs            |  3 +-
 rust/tvm-rt/src/array.rs                | 11 +++--
 rust/tvm-rt/src/errors.rs               |  4 +-
 rust/tvm-rt/src/function.rs             |  2 +-
 rust/tvm/src/bin/tyck.rs                |  8 +--
 rust/tvm/src/ir/diagnostics/codespan.rs | 87 +++++++++++++++++++--------------
 rust/tvm/src/ir/mod.rs                  |  2 +-
 rust/tvm/src/ir/module.rs               |  5 +-
 rust/tvm/src/ir/relay/mod.rs            |  2 +-
 rust/tvm/src/ir/relay/visitor.rs        | 24 ---------
 rust/tvm/src/ir/source_map.rs           | 13 ++---
 rust/tvm/src/ir/span.rs                 |  2 +-
 src/ir/expr.cc                          | 11 -----
 14 files changed, 79 insertions(+), 96 deletions(-)

diff --git a/python/tvm/ir/diagnostics/__init__.py b/python/tvm/ir/diagnostics/__init__.py
index 0ad2a7a..3a6402c 100644
--- a/python/tvm/ir/diagnostics/__init__.py
+++ b/python/tvm/ir/diagnostics/__init__.py
@@ -37,6 +37,7 @@ def get_renderer():
     """
     return _ffi_api.GetRenderer()
 
+
 @tvm.register_func("diagnostics.override_renderer")
 def override_renderer(render_func):
     """
diff --git a/rust/compiler-ext/src/lib.rs b/rust/compiler-ext/src/lib.rs
index c136d06..346f40f 100644
--- a/rust/compiler-ext/src/lib.rs
+++ b/rust/compiler-ext/src/lib.rs
@@ -36,8 +36,7 @@ tvm::export!(test_fn, test_fn2);
 #[no_mangle]
 fn compiler_ext_initialize() -> i32 {
     let _ = env_logger::try_init();
-    tvm_export("rust_ext")
-        .expect("failed to initialize Rust compiler_ext");
+    tvm_export("rust_ext").expect("failed to initialize Rust compiler_ext");
     log::debug!("done!");
     return 0;
 }
diff --git a/rust/tvm-rt/src/array.rs b/rust/tvm-rt/src/array.rs
index 032ca79..66e32a7 100644
--- a/rust/tvm-rt/src/array.rs
+++ b/rust/tvm-rt/src/array.rs
@@ -18,8 +18,8 @@
  */
 
 use std::convert::{TryFrom, TryInto};
-use std::marker::PhantomData;
 use std::iter::{IntoIterator, Iterator};
+use std::marker::PhantomData;
 
 use crate::errors::Error;
 use crate::object::{IsObjectRef, Object, ObjectPtr, ObjectRef};
@@ -93,8 +93,7 @@ impl<T: IsObjectRef> Iterator for IntoIter<T> {
 
     fn next(&mut self) -> Option<Self::Item> {
         if self.pos < self.size {
-            let item = self.array.get(self.pos)
-                .expect("should not fail");
+            let item = self.array.get(self.pos).expect("should not fail");
             self.pos += 1;
             Some(item)
         } else {
@@ -109,7 +108,11 @@ impl<T: IsObjectRef> IntoIterator for Array<T> {
 
     fn into_iter(self) -> Self::IntoIter {
         let size = self.len() as isize;
-        IntoIter { array: self, pos: 0, size: size }
+        IntoIter {
+            array: self,
+            pos: 0,
+            size: size,
+        }
     }
 }
 
diff --git a/rust/tvm-rt/src/errors.rs b/rust/tvm-rt/src/errors.rs
index 3de9f3c..31ce385 100644
--- a/rust/tvm-rt/src/errors.rs
+++ b/rust/tvm-rt/src/errors.rs
@@ -68,7 +68,9 @@ pub enum Error {
     Infallible(#[from] std::convert::Infallible),
     #[error("a panic occurred while executing a Rust packed function")]
     Panic,
-    #[error("one or more error diagnostics were emitted, please check diagnostic render for output.")]
+    #[error(
+        "one or more error diagnostics were emitted, please check diagnostic render for output."
+    )]
     DiagnosticError(String),
     #[error("{0}")]
     Raw(String),
diff --git a/rust/tvm-rt/src/function.rs b/rust/tvm-rt/src/function.rs
index 173b60a..4c6f56e 100644
--- a/rust/tvm-rt/src/function.rs
+++ b/rust/tvm-rt/src/function.rs
@@ -128,7 +128,7 @@ impl Function {
                 type_codes.as_mut_ptr() as *mut c_int,
                 num_args as c_int,
                 &mut ret_val as *mut _,
-                &mut ret_type_code as *mut _
+                &mut ret_type_code as *mut _,
             )
         };
 
diff --git a/rust/tvm/src/bin/tyck.rs b/rust/tvm/src/bin/tyck.rs
index 13470e7..e9c2663 100644
--- a/rust/tvm/src/bin/tyck.rs
+++ b/rust/tvm/src/bin/tyck.rs
@@ -20,9 +20,11 @@ fn main() -> Result<()> {
     let opt = Opt::from_args();
     println!("{:?}", &opt);
     let _module = match IRModule::parse_file(opt.input) {
-        Err(ir::module::Error::TVM(Error::DiagnosticError(_))) => { return Ok(()) },
-        Err(e) => { return Err(e.into()); },
-        Ok(module) => module
+        Err(ir::module::Error::TVM(Error::DiagnosticError(_))) => return Ok(()),
+        Err(e) => {
+            return Err(e.into());
+        }
+        Ok(module) => module,
     };
 
     Ok(())
diff --git a/rust/tvm/src/ir/diagnostics/codespan.rs b/rust/tvm/src/ir/diagnostics/codespan.rs
index 9fc1ee0..9a31691 100644
--- a/rust/tvm/src/ir/diagnostics/codespan.rs
+++ b/rust/tvm/src/ir/diagnostics/codespan.rs
@@ -1,3 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/// A TVM diagnostics renderer which uses the Rust `codespan`
+/// library to produce error messages.
 use std::collections::HashMap;
 use std::sync::{Arc, Mutex};
 
@@ -6,13 +27,8 @@ use codespan_reporting::files::SimpleFiles;
 use codespan_reporting::term::termcolor::{ColorChoice, StandardStream};
 use codespan_reporting::term::{self, ColorArg};
 
-use crate::ir::source_map::*;
 use super::*;
-
-enum StartOrEnd {
-    Start,
-    End,
-}
+use crate::ir::source_map::*;
 
 struct ByteRange<FileId> {
     file_id: FileId,
@@ -26,7 +42,7 @@ enum FileSpanToByteRange {
         /// Map character regions which are larger then 1-byte to length.
         lengths: HashMap<isize, isize>,
         source: String,
-    }
+    },
 }
 
 impl FileSpanToByteRange {
@@ -34,24 +50,11 @@ impl FileSpanToByteRange {
         let mut last_index = 0;
         let mut is_ascii = true;
         if source.is_ascii() {
-            let line_lengths =
-                source
-                    .lines()
-                    .map(|line| line.len())
-                    .collect();
+            let line_lengths = source.lines().map(|line| line.len()).collect();
             FileSpanToByteRange::AsciiSource(line_lengths)
         } else {
             panic!()
         }
-
-        // for (index, _) in source.char_indices() {
-        //     if last_index - 1 != last_index {
-        //         is_ascii = false;
-        //     } else {
-        //         panic!();
-        //     }
-        //     last_index = index;
-        // }
     }
 
     fn lookup(&self, span: &Span) -> ByteRange<String> {
@@ -61,22 +64,34 @@ impl FileSpanToByteRange {
 
         match self {
             AsciiSource(ref line_lengths) => {
-                let start_pos = (&line_lengths[0..(span.line - 1) as usize]).into_iter().sum::<usize>() + (span.column) as usize;
-                let end_pos = (&line_lengths[0..(span.end_line - 1) as usize]).into_iter().sum::<usize>() + (span.end_column) as usize;
-                ByteRange { file_id: source_name, start_pos, end_pos }
-            },
-            _ => panic!()
+                let start_pos = (&line_lengths[0..(span.line - 1) as usize])
+                    .into_iter()
+                    .sum::<usize>()
+                    + (span.column) as usize;
+                let end_pos = (&line_lengths[0..(span.end_line - 1) as usize])
+                    .into_iter()
+                    .sum::<usize>()
+                    + (span.end_column) as usize;
+                ByteRange {
+                    file_id: source_name,
+                    start_pos,
+                    end_pos,
+                }
+            }
+            _ => panic!(),
         }
     }
 }
 
 struct SpanToByteRange {
-    map: HashMap<String, FileSpanToByteRange>
+    map: HashMap<String, FileSpanToByteRange>,
 }
 
 impl SpanToByteRange {
     fn new() -> SpanToByteRange {
-        SpanToByteRange { map: HashMap::new() }
+        SpanToByteRange {
+            map: HashMap::new(),
+        }
     }
 
     pub fn add_source(&mut self, source: Source) {
@@ -86,7 +101,8 @@ impl SpanToByteRange {
             panic!()
         } else {
             let source = source.source.as_str().expect("fpp").into();
-            self.map.insert(source_name, FileSpanToByteRange::new(source));
+            self.map
+                .insert(source_name, FileSpanToByteRange::new(source));
         }
     }
 
@@ -143,9 +159,10 @@ impl DiagnosticState {
         let diagnostic = CDiagnostic::new(severity)
             .with_message(message)
             .with_code("EXXX")
-            .with_labels(vec![
-                Label::primary(file_id, byte_range.start_pos..byte_range.end_pos)
-            ]);
+            .with_labels(vec![Label::primary(
+                file_id,
+                byte_range.start_pos..byte_range.end_pos,
+            )]);
 
         diagnostic
     }
@@ -161,11 +178,7 @@ fn renderer(state: &mut DiagnosticState, diag_ctx: DiagnosticContext) {
             Ok(source) => {
                 state.add_source(source);
                 let diagnostic = state.to_diagnostic(diagnostic);
-                term::emit(
-                    &mut writer.lock(),
-                    &config,
-                    &state.files,
-                    &diagnostic).unwrap();
+                term::emit(&mut writer.lock(), &config, &state.files, &diagnostic).unwrap();
             }
         }
     }
diff --git a/rust/tvm/src/ir/mod.rs b/rust/tvm/src/ir/mod.rs
index df9bc68..6d51580 100644
--- a/rust/tvm/src/ir/mod.rs
+++ b/rust/tvm/src/ir/mod.rs
@@ -25,8 +25,8 @@ pub mod function;
 pub mod module;
 pub mod op;
 pub mod relay;
-pub mod span;
 pub mod source_map;
+pub mod span;
 pub mod tir;
 pub mod ty;
 
diff --git a/rust/tvm/src/ir/module.rs b/rust/tvm/src/ir/module.rs
index 11d6c49..443915f 100644
--- a/rust/tvm/src/ir/module.rs
+++ b/rust/tvm/src/ir/module.rs
@@ -32,7 +32,6 @@ use super::expr::GlobalVar;
 use super::function::BaseFunc;
 use super::source_map::SourceMap;
 
-
 // TODO(@jroesch): define type
 type TypeData = ObjectRef;
 type GlobalTypeVar = ObjectRef;
@@ -133,7 +132,9 @@ impl IRModule {
         parse_module(file_name.into(), source.into())
     }
 
-    pub fn parse_file<P: 'static + AsRef<Path>>(file_path: P) -> std::result::Result<IRModule, Error> {
+    pub fn parse_file<P: 'static + AsRef<Path>>(
+        file_path: P,
+    ) -> std::result::Result<IRModule, Error> {
         let file_path = file_path.as_ref();
         let file_path_as_str = file_path.to_str().unwrap().to_string();
         let source = std::fs::read_to_string(file_path)?;
diff --git a/rust/tvm/src/ir/relay/mod.rs b/rust/tvm/src/ir/relay/mod.rs
index 4b09128..530b120 100644
--- a/rust/tvm/src/ir/relay/mod.rs
+++ b/rust/tvm/src/ir/relay/mod.rs
@@ -27,8 +27,8 @@ use crate::runtime::{object::*, String as TString};
 use super::attrs::Attrs;
 use super::expr::BaseExprNode;
 use super::function::BaseFuncNode;
-use super::ty::{Type, TypeNode};
 use super::span::Span;
+use super::ty::{Type, TypeNode};
 
 use tvm_macros::Object;
 use tvm_rt::NDArray;
diff --git a/rust/tvm/src/ir/relay/visitor.rs b/rust/tvm/src/ir/relay/visitor.rs
deleted file mode 100644
index 3166174..0000000
--- a/rust/tvm/src/ir/relay/visitor.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use super::Expr;
-
-macro_rules! downcast_match {
-    ($id:ident; { $($t:ty => $arm:expr $(,)? )+ , else => $default:expr }) => {
-        $( if let Ok($id) = $id.downcast_clone::<$t>() { $arm } else )+
-        { $default }
-    }
-}
-
-trait ExprVisitorMut {
-    fn visit(&mut self, expr: Expr) {
-        downcast_match!(expr; {
-            else => {
-                panic!()
-            }
-        });
-    }
-
-    fn visit(&mut self, expr: Expr);
-}
-
-// trait ExprTransformer {
-//     fn
-// }
diff --git a/rust/tvm/src/ir/source_map.rs b/rust/tvm/src/ir/source_map.rs
index ebe7e46..b0cc0d8 100644
--- a/rust/tvm/src/ir/source_map.rs
+++ b/rust/tvm/src/ir/source_map.rs
@@ -19,7 +19,7 @@
 
 use crate::runtime::map::Map;
 use crate::runtime::object::Object;
-use crate::runtime::string::{String as TString};
+use crate::runtime::string::String as TString;
 
 use super::span::{SourceName, Span};
 
@@ -39,12 +39,10 @@ pub struct SourceNode {
 
     /// The raw source. */
     pub source: TString,
-
-   // A mapping of line breaks into the raw source.
-   // std::vector<std::pair<int, int>> line_map;
+    // A mapping of line breaks into the raw source.
+    // std::vector<std::pair<int, int>> line_map;
 }
 
-
 //  class Source : public ObjectRef {
 //   public:
 //    TVM_DLL Source(SourceName src_name, std::string source);
@@ -53,7 +51,6 @@ pub struct SourceNode {
 //    TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Source, ObjectRef, SourceNode);
 //  };
 
-
 /// A mapping from a unique source name to source fragments.
 #[repr(C)]
 #[derive(Object)]
@@ -61,6 +58,6 @@ pub struct SourceNode {
 #[ref_name = "SourceMap"]
 pub struct SourceMapNode {
     pub base: Object,
-   /// The source mapping.
-   pub source_map: Map<SourceName, Source>,
+    /// The source mapping.
+    pub source_map: Map<SourceName, Source>,
 }
diff --git a/rust/tvm/src/ir/span.rs b/rust/tvm/src/ir/span.rs
index c54fd51..afcbe9c 100644
--- a/rust/tvm/src/ir/span.rs
+++ b/rust/tvm/src/ir/span.rs
@@ -18,7 +18,7 @@
 * under the License.
 */
 
-use crate::runtime::{ObjectRef, Object, String as TString};
+use crate::runtime::{Object, ObjectRef, String as TString};
 use tvm_macros::Object;
 
 /// A source file name, contained in a Span.
diff --git a/src/ir/expr.cc b/src/ir/expr.cc
index 5110eef..67e5cea 100644
--- a/src/ir/expr.cc
+++ b/src/ir/expr.cc
@@ -192,15 +192,4 @@ TVM_REGISTER_GLOBAL("ir.DebugPrint").set_body_typed([](ObjectRef ref) {
   return ss.str();
 });
 
-
-
 }  // namespace tvm
-
-#ifdef RUST_COMPILER_EXT
-
-extern "C" {
-  int compiler_ext_initialize();
-  static int test = compiler_ext_initialize();
-}
-
-#endif