From 7b15c4f7ae95e2e855cb783871906fa7bf364c4c Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Thu, 17 Oct 2019 19:36:55 +0300 Subject: WIP: move to xtasks --- .cargo/config | 23 +-- Cargo.lock | 26 +-- Cargo.toml | 2 +- README.md | 4 +- crates/ra_tools/Cargo.toml | 15 -- crates/ra_tools/src/bin/pre-commit.rs | 31 --- crates/ra_tools/src/boilerplate_gen.rs | 348 --------------------------------- crates/ra_tools/src/help.rs | 47 ----- crates/ra_tools/src/lib.rs | 332 ------------------------------- crates/ra_tools/src/main.rs | 218 --------------------- crates/ra_tools/tests/cli.rs | 45 ----- crates/ra_tools/tests/docs.rs | 63 ------ crates/ra_tools/tests/main.rs | 2 - docs/dev/architecture.md | 14 +- docs/user/README.md | 6 +- xtask/Cargo.toml | 15 ++ xtask/src/bin/pre-commit.rs | 31 +++ xtask/src/boilerplate_gen.rs | 348 +++++++++++++++++++++++++++++++++ xtask/src/help.rs | 47 +++++ xtask/src/lib.rs | 332 +++++++++++++++++++++++++++++++ xtask/src/main.rs | 218 +++++++++++++++++++++ xtask/tests/cli.rs | 45 +++++ xtask/tests/docs.rs | 63 ++++++ xtask/tests/main.rs | 2 + 24 files changed, 1126 insertions(+), 1151 deletions(-) delete mode 100644 crates/ra_tools/Cargo.toml delete mode 100644 crates/ra_tools/src/bin/pre-commit.rs delete mode 100644 crates/ra_tools/src/boilerplate_gen.rs delete mode 100644 crates/ra_tools/src/help.rs delete mode 100644 crates/ra_tools/src/lib.rs delete mode 100644 crates/ra_tools/src/main.rs delete mode 100644 crates/ra_tools/tests/cli.rs delete mode 100644 crates/ra_tools/tests/docs.rs delete mode 100644 crates/ra_tools/tests/main.rs create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/bin/pre-commit.rs create mode 100644 xtask/src/boilerplate_gen.rs create mode 100644 xtask/src/help.rs create mode 100644 xtask/src/lib.rs create mode 100644 xtask/src/main.rs create mode 100644 xtask/tests/cli.rs create mode 100644 xtask/tests/docs.rs create mode 100644 xtask/tests/main.rs diff --git a/.cargo/config b/.cargo/config index 92a3acfd0..67d0d1885 100644 --- a/.cargo/config +++ b/.cargo/config @@ -1,23 +1,4 @@ [alias] -# Automatically generates the ast and syntax kinds files -gen-syntax = "run --package ra_tools --bin ra_tools -- gen-syntax" +xtask = "run --package xtask --bin xtask --" -# Extracts the tests from -gen-tests = "run --package ra_tools --bin ra_tools -- gen-tests" - -# Installs the visual studio code extension -install-ra = "run --package ra_tools --bin ra_tools -- install-ra" -install-code = "run --package ra_tools --bin ra_tools -- install-ra" # just an alias - -# Formats the full repository or installs the git hook to do it automatically. -format = "run --package ra_tools --bin ra_tools -- format" -format-hook = "run --package ra_tools --bin ra_tools -- format-hook" - -# Run clippy -lint = "run --package ra_tools --bin ra_tools -- lint" - -# Runs the fuzzing test suite (currently only parser) -fuzz-tests = "run --package ra_tools --bin ra_tools -- fuzz-tests" - -# Parse a file. This should be piped the file contents -parse = "run --package ra_cli -- parse" +install-ra = "run --package xtask -- install" # for backwards compat diff --git a/Cargo.lock b/Cargo.lock index 9a048e67e..d2fe8e216 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1139,19 +1139,6 @@ dependencies = [ "text_unit 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "ra_tools" -version = "0.1.0" -dependencies = [ - "itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", - "pico-args 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "ron 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)", - "walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "ra_tt" version = "0.1.0" @@ -1784,6 +1771,19 @@ dependencies = [ "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "pico-args 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "ron 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)", + "walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "yaml-rust" version = "0.4.3" diff --git a/Cargo.toml b/Cargo.toml index 6ec176cf7..e8f6c4267 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = [ "crates/*" ] +members = [ "crates/*", "xtask/", "website/website-gen" ] [profile.dev] debug = 1 # only line info diff --git a/README.md b/README.md index 55d91a70a..f5ee4263d 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,10 @@ To quickly install rust-analyzer with VS Code extension with standard setup $ git clone https://github.com/rust-analyzer/rust-analyzer && cd rust-analyzer # install both the language server and VS Code extension -$ cargo install-ra +$ cargo xtask install # alternatively, install only the server. Binary name is `ra_lsp_server`. -$ cargo install-ra --server +$ cargo xtask install --server ``` For non-standard setup of VS Code and other editors, see [./docs/user](./docs/user). diff --git a/crates/ra_tools/Cargo.toml b/crates/ra_tools/Cargo.toml deleted file mode 100644 index 9cceacee3..000000000 --- a/crates/ra_tools/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -edition = "2018" -name = "ra_tools" -version = "0.1.0" -authors = ["rust-analyzer developers"] -publish = false - -[dependencies] -walkdir = "2.1.3" -itertools = "0.8.0" -pico-args = "0.3.0" -quote = "1.0.2" -proc-macro2 = "1.0.1" -ron = "0.5.1" -serde = { version = "1.0.0", features = ["derive"] } diff --git a/crates/ra_tools/src/bin/pre-commit.rs b/crates/ra_tools/src/bin/pre-commit.rs deleted file mode 100644 index 16bbf9cb2..000000000 --- a/crates/ra_tools/src/bin/pre-commit.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! FIXME: write short doc here - -use std::process::Command; - -use ra_tools::{project_root, run, run_rustfmt, Overwrite, Result}; - -fn main() -> Result<()> { - run_rustfmt(Overwrite)?; - update_staged() -} - -fn update_staged() -> Result<()> { - let root = project_root(); - let output = Command::new("git") - .arg("diff") - .arg("--diff-filter=MAR") - .arg("--name-only") - .arg("--cached") - .current_dir(&root) - .output()?; - if !output.status.success() { - Err(format!( - "`git diff --diff-filter=MAR --name-only --cached` exited with {}", - output.status - ))?; - } - for line in String::from_utf8(output.stdout)?.lines() { - run(&format!("git update-index --add {}", root.join(line).to_string_lossy()), ".")?; - } - Ok(()) -} diff --git a/crates/ra_tools/src/boilerplate_gen.rs b/crates/ra_tools/src/boilerplate_gen.rs deleted file mode 100644 index 39f1cae66..000000000 --- a/crates/ra_tools/src/boilerplate_gen.rs +++ /dev/null @@ -1,348 +0,0 @@ -//! FIXME: write short doc here - -use std::{ - collections::BTreeMap, - fs, - io::Write, - process::{Command, Stdio}, -}; - -use proc_macro2::{Punct, Spacing}; -use quote::{format_ident, quote}; -use ron; -use serde::Deserialize; - -use crate::{project_root, update, Mode, Result, AST, GRAMMAR, SYNTAX_KINDS}; - -pub fn generate_boilerplate(mode: Mode) -> Result<()> { - let grammar = project_root().join(GRAMMAR); - let grammar: Grammar = { - let text = fs::read_to_string(grammar)?; - ron::de::from_str(&text)? - }; - - let syntax_kinds_file = project_root().join(SYNTAX_KINDS); - let syntax_kinds = generate_syntax_kinds(&grammar)?; - update(syntax_kinds_file.as_path(), &syntax_kinds, mode)?; - - let ast_file = project_root().join(AST); - let ast = generate_ast(&grammar)?; - update(ast_file.as_path(), &ast, mode)?; - - Ok(()) -} - -fn generate_ast(grammar: &Grammar) -> Result { - let nodes = grammar.ast.iter().map(|(name, ast_node)| { - let variants = - ast_node.variants.iter().map(|var| format_ident!("{}", var)).collect::>(); - let name = format_ident!("{}", name); - - let adt = if variants.is_empty() { - let kind = format_ident!("{}", to_upper_snake_case(&name.to_string())); - quote! { - #[derive(Debug, Clone, PartialEq, Eq, Hash)] - pub struct #name { - pub(crate) syntax: SyntaxNode, - } - - impl AstNode for #name { - fn can_cast(kind: SyntaxKind) -> bool { - match kind { - #kind => true, - _ => false, - } - } - fn cast(syntax: SyntaxNode) -> Option { - if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } - } - fn syntax(&self) -> &SyntaxNode { &self.syntax } - } - } - } else { - let kinds = variants - .iter() - .map(|name| format_ident!("{}", to_upper_snake_case(&name.to_string()))) - .collect::>(); - - quote! { - #[derive(Debug, Clone, PartialEq, Eq, Hash)] - pub enum #name { - #(#variants(#variants),)* - } - - #( - impl From<#variants> for #name { - fn from(node: #variants) -> #name { - #name::#variants(node) - } - } - )* - - impl AstNode for #name { - fn can_cast(kind: SyntaxKind) -> bool { - match kind { - #(#kinds)|* => true, - _ => false, - } - } - fn cast(syntax: SyntaxNode) -> Option { - let res = match syntax.kind() { - #( - #kinds => #name::#variants(#variants { syntax }), - )* - _ => return None, - }; - Some(res) - } - fn syntax(&self) -> &SyntaxNode { - match self { - #( - #name::#variants(it) => &it.syntax, - )* - } - } - } - } - }; - - let traits = ast_node.traits.iter().map(|trait_name| { - let trait_name = format_ident!("{}", trait_name); - quote!(impl ast::#trait_name for #name {}) - }); - - let collections = ast_node.collections.iter().map(|(name, kind)| { - let method_name = format_ident!("{}", name); - let kind = format_ident!("{}", kind); - quote! { - pub fn #method_name(&self) -> AstChildren<#kind> { - AstChildren::new(&self.syntax) - } - } - }); - - let options = ast_node.options.iter().map(|attr| { - let method_name = match attr { - Attr::Type(t) => format_ident!("{}", to_lower_snake_case(&t)), - Attr::NameType(n, _) => format_ident!("{}", n), - }; - let ty = match attr { - Attr::Type(t) | Attr::NameType(_, t) => format_ident!("{}", t), - }; - quote! { - pub fn #method_name(&self) -> Option<#ty> { - AstChildren::new(&self.syntax).next() - } - } - }); - - quote! { - #adt - - #(#traits)* - - impl #name { - #(#collections)* - #(#options)* - } - } - }); - - let ast = quote! { - use crate::{ - SyntaxNode, SyntaxKind::{self, *}, - ast::{self, AstNode, AstChildren}, - }; - - #(#nodes)* - }; - - let pretty = reformat(ast)?; - Ok(pretty) -} - -fn generate_syntax_kinds(grammar: &Grammar) -> Result { - let (single_byte_tokens_values, single_byte_tokens): (Vec<_>, Vec<_>) = grammar - .punct - .iter() - .filter(|(token, _name)| token.len() == 1) - .map(|(token, name)| (token.chars().next().unwrap(), format_ident!("{}", name))) - .unzip(); - - let punctuation_values = grammar.punct.iter().map(|(token, _name)| { - if "{}[]()".contains(token) { - let c = token.chars().next().unwrap(); - quote! { #c } - } else { - let cs = token.chars().map(|c| Punct::new(c, Spacing::Joint)); - quote! { #(#cs)* } - } - }); - let punctuation = - grammar.punct.iter().map(|(_token, name)| format_ident!("{}", name)).collect::>(); - - let full_keywords_values = &grammar.keywords; - let full_keywords = - full_keywords_values.iter().map(|kw| format_ident!("{}_KW", to_upper_snake_case(&kw))); - - let all_keywords_values = - grammar.keywords.iter().chain(grammar.contextual_keywords.iter()).collect::>(); - let all_keywords_idents = all_keywords_values.iter().map(|kw| format_ident!("{}", kw)); - let all_keywords = all_keywords_values - .iter() - .map(|name| format_ident!("{}_KW", to_upper_snake_case(&name))) - .collect::>(); - - let literals = - grammar.literals.iter().map(|name| format_ident!("{}", name)).collect::>(); - - let tokens = grammar.tokens.iter().map(|name| format_ident!("{}", name)).collect::>(); - - let nodes = grammar.nodes.iter().map(|name| format_ident!("{}", name)).collect::>(); - - let ast = quote! { - #![allow(bad_style, missing_docs, unreachable_pub)] - /// The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT_DEF`. - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] - #[repr(u16)] - pub enum SyntaxKind { - // Technical SyntaxKinds: they appear temporally during parsing, - // but never end up in the final tree - #[doc(hidden)] - TOMBSTONE, - #[doc(hidden)] - EOF, - #(#punctuation,)* - #(#all_keywords,)* - #(#literals,)* - #(#tokens,)* - #(#nodes,)* - - // Technical kind so that we can cast from u16 safely - #[doc(hidden)] - __LAST, - } - use self::SyntaxKind::*; - - impl SyntaxKind { - pub fn is_keyword(self) -> bool { - match self { - #(#all_keywords)|* => true, - _ => false, - } - } - - pub fn is_punct(self) -> bool { - match self { - #(#punctuation)|* => true, - _ => false, - } - } - - pub fn is_literal(self) -> bool { - match self { - #(#literals)|* => true, - _ => false, - } - } - - pub fn from_keyword(ident: &str) -> Option { - let kw = match ident { - #(#full_keywords_values => #full_keywords,)* - _ => return None, - }; - Some(kw) - } - - pub fn from_char(c: char) -> Option { - let tok = match c { - #(#single_byte_tokens_values => #single_byte_tokens,)* - _ => return None, - }; - Some(tok) - } - } - - #[macro_export] - macro_rules! T { - #((#punctuation_values) => { $crate::SyntaxKind::#punctuation };)* - #((#all_keywords_idents) => { $crate::SyntaxKind::#all_keywords };)* - } - }; - - reformat(ast) -} - -fn reformat(text: impl std::fmt::Display) -> Result { - let mut rustfmt = Command::new("rustfmt") - .arg("--config-path") - .arg(project_root().join("rustfmt.toml")) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn()?; - write!(rustfmt.stdin.take().unwrap(), "{}", text)?; - let output = rustfmt.wait_with_output()?; - let stdout = String::from_utf8(output.stdout)?; - let preamble = "Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`"; - Ok(format!("//! {}\n\n{}", preamble, stdout)) -} - -#[derive(Deserialize, Debug)] -struct Grammar { - punct: Vec<(String, String)>, - keywords: Vec, - contextual_keywords: Vec, - literals: Vec, - tokens: Vec, - nodes: Vec, - ast: BTreeMap, -} - -#[derive(Deserialize, Debug)] -struct AstNode { - #[serde(default)] - #[serde(rename = "enum")] - variants: Vec, - - #[serde(default)] - traits: Vec, - #[serde(default)] - collections: Vec<(String, String)>, - #[serde(default)] - options: Vec, -} - -#[derive(Deserialize, Debug)] -#[serde(untagged)] -enum Attr { - Type(String), - NameType(String, String), -} - -fn to_upper_snake_case(s: &str) -> String { - let mut buf = String::with_capacity(s.len()); - let mut prev_is_upper = None; - for c in s.chars() { - if c.is_ascii_uppercase() && prev_is_upper == Some(false) { - buf.push('_') - } - prev_is_upper = Some(c.is_ascii_uppercase()); - - buf.push(c.to_ascii_uppercase()); - } - buf -} - -fn to_lower_snake_case(s: &str) -> String { - let mut buf = String::with_capacity(s.len()); - let mut prev_is_upper = None; - for c in s.chars() { - if c.is_ascii_uppercase() && prev_is_upper == Some(false) { - buf.push('_') - } - prev_is_upper = Some(c.is_ascii_uppercase()); - - buf.push(c.to_ascii_lowercase()); - } - buf -} diff --git a/crates/ra_tools/src/help.rs b/crates/ra_tools/src/help.rs deleted file mode 100644 index 72dfabacd..000000000 --- a/crates/ra_tools/src/help.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! FIXME: write short doc here - -pub const GLOBAL_HELP: &str = "tasks - -USAGE: - ra_tools - -FLAGS: - -h, --help Prints help information - -SUBCOMMANDS: - format - format-hook - fuzz-tests - gen-syntax - gen-tests - install-ra - lint"; - -pub const INSTALL_RA_HELP: &str = "ra_tools-install-ra - -USAGE: - ra_tools.exe install-ra [FLAGS] - -FLAGS: - --client-code - -h, --help Prints help information - --jemalloc - --server"; - -pub fn print_no_param_subcommand_help(subcommand: &str) { - eprintln!( - "ra_tools-{} - -USAGE: - ra_tools {} - -FLAGS: - -h, --help Prints help information", - subcommand, subcommand - ); -} - -pub const INSTALL_RA_CONFLICT: &str = - "error: The argument `--server` cannot be used with `--client-code` - -For more information try --help"; diff --git a/crates/ra_tools/src/lib.rs b/crates/ra_tools/src/lib.rs deleted file mode 100644 index aa993a38a..000000000 --- a/crates/ra_tools/src/lib.rs +++ /dev/null @@ -1,332 +0,0 @@ -//! FIXME: write short doc here - -mod boilerplate_gen; - -use std::{ - collections::HashMap, - error::Error, - fs, - io::{Error as IoError, ErrorKind}, - path::{Path, PathBuf}, - process::{Command, Output, Stdio}, -}; - -use itertools::Itertools; - -pub use self::boilerplate_gen::generate_boilerplate; - -pub type Result = std::result::Result>; - -pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron"; -const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar"; -const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/ok"; -const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/err"; - -pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs"; -pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs"; -const TOOLCHAIN: &str = "stable"; - -#[derive(Debug, PartialEq, Eq, Clone, Copy)] -pub enum Mode { - Overwrite, - Verify, -} -pub use Mode::*; - -#[derive(Debug)] -pub struct Test { - pub name: String, - pub text: String, - pub ok: bool, -} - -pub fn collect_tests(s: &str) -> Vec<(usize, Test)> { - let mut res = vec![]; - let prefix = "// "; - let comment_blocks = s - .lines() - .map(str::trim_start) - .enumerate() - .group_by(|(_idx, line)| line.starts_with(prefix)); - - 'outer: for (is_comment, block) in comment_blocks.into_iter() { - if !is_comment { - continue; - } - let mut block = block.map(|(idx, line)| (idx, &line[prefix.len()..])); - - let mut ok = true; - let (start_line, name) = loop { - match block.next() { - Some((idx, line)) if line.starts_with("test ") => { - break (idx, line["test ".len()..].to_string()); - } - Some((idx, line)) if line.starts_with("test_err ") => { - ok = false; - break (idx, line["test_err ".len()..].to_string()); - } - Some(_) => (), - None => continue 'outer, - } - }; - let text: String = - itertools::join(block.map(|(_, line)| line).chain(::std::iter::once("")), "\n"); - assert!(!text.trim().is_empty() && text.ends_with('\n')); - res.push((start_line, Test { name, text, ok })) - } - res -} - -pub fn project_root() -> PathBuf { - Path::new(&env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap().to_path_buf() -} - -pub struct Cmd<'a> { - pub unix: &'a str, - pub windows: &'a str, - pub work_dir: &'a str, -} - -impl Cmd<'_> { - pub fn run(self) -> Result<()> { - if cfg!(windows) { - run(self.windows, self.work_dir) - } else { - run(self.unix, self.work_dir) - } - } - pub fn run_with_output(self) -> Result { - if cfg!(windows) { - run_with_output(self.windows, self.work_dir) - } else { - run_with_output(self.unix, self.work_dir) - } - } -} - -pub fn run(cmdline: &str, dir: &str) -> Result<()> { - do_run(cmdline, dir, |c| { - c.stdout(Stdio::inherit()); - }) - .map(|_| ()) -} - -pub fn run_with_output(cmdline: &str, dir: &str) -> Result { - do_run(cmdline, dir, |_| {}) -} - -pub fn run_rustfmt(mode: Mode) -> Result<()> { - match Command::new("rustup") - .args(&["run", TOOLCHAIN, "--", "cargo", "fmt", "--version"]) - .stderr(Stdio::null()) - .stdout(Stdio::null()) - .status() - { - Ok(status) if status.success() => (), - _ => install_rustfmt()?, - }; - - if mode == Verify { - run(&format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN), ".")?; - } else { - run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?; - } - Ok(()) -} - -pub fn install_rustfmt() -> Result<()> { - run(&format!("rustup install {}", TOOLCHAIN), ".")?; - run(&format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN), ".") -} - -pub fn install_format_hook() -> Result<()> { - let result_path = Path::new(if cfg!(windows) { - "./.git/hooks/pre-commit.exe" - } else { - "./.git/hooks/pre-commit" - }); - if !result_path.exists() { - run("cargo build --package ra_tools --bin pre-commit", ".")?; - if cfg!(windows) { - fs::copy("./target/debug/pre-commit.exe", result_path)?; - } else { - fs::copy("./target/debug/pre-commit", result_path)?; - } - } else { - Err(IoError::new(ErrorKind::AlreadyExists, "Git hook already created"))?; - } - Ok(()) -} - -pub fn run_clippy() -> Result<()> { - match Command::new("rustup") - .args(&["run", TOOLCHAIN, "--", "cargo", "clippy", "--version"]) - .stderr(Stdio::null()) - .stdout(Stdio::null()) - .status() - { - Ok(status) if status.success() => (), - _ => install_clippy()?, - }; - - let allowed_lints = [ - "clippy::collapsible_if", - "clippy::map_clone", // FIXME: remove when Iterator::copied stabilizes (1.36.0) - "clippy::needless_pass_by_value", - "clippy::nonminimal_bool", - "clippy::redundant_pattern_matching", - ]; - run( - &format!( - "rustup run {} -- cargo clippy --all-features --all-targets -- -A {}", - TOOLCHAIN, - allowed_lints.join(" -A ") - ), - ".", - )?; - Ok(()) -} - -pub fn install_clippy() -> Result<()> { - run(&format!("rustup install {}", TOOLCHAIN), ".")?; - run(&format!("rustup component add clippy --toolchain {}", TOOLCHAIN), ".") -} - -pub fn run_fuzzer() -> Result<()> { - match Command::new("cargo") - .args(&["fuzz", "--help"]) - .stderr(Stdio::null()) - .stdout(Stdio::null()) - .status() - { - Ok(status) if status.success() => (), - _ => run("cargo install cargo-fuzz", ".")?, - }; - - run("rustup run nightly -- cargo fuzz run parser", "./crates/ra_syntax") -} - -pub fn gen_tests(mode: Mode) -> Result<()> { - let tests = tests_from_dir(&project_root().join(Path::new(GRAMMAR_DIR)))?; - fn install_tests(tests: &HashMap, into: &str, mode: Mode) -> Result<()> { - let tests_dir = project_root().join(into); - if !tests_dir.is_dir() { - fs::create_dir_all(&tests_dir)?; - } - // ok is never actually read, but it needs to be specified to create a Test in existing_tests - let existing = existing_tests(&tests_dir, true)?; - for t in existing.keys().filter(|&t| !tests.contains_key(t)) { - panic!("Test is deleted: {}", t); - } - - let mut new_idx = existing.len() + 1; - for (name, test) in tests { - let path = match existing.get(name) { - Some((path, _test)) => path.clone(), - None => { - let file_name = format!("{:04}_{}.rs", new_idx, name); - new_idx += 1; - tests_dir.join(file_name) - } - }; - update(&path, &test.text, mode)?; - } - Ok(()) - } - install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?; - install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode) -} - -fn do_run(cmdline: &str, dir: &str, mut f: F) -> Result -where - F: FnMut(&mut Command), -{ - eprintln!("\nwill run: {}", cmdline); - let proj_dir = project_root().join(dir); - let mut args = cmdline.split_whitespace(); - let exec = args.next().unwrap(); - let mut cmd = Command::new(exec); - f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit())); - let output = cmd.output()?; - if !output.status.success() { - Err(format!("`{}` exited with {}", cmdline, output.status))?; - } - Ok(output) -} - -#[derive(Default, Debug)] -struct Tests { - pub ok: HashMap, - pub err: HashMap, -} - -fn tests_from_dir(dir: &Path) -> Result { - let mut res = Tests::default(); - for entry in ::walkdir::WalkDir::new(dir) { - let entry = entry.unwrap(); - if !entry.file_type().is_file() { - continue; - } - if entry.path().extension().unwrap_or_default() != "rs" { - continue; - } - process_file(&mut res, entry.path())?; - } - let grammar_rs = dir.parent().unwrap().join("grammar.rs"); - process_file(&mut res, &grammar_rs)?; - return Ok(res); - fn process_file(res: &mut Tests, path: &Path) -> Result<()> { - let text = fs::read_to_string(path)?; - - for (_, test) in collect_tests(&text) { - if test.ok { - if let Some(old_test) = res.ok.insert(test.name.clone(), test) { - Err(format!("Duplicate test: {}", old_test.name))? - } - } else { - if let Some(old_test) = res.err.insert(test.name.clone(), test) { - Err(format!("Duplicate test: {}", old_test.name))? - } - } - } - Ok(()) - } -} - -fn existing_tests(dir: &Path, ok: bool) -> Result> { - let mut res = HashMap::new(); - for file in fs::read_dir(dir)? { - let file = file?; - let path = file.path(); - if path.extension().unwrap_or_default() != "rs" { - continue; - } - let name = { - let file_name = path.file_name().unwrap().to_str().unwrap(); - file_name[5..file_name.len() - 3].to_string() - }; - let text = fs::read_to_string(&path)?; - let test = Test { name: name.clone(), text, ok }; - if let Some(old) = res.insert(name, (path, test)) { - println!("Duplicate test: {:?}", old); - } - } - Ok(res) -} - -/// A helper to update file on disk if it has changed. -/// With verify = false, -pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> { - match fs::read_to_string(path) { - Ok(ref old_contents) if old_contents == contents => { - return Ok(()); - } - _ => (), - } - if mode == Verify { - Err(format!("`{}` is not up-to-date", path.display()))?; - } - eprintln!("updating {}", path.display()); - fs::write(path, contents)?; - Ok(()) -} diff --git a/crates/ra_tools/src/main.rs b/crates/ra_tools/src/main.rs deleted file mode 100644 index 161871ccf..000000000 --- a/crates/ra_tools/src/main.rs +++ /dev/null @@ -1,218 +0,0 @@ -//! FIXME: write short doc here - -mod help; - -use core::fmt::Write; -use core::str; -use pico_args::Arguments; -use ra_tools::{ - gen_tests, generate_boilerplate, install_format_hook, run, run_clippy, run_fuzzer, run_rustfmt, - Cmd, Overwrite, Result, -}; -use std::{env, path::PathBuf}; - -struct InstallOpt { - client: Option, - server: Option, -} - -enum ClientOpt { - VsCode, -} - -struct ServerOpt { - jemalloc: bool, -} - -fn main() -> Result<()> { - let subcommand = match std::env::args_os().nth(1) { - None => { - eprintln!("{}", help::GLOBAL_HELP); - return Ok(()); - } - Some(s) => s, - }; - let mut matches = Arguments::from_vec(std::env::args_os().skip(2).collect()); - let subcommand = &*subcommand.to_string_lossy(); - match subcommand { - "install-ra" | "install-code" => { - if matches.contains(["-h", "--help"]) { - eprintln!("{}", help::INSTALL_RA_HELP); - return Ok(()); - } - let server = matches.contains("--server"); - let client_code = matches.contains("--client-code"); - if server && client_code { - eprintln!("{}", help::INSTALL_RA_CONFLICT); - return Ok(()); - } - let jemalloc = matches.contains("--jemalloc"); - matches.finish().or_else(handle_extra_flags)?; - let opts = InstallOpt { - client: if server { None } else { Some(ClientOpt::VsCode) }, - server: if client_code { None } else { Some(ServerOpt { jemalloc: jemalloc }) }, - }; - install(opts)? - } - "gen-tests" => { - if matches.contains(["-h", "--help"]) { - help::print_no_param_subcommand_help(&subcommand); - return Ok(()); - } - gen_tests(Overwrite)? - } - "gen-syntax" => { - if matches.contains(["-h", "--help"]) { - help::print_no_param_subcommand_help(&subcommand); - return Ok(()); - } - generate_boilerplate(Overwrite)? - } - "format" => { - if matches.contains(["-h", "--help"]) { - help::print_no_param_subcommand_help(&subcommand); - return Ok(()); - } - run_rustfmt(Overwrite)? - } - "format-hook" => { - if matches.contains(["-h", "--help"]) { - help::print_no_param_subcommand_help(&subcommand); - return Ok(()); - } - install_format_hook()? - } - "lint" => { - if matches.contains(["-h", "--help"]) { - help::print_no_param_subcommand_help(&subcommand); - return Ok(()); - } - run_clippy()? - } - "fuzz-tests" => { - if matches.contains(["-h", "--help"]) { - help::print_no_param_subcommand_help(&subcommand); - return Ok(()); - } - run_fuzzer()? - } - _ => eprintln!("{}", help::GLOBAL_HELP), - } - Ok(()) -} - -fn handle_extra_flags(e: pico_args::Error) -> Result<()> { - if let pico_args::Error::UnusedArgsLeft(flags) = e { - let mut invalid_flags = String::new(); - for flag in flags { - write!(&mut invalid_flags, "{}, ", flag)?; - } - let (invalid_flags, _) = invalid_flags.split_at(invalid_flags.len() - 2); - Err(format!("Invalid flags: {}", invalid_flags).into()) - } else { - Err(e.to_string().into()) - } -} - -fn install(opts: InstallOpt) -> Result<()> { - if cfg!(target_os = "macos") { - fix_path_for_mac()? - } - if let Some(server) = opts.server { - install_server(server)?; - } - if let Some(client) = opts.client { - install_client(client)?; - } - Ok(()) -} - -fn fix_path_for_mac() -> Result<()> { - let mut vscode_path: Vec = { - const COMMON_APP_PATH: &str = - r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin"; - const ROOT_DIR: &str = ""; - let home_dir = match env::var("HOME") { - Ok(home) => home, - Err(e) => Err(format!("Failed getting HOME from environment with error: {}.", e))?, - }; - - [ROOT_DIR, &home_dir] - .iter() - .map(|dir| String::from(*dir) + COMMON_APP_PATH) - .map(PathBuf::from) - .filter(|path| path.exists()) - .collect() - }; - - if !vscode_path.is_empty() { - let vars = match env::var_os("PATH") { - Some(path) => path, - None => Err("Could not get PATH variable from env.")?, - }; - - let mut paths = env::split_paths(&vars).collect::>(); - paths.append(&mut vscode_path); - let new_paths = env::join_paths(paths)?; - env::set_var("PATH", &new_paths); - } - - Ok(()) -} - -fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { - Cmd { unix: r"npm ci", windows: r"cmd.exe /c npm.cmd ci", work_dir: "./editors/code" }.run()?; - Cmd { - unix: r"npm run package", - windows: r"cmd.exe /c npm.cmd run package", - work_dir: "./editors/code", - } - .run()?; - - let code_binary = ["code", "code-insiders", "codium"].iter().find(|bin| { - Cmd { - unix: &format!("{} --version", bin), - windows: &format!("cmd.exe /c {}.cmd --version", bin), - work_dir: "./editors/code", - } - .run() - .is_ok() - }); - - let code_binary = match code_binary { - Some(it) => it, - None => Err("Can't execute `code --version`. Perhaps it is not in $PATH?")?, - }; - - Cmd { - unix: &format!(r"{} --install-extension ./ra-lsp-0.0.1.vsix --force", code_binary), - windows: &format!( - r"cmd.exe /c {}.cmd --install-extension ./ra-lsp-0.0.1.vsix --force", - code_binary - ), - work_dir: "./editors/code", - } - .run()?; - - let output = Cmd { - unix: &format!(r"{} --list-extensions", code_binary), - windows: &format!(r"cmd.exe /c {}.cmd --list-extensions", code_binary), - work_dir: ".", - } - .run_with_output()?; - - if !str::from_utf8(&output.stdout)?.contains("ra-lsp") { - Err("Could not install the Visual Studio Code extension. \ - Please make sure you have at least NodeJS 10.x installed and try again.")?; - } - - Ok(()) -} - -fn install_server(opts: ServerOpt) -> Result<()> { - if opts.jemalloc { - run("cargo install --path crates/ra_lsp_server --locked --force --features jemalloc", ".") - } else { - run("cargo install --path crates/ra_lsp_server --locked --force", ".") - } -} diff --git a/crates/ra_tools/tests/cli.rs b/crates/ra_tools/tests/cli.rs deleted file mode 100644 index 609fd4d8b..000000000 --- a/crates/ra_tools/tests/cli.rs +++ /dev/null @@ -1,45 +0,0 @@ -use ra_tools::{gen_tests, generate_boilerplate, project_root, run_rustfmt, Verify}; -use walkdir::WalkDir; - -#[test] -fn generated_grammar_is_fresh() { - if let Err(error) = generate_boilerplate(Verify) { - panic!("{}. Please update it by running `cargo gen-syntax`", error); - } -} - -#[test] -fn generated_tests_are_fresh() { - if let Err(error) = gen_tests(Verify) { - panic!("{}. Please update tests by running `cargo gen-tests`", error); - } -} - -#[test] -fn check_code_formatting() { - if let Err(error) = run_rustfmt(Verify) { - panic!("{}. Please format the code by running `cargo format`", error); - } -} - -#[test] -fn no_todo() { - WalkDir::new(project_root().join("crates")).into_iter().for_each(|e| { - let e = e.unwrap(); - if e.path().extension().map(|it| it != "rs").unwrap_or(true) { - return; - } - if e.path().ends_with("tests/cli.rs") { - return; - } - let text = std::fs::read_to_string(e.path()).unwrap(); - if text.contains("TODO") || text.contains("TOOD") { - panic!( - "\nTODO markers should not be committed to the master branch,\n\ - use FIXME instead\n\ - {}\n", - e.path().display(), - ) - } - }) -} diff --git a/crates/ra_tools/tests/docs.rs b/crates/ra_tools/tests/docs.rs deleted file mode 100644 index ea3330175..000000000 --- a/crates/ra_tools/tests/docs.rs +++ /dev/null @@ -1,63 +0,0 @@ -use std::fs; -use std::io::prelude::*; -use std::io::BufReader; -use std::path::Path; - -use walkdir::{DirEntry, WalkDir}; - -use ra_tools::project_root; - -fn is_exclude_dir(p: &Path) -> bool { - let exclude_dirs = ["tests", "test_data"]; - let mut cur_path = p; - while let Some(path) = cur_path.parent() { - if exclude_dirs.iter().any(|dir| path.ends_with(dir)) { - return true; - } - cur_path = path; - } - - false -} - -fn is_exclude_file(d: &DirEntry) -> bool { - let file_names = ["tests.rs"]; - - d.file_name().to_str().map(|f_n| file_names.iter().any(|name| *name == f_n)).unwrap_or(false) -} - -fn is_hidden(entry: &DirEntry) -> bool { - entry.file_name().to_str().map(|s| s.starts_with(".")).unwrap_or(false) -} - -#[test] -fn no_docs_comments() { - let crates = project_root().join("crates"); - let iter = WalkDir::new(crates); - for f in iter.into_iter().filter_entry(|e| !is_hidden(e)) { - let f = f.unwrap(); - if f.file_type().is_dir() { - continue; - } - if f.path().extension().map(|it| it != "rs").unwrap_or(false) { - continue; - } - if is_exclude_dir(f.path()) { - continue; - } - if is_exclude_file(&f) { - continue; - } - let mut reader = BufReader::new(fs::File::open(f.path()).unwrap()); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - if !line.starts_with("//!") { - panic!( - "\nMissing docs strings\n\ - module: {}\n\ - Need add doc for module\n", - f.path().display() - ) - } - } -} diff --git a/crates/ra_tools/tests/main.rs b/crates/ra_tools/tests/main.rs deleted file mode 100644 index 56d1318d6..000000000 --- a/crates/ra_tools/tests/main.rs +++ /dev/null @@ -1,2 +0,0 @@ -mod cli; -mod docs; diff --git a/docs/dev/architecture.md b/docs/dev/architecture.md index 1ffabc6ef..28f2a37e5 100644 --- a/docs/dev/architecture.md +++ b/docs/dev/architecture.md @@ -45,21 +45,15 @@ can be quickly updated for small modifications. Some of the components of this repository are generated through automatic processes. These are outlined below: -- `gen-syntax`: The kinds of tokens that are reused in several places, so a generator - is used. We use tera templates to generate the files listed below, based on +- `cargo xtask codegen`: The kinds of tokens that are reused in several places, so a generator + is used. We use `quote!` macro to generate the files listed below, based on the grammar described in [grammar.ron]: - - [ast/generated.rs][ast generated] in `ra_syntax` based on - [ast/generated.tera.rs][ast source] - - [syntax_kind/generated.rs][syntax_kind generated] in `ra_syntax` based on - [syntax_kind/generated.tera.rs][syntax_kind source] + - [ast/generated.rs][ast generated] + - [syntax_kind/generated.rs][syntax_kind generated] -[tera]: https://tera.netlify.com/ [grammar.ron]: ../../crates/ra_syntax/src/grammar.ron [ast generated]: ../../crates/ra_syntax/src/ast/generated.rs -[ast source]: ../../crates/ra_syntax/src/ast/generated.rs.tera [syntax_kind generated]: ../../crates/ra_parser/src/syntax_kind/generated.rs -[syntax_kind source]: ../../crates/ra_parser/src/syntax_kind/generated.rs.tera - ## Code Walk-Through diff --git a/docs/user/README.md b/docs/user/README.md index 5b7502132..f45c0d7d1 100644 --- a/docs/user/README.md +++ b/docs/user/README.md @@ -1,6 +1,6 @@ The main interface to rust-analyzer is the [LSP](https://microsoft.github.io/language-server-protocol/) implementation. To -install lsp server, use `cargo install-ra --server`, which is a shorthand for `cargo +install lsp server, use `cargo xtask install --server`, which is a shorthand for `cargo install --package ra_lsp_server`. The binary is named `ra_lsp_server`, you should be able to use it with any LSP-compatible editor. We use custom extensions to LSP, so special client-side support is required to take full @@ -33,7 +33,7 @@ following commands: ``` $ git clone https://github.com/rust-analyzer/rust-analyzer.git --depth 1 $ cd rust-analyzer -$ cargo install-ra +$ cargo xtask install ``` The automatic installation is expected to *just work* for common cases, if it @@ -58,7 +58,7 @@ Beyond basic LSP features, there are some extension commands which you can invoke via Ctrl+Shift+P or bind to a shortcut. See [./features.md](./features.md) for details. -For updates, pull the latest changes from the master branch, run `cargo install-ra` again, and **restart** VS Code instance. +For updates, pull the latest changes from the master branch, run `cargo xtask install` again, and **restart** VS Code instance. See [microsoft/vscode#72308](https://github.com/microsoft/vscode/issues/72308) for why a full restart is needed. ### Settings diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 000000000..4fc1c744b --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,15 @@ +[package] +edition = "2018" +name = "xtask" +version = "0.1.0" +authors = ["rust-analyzer developers"] +publish = false + +[dependencies] +walkdir = "2.1.3" +itertools = "0.8.0" +pico-args = "0.3.0" +quote = "1.0.2" +proc-macro2 = "1.0.1" +ron = "0.5.1" +serde = { version = "1.0.0", features = ["derive"] } diff --git a/xtask/src/bin/pre-commit.rs b/xtask/src/bin/pre-commit.rs new file mode 100644 index 000000000..16bbf9cb2 --- /dev/null +++ b/xtask/src/bin/pre-commit.rs @@ -0,0 +1,31 @@ +//! FIXME: write short doc here + +use std::process::Command; + +use ra_tools::{project_root, run, run_rustfmt, Overwrite, Result}; + +fn main() -> Result<()> { + run_rustfmt(Overwrite)?; + update_staged() +} + +fn update_staged() -> Result<()> { + let root = project_root(); + let output = Command::new("git") + .arg("diff") + .arg("--diff-filter=MAR") + .arg("--name-only") + .arg("--cached") + .current_dir(&root) + .output()?; + if !output.status.success() { + Err(format!( + "`git diff --diff-filter=MAR --name-only --cached` exited with {}", + output.status + ))?; + } + for line in String::from_utf8(output.stdout)?.lines() { + run(&format!("git update-index --add {}", root.join(line).to_string_lossy()), ".")?; + } + Ok(()) +} diff --git a/xtask/src/boilerplate_gen.rs b/xtask/src/boilerplate_gen.rs new file mode 100644 index 000000000..39f1cae66 --- /dev/null +++ b/xtask/src/boilerplate_gen.rs @@ -0,0 +1,348 @@ +//! FIXME: write short doc here + +use std::{ + collections::BTreeMap, + fs, + io::Write, + process::{Command, Stdio}, +}; + +use proc_macro2::{Punct, Spacing}; +use quote::{format_ident, quote}; +use ron; +use serde::Deserialize; + +use crate::{project_root, update, Mode, Result, AST, GRAMMAR, SYNTAX_KINDS}; + +pub fn generate_boilerplate(mode: Mode) -> Result<()> { + let grammar = project_root().join(GRAMMAR); + let grammar: Grammar = { + let text = fs::read_to_string(grammar)?; + ron::de::from_str(&text)? + }; + + let syntax_kinds_file = project_root().join(SYNTAX_KINDS); + let syntax_kinds = generate_syntax_kinds(&grammar)?; + update(syntax_kinds_file.as_path(), &syntax_kinds, mode)?; + + let ast_file = project_root().join(AST); + let ast = generate_ast(&grammar)?; + update(ast_file.as_path(), &ast, mode)?; + + Ok(()) +} + +fn generate_ast(grammar: &Grammar) -> Result { + let nodes = grammar.ast.iter().map(|(name, ast_node)| { + let variants = + ast_node.variants.iter().map(|var| format_ident!("{}", var)).collect::>(); + let name = format_ident!("{}", name); + + let adt = if variants.is_empty() { + let kind = format_ident!("{}", to_upper_snake_case(&name.to_string())); + quote! { + #[derive(Debug, Clone, PartialEq, Eq, Hash)] + pub struct #name { + pub(crate) syntax: SyntaxNode, + } + + impl AstNode for #name { + fn can_cast(kind: SyntaxKind) -> bool { + match kind { + #kind => true, + _ => false, + } + } + fn cast(syntax: SyntaxNode) -> Option { + if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } + } + fn syntax(&self) -> &SyntaxNode { &self.syntax } + } + } + } else { + let kinds = variants + .iter() + .map(|name| format_ident!("{}", to_upper_snake_case(&name.to_string()))) + .collect::>(); + + quote! { + #[derive(Debug, Clone, PartialEq, Eq, Hash)] + pub enum #name { + #(#variants(#variants),)* + } + + #( + impl From<#variants> for #name { + fn from(node: #variants) -> #name { + #name::#variants(node) + } + } + )* + + impl AstNode for #name { + fn can_cast(kind: SyntaxKind) -> bool { + match kind { + #(#kinds)|* => true, + _ => false, + } + } + fn cast(syntax: SyntaxNode) -> Option { + let res = match syntax.kind() { + #( + #kinds => #name::#variants(#variants { syntax }), + )* + _ => return None, + }; + Some(res) + } + fn syntax(&self) -> &SyntaxNode { + match self { + #( + #name::#variants(it) => &it.syntax, + )* + } + } + } + } + }; + + let traits = ast_node.traits.iter().map(|trait_name| { + let trait_name = format_ident!("{}", trait_name); + quote!(impl ast::#trait_name for #name {}) + }); + + let collections = ast_node.collections.iter().map(|(name, kind)| { + let method_name = format_ident!("{}", name); + let kind = format_ident!("{}", kind); + quote! { + pub fn #method_name(&self) -> AstChildren<#kind> { + AstChildren::new(&self.syntax) + } + } + }); + + let options = ast_node.options.iter().map(|attr| { + let method_name = match attr { + Attr::Type(t) => format_ident!("{}", to_lower_snake_case(&t)), + Attr::NameType(n, _) => format_ident!("{}", n), + }; + let ty = match attr { + Attr::Type(t) | Attr::NameType(_, t) => format_ident!("{}", t), + }; + quote! { + pub fn #method_name(&self) -> Option<#ty> { + AstChildren::new(&self.syntax).next() + } + } + }); + + quote! { + #adt + + #(#traits)* + + impl #name { + #(#collections)* + #(#options)* + } + } + }); + + let ast = quote! { + use crate::{ + SyntaxNode, SyntaxKind::{self, *}, + ast::{self, AstNode, AstChildren}, + }; + + #(#nodes)* + }; + + let pretty = reformat(ast)?; + Ok(pretty) +} + +fn generate_syntax_kinds(grammar: &Grammar) -> Result { + let (single_byte_tokens_values, single_byte_tokens): (Vec<_>, Vec<_>) = grammar + .punct + .iter() + .filter(|(token, _name)| token.len() == 1) + .map(|(token, name)| (token.chars().next().unwrap(), format_ident!("{}", name))) + .unzip(); + + let punctuation_values = grammar.punct.iter().map(|(token, _name)| { + if "{}[]()".contains(token) { + let c = token.chars().next().unwrap(); + quote! { #c } + } else { + let cs = token.chars().map(|c| Punct::new(c, Spacing::Joint)); + quote! { #(#cs)* } + } + }); + let punctuation = + grammar.punct.iter().map(|(_token, name)| format_ident!("{}", name)).collect::>(); + + let full_keywords_values = &grammar.keywords; + let full_keywords = + full_keywords_values.iter().map(|kw| format_ident!("{}_KW", to_upper_snake_case(&kw))); + + let all_keywords_values = + grammar.keywords.iter().chain(grammar.contextual_keywords.iter()).collect::>(); + let all_keywords_idents = all_keywords_values.iter().map(|kw| format_ident!("{}", kw)); + let all_keywords = all_keywords_values + .iter() + .map(|name| format_ident!("{}_KW", to_upper_snake_case(&name))) + .collect::>(); + + let literals = + grammar.literals.iter().map(|name| format_ident!("{}", name)).collect::>(); + + let tokens = grammar.tokens.iter().map(|name| format_ident!("{}", name)).collect::>(); + + let nodes = grammar.nodes.iter().map(|name| format_ident!("{}", name)).collect::>(); + + let ast = quote! { + #![allow(bad_style, missing_docs, unreachable_pub)] + /// The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT_DEF`. + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] + #[repr(u16)] + pub enum SyntaxKind { + // Technical SyntaxKinds: they appear temporally during parsing, + // but never end up in the final tree + #[doc(hidden)] + TOMBSTONE, + #[doc(hidden)] + EOF, + #(#punctuation,)* + #(#all_keywords,)* + #(#literals,)* + #(#tokens,)* + #(#nodes,)* + + // Technical kind so that we can cast from u16 safely + #[doc(hidden)] + __LAST, + } + use self::SyntaxKind::*; + + impl SyntaxKind { + pub fn is_keyword(self) -> bool { + match self { + #(#all_keywords)|* => true, + _ => false, + } + } + + pub fn is_punct(self) -> bool { + match self { + #(#punctuation)|* => true, + _ => false, + } + } + + pub fn is_literal(self) -> bool { + match self { + #(#literals)|* => true, + _ => false, + } + } + + pub fn from_keyword(ident: &str) -> Option { + let kw = match ident { + #(#full_keywords_values => #full_keywords,)* + _ => return None, + }; + Some(kw) + } + + pub fn from_char(c: char) -> Option { + let tok = match c { + #(#single_byte_tokens_values => #single_byte_tokens,)* + _ => return None, + }; + Some(tok) + } + } + + #[macro_export] + macro_rules! T { + #((#punctuation_values) => { $crate::SyntaxKind::#punctuation };)* + #((#all_keywords_idents) => { $crate::SyntaxKind::#all_keywords };)* + } + }; + + reformat(ast) +} + +fn reformat(text: impl std::fmt::Display) -> Result { + let mut rustfmt = Command::new("rustfmt") + .arg("--config-path") + .arg(project_root().join("rustfmt.toml")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn()?; + write!(rustfmt.stdin.take().unwrap(), "{}", text)?; + let output = rustfmt.wait_with_output()?; + let stdout = String::from_utf8(output.stdout)?; + let preamble = "Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`"; + Ok(format!("//! {}\n\n{}", preamble, stdout)) +} + +#[derive(Deserialize, Debug)] +struct Grammar { + punct: Vec<(String, String)>, + keywords: Vec, + contextual_keywords: Vec, + literals: Vec, + tokens: Vec, + nodes: Vec, + ast: BTreeMap, +} + +#[derive(Deserialize, Debug)] +struct AstNode { + #[serde(default)] + #[serde(rename = "enum")] + variants: Vec, + + #[serde(default)] + traits: Vec, + #[serde(default)] + collections: Vec<(String, String)>, + #[serde(default)] + options: Vec, +} + +#[derive(Deserialize, Debug)] +#[serde(untagged)] +enum Attr { + Type(String), + NameType(String, String), +} + +fn to_upper_snake_case(s: &str) -> String { + let mut buf = String::with_capacity(s.len()); + let mut prev_is_upper = None; + for c in s.chars() { + if c.is_ascii_uppercase() && prev_is_upper == Some(false) { + buf.push('_') + } + prev_is_upper = Some(c.is_ascii_uppercase()); + + buf.push(c.to_ascii_uppercase()); + } + buf +} + +fn to_lower_snake_case(s: &str) -> String { + let mut buf = String::with_capacity(s.len()); + let mut prev_is_upper = None; + for c in s.chars() { + if c.is_ascii_uppercase() && prev_is_upper == Some(false) { + buf.push('_') + } + prev_is_upper = Some(c.is_ascii_uppercase()); + + buf.push(c.to_ascii_lowercase()); + } + buf +} diff --git a/xtask/src/help.rs b/xtask/src/help.rs new file mode 100644 index 000000000..4c6bf6b53 --- /dev/null +++ b/xtask/src/help.rs @@ -0,0 +1,47 @@ +//! FIXME: write short doc here + +pub const GLOBAL_HELP: &str = "tasks + +USAGE: + ra_tools + +FLAGS: + -h, --help Prints help information + +SUBCOMMANDS: + format + format-hook + fuzz-tests + codegen + gen-tests + install + lint"; + +pub const INSTALL_HELP: &str = "ra_tools-install + +USAGE: + ra_tools.exe install [FLAGS] + +FLAGS: + --client-code + -h, --help Prints help information + --jemalloc + --server"; + +pub fn print_no_param_subcommand_help(subcommand: &str) { + eprintln!( + "ra_tools-{} + +USAGE: + ra_tools {} + +FLAGS: + -h, --help Prints help information", + subcommand, subcommand + ); +} + +pub const INSTALL_RA_CONFLICT: &str = + "error: The argument `--server` cannot be used with `--client-code` + +For more information try --help"; diff --git a/xtask/src/lib.rs b/xtask/src/lib.rs new file mode 100644 index 000000000..761592e85 --- /dev/null +++ b/xtask/src/lib.rs @@ -0,0 +1,332 @@ +//! FIXME: write short doc here + +mod boilerplate_gen; + +use std::{ + collections::HashMap, + error::Error, + fs, + io::{Error as IoError, ErrorKind}, + path::{Path, PathBuf}, + process::{Command, Output, Stdio}, +}; + +use itertools::Itertools; + +pub use self::boilerplate_gen::generate_boilerplate; + +pub type Result = std::result::Result>; + +pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron"; +const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar"; +const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/ok"; +const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/err"; + +pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs"; +pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs"; +const TOOLCHAIN: &str = "stable"; + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum Mode { + Overwrite, + Verify, +} +pub use Mode::*; + +#[derive(Debug)] +pub struct Test { + pub name: String, + pub text: String, + pub ok: bool, +} + +pub fn collect_tests(s: &str) -> Vec<(usize, Test)> { + let mut res = vec![]; + let prefix = "// "; + let comment_blocks = s + .lines() + .map(str::trim_start) + .enumerate() + .group_by(|(_idx, line)| line.starts_with(prefix)); + + 'outer: for (is_comment, block) in comment_blocks.into_iter() { + if !is_comment { + continue; + } + let mut block = block.map(|(idx, line)| (idx, &line[prefix.len()..])); + + let mut ok = true; + let (start_line, name) = loop { + match block.next() { + Some((idx, line)) if line.starts_with("test ") => { + break (idx, line["test ".len()..].to_string()); + } + Some((idx, line)) if line.starts_with("test_err ") => { + ok = false; + break (idx, line["test_err ".len()..].to_string()); + } + Some(_) => (), + None => continue 'outer, + } + }; + let text: String = + itertools::join(block.map(|(_, line)| line).chain(::std::iter::once("")), "\n"); + assert!(!text.trim().is_empty() && text.ends_with('\n')); + res.push((start_line, Test { name, text, ok })) + } + res +} + +pub fn project_root() -> PathBuf { + Path::new(&env!("CARGO_MANIFEST_DIR")).ancestors().nth(1).unwrap().to_path_buf() +} + +pub struct Cmd<'a> { + pub unix: &'a str, + pub windows: &'a str, + pub work_dir: &'a str, +} + +impl Cmd<'_> { + pub fn run(self) -> Result<()> { + if cfg!(windows) { + run(self.windows, self.work_dir) + } else { + run(self.unix, self.work_dir) + } + } + pub fn run_with_output(self) -> Result { + if cfg!(windows) { + run_with_output(self.windows, self.work_dir) + } else { + run_with_output(self.unix, self.work_dir) + } + } +} + +pub fn run(cmdline: &str, dir: &str) -> Result<()> { + do_run(cmdline, dir, |c| { + c.stdout(Stdio::inherit()); + }) + .map(|_| ()) +} + +pub fn run_with_output(cmdline: &str, dir: &str) -> Result { + do_run(cmdline, dir, |_| {}) +} + +pub fn run_rustfmt(mode: Mode) -> Result<()> { + match Command::new("rustup") + .args(&["run", TOOLCHAIN, "--", "cargo", "fmt", "--version"]) + .stderr(Stdio::null()) + .stdout(Stdio::null()) + .status() + { + Ok(status) if status.success() => (), + _ => install_rustfmt()?, + }; + + if mode == Verify { + run(&format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN), ".")?; + } else { + run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?; + } + Ok(()) +} + +pub fn install_rustfmt() -> Result<()> { + run(&format!("rustup install {}", TOOLCHAIN), ".")?; + run(&format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN), ".") +} + +pub fn install_format_hook() -> Result<()> { + let result_path = Path::new(if cfg!(windows) { + "./.git/hooks/pre-commit.exe" + } else { + "./.git/hooks/pre-commit" + }); + if !result_path.exists() { + run("cargo build --package ra_tools --bin pre-commit", ".")?; + if cfg!(windows) { + fs::copy("./target/debug/pre-commit.exe", result_path)?; + } else { + fs::copy("./target/debug/pre-commit", result_path)?; + } + } else { + Err(IoError::new(ErrorKind::AlreadyExists, "Git hook already created"))?; + } + Ok(()) +} + +pub fn run_clippy() -> Result<()> { + match Command::new("rustup") + .args(&["run", TOOLCHAIN, "--", "cargo", "clippy", "--version"]) + .stderr(Stdio::null()) + .stdout(Stdio::null()) + .status() + { + Ok(status) if status.success() => (), + _ => install_clippy()?, + }; + + let allowed_lints = [ + "clippy::collapsible_if", + "clippy::map_clone", // FIXME: remove when Iterator::copied stabilizes (1.36.0) + "clippy::needless_pass_by_value", + "clippy::nonminimal_bool", + "clippy::redundant_pattern_matching", + ]; + run( + &format!( + "rustup run {} -- cargo clippy --all-features --all-targets -- -A {}", + TOOLCHAIN, + allowed_lints.join(" -A ") + ), + ".", + )?; + Ok(()) +} + +pub fn install_clippy() -> Result<()> { + run(&format!("rustup install {}", TOOLCHAIN), ".")?; + run(&format!("rustup component add clippy --toolchain {}", TOOLCHAIN), ".") +} + +pub fn run_fuzzer() -> Result<()> { + match Command::new("cargo") + .args(&["fuzz", "--help"]) + .stderr(Stdio::null()) + .stdout(Stdio::null()) + .status() + { + Ok(status) if status.success() => (), + _ => run("cargo install cargo-fuzz", ".")?, + }; + + run("rustup run nightly -- cargo fuzz run parser", "./crates/ra_syntax") +} + +pub fn gen_tests(mode: Mode) -> Result<()> { + let tests = tests_from_dir(&project_root().join(Path::new(GRAMMAR_DIR)))?; + fn install_tests(tests: &HashMap, into: &str, mode: Mode) -> Result<()> { + let tests_dir = project_root().join(into); + if !tests_dir.is_dir() { + fs::create_dir_all(&tests_dir)?; + } + // ok is never actually read, but it needs to be specified to create a Test in existing_tests + let existing = existing_tests(&tests_dir, true)?; + for t in existing.keys().filter(|&t| !tests.contains_key(t)) { + panic!("Test is deleted: {}", t); + } + + let mut new_idx = existing.len() + 1; + for (name, test) in tests { + let path = match existing.get(name) { + Some((path, _test)) => path.clone(), + None => { + let file_name = format!("{:04}_{}.rs", new_idx, name); + new_idx += 1; + tests_dir.join(file_name) + } + }; + update(&path, &test.text, mode)?; + } + Ok(()) + } + install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?; + install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode) +} + +fn do_run(cmdline: &str, dir: &str, mut f: F) -> Result +where + F: FnMut(&mut Command), +{ + eprintln!("\nwill run: {}", cmdline); + let proj_dir = project_root().join(dir); + let mut args = cmdline.split_whitespace(); + let exec = args.next().unwrap(); + let mut cmd = Command::new(exec); + f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit())); + let output = cmd.output()?; + if !output.status.success() { + Err(format!("`{}` exited with {}", cmdline, output.status))?; + } + Ok(output) +} + +#[derive(Default, Debug)] +struct Tests { + pub ok: HashMap, + pub err: HashMap, +} + +fn tests_from_dir(dir: &Path) -> Result { + let mut res = Tests::default(); + for entry in ::walkdir::WalkDir::new(dir) { + let entry = entry.unwrap(); + if !entry.file_type().is_file() { + continue; + } + if entry.path().extension().unwrap_or_default() != "rs" { + continue; + } + process_file(&mut res, entry.path())?; + } + let grammar_rs = dir.parent().unwrap().join("grammar.rs"); + process_file(&mut res, &grammar_rs)?; + return Ok(res); + fn process_file(res: &mut Tests, path: &Path) -> Result<()> { + let text = fs::read_to_string(path)?; + + for (_, test) in collect_tests(&text) { + if test.ok { + if let Some(old_test) = res.ok.insert(test.name.clone(), test) { + Err(format!("Duplicate test: {}", old_test.name))? + } + } else { + if let Some(old_test) = res.err.insert(test.name.clone(), test) { + Err(format!("Duplicate test: {}", old_test.name))? + } + } + } + Ok(()) + } +} + +fn existing_tests(dir: &Path, ok: bool) -> Result> { + let mut res = HashMap::new(); + for file in fs::read_dir(dir)? { + let file = file?; + let path = file.path(); + if path.extension().unwrap_or_default() != "rs" { + continue; + } + let name = { + let file_name = path.file_name().unwrap().to_str().unwrap(); + file_name[5..file_name.len() - 3].to_string() + }; + let text = fs::read_to_string(&path)?; + let test = Test { name: name.clone(), text, ok }; + if let Some(old) = res.insert(name, (path, test)) { + println!("Duplicate test: {:?}", old); + } + } + Ok(res) +} + +/// A helper to update file on disk if it has changed. +/// With verify = false, +pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> { + match fs::read_to_string(path) { + Ok(ref old_contents) if old_contents == contents => { + return Ok(()); + } + _ => (), + } + if mode == Verify { + Err(format!("`{}` is not up-to-date", path.display()))?; + } + eprintln!("updating {}", path.display()); + fs::write(path, contents)?; + Ok(()) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 000000000..623058436 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,218 @@ +//! FIXME: write short doc here + +mod help; + +use core::fmt::Write; +use core::str; +use pico_args::Arguments; +use std::{env, path::PathBuf}; +use xtask::{ + gen_tests, generate_boilerplate, install_format_hook, run, run_clippy, run_fuzzer, run_rustfmt, + Cmd, Overwrite, Result, +}; + +struct InstallOpt { + client: Option, + server: Option, +} + +enum ClientOpt { + VsCode, +} + +struct ServerOpt { + jemalloc: bool, +} + +fn main() -> Result<()> { + let subcommand = match std::env::args_os().nth(1) { + None => { + eprintln!("{}", help::GLOBAL_HELP); + return Ok(()); + } + Some(s) => s, + }; + let mut matches = Arguments::from_vec(std::env::args_os().skip(2).collect()); + let subcommand = &*subcommand.to_string_lossy(); + match subcommand { + "install" => { + if matches.contains(["-h", "--help"]) { + eprintln!("{}", help::INSTALL_HELP); + return Ok(()); + } + let server = matches.contains("--server"); + let client_code = matches.contains("--client-code"); + if server && client_code { + eprintln!("{}", help::INSTALL_RA_CONFLICT); + return Ok(()); + } + let jemalloc = matches.contains("--jemalloc"); + matches.finish().or_else(handle_extra_flags)?; + let opts = InstallOpt { + client: if server { None } else { Some(ClientOpt::VsCode) }, + server: if client_code { None } else { Some(ServerOpt { jemalloc: jemalloc }) }, + }; + install(opts)? + } + "gen-tests" => { + if matches.contains(["-h", "--help"]) { + help::print_no_param_subcommand_help(&subcommand); + return Ok(()); + } + gen_tests(Overwrite)? + } + "codegen" => { + if matches.contains(["-h", "--help"]) { + help::print_no_param_subcommand_help(&subcommand); + return Ok(()); + } + generate_boilerplate(Overwrite)? + } + "format" => { + if matches.contains(["-h", "--help"]) { + help::print_no_param_subcommand_help(&subcommand); + return Ok(()); + } + run_rustfmt(Overwrite)? + } + "format-hook" => { + if matches.contains(["-h", "--help"]) { + help::print_no_param_subcommand_help(&subcommand); + return Ok(()); + } + install_format_hook()? + } + "lint" => { + if matches.contains(["-h", "--help"]) { + help::print_no_param_subcommand_help(&subcommand); + return Ok(()); + } + run_clippy()? + } + "fuzz-tests" => { + if matches.contains(["-h", "--help"]) { + help::print_no_param_subcommand_help(&subcommand); + return Ok(()); + } + run_fuzzer()? + } + _ => eprintln!("{}", help::GLOBAL_HELP), + } + Ok(()) +} + +fn handle_extra_flags(e: pico_args::Error) -> Result<()> { + if let pico_args::Error::UnusedArgsLeft(flags) = e { + let mut invalid_flags = String::new(); + for flag in flags { + write!(&mut invalid_flags, "{}, ", flag)?; + } + let (invalid_flags, _) = invalid_flags.split_at(invalid_flags.len() - 2); + Err(format!("Invalid flags: {}", invalid_flags).into()) + } else { + Err(e.to_string().into()) + } +} + +fn install(opts: InstallOpt) -> Result<()> { + if cfg!(target_os = "macos") { + fix_path_for_mac()? + } + if let Some(server) = opts.server { + install_server(server)?; + } + if let Some(client) = opts.client { + install_client(client)?; + } + Ok(()) +} + +fn fix_path_for_mac() -> Result<()> { + let mut vscode_path: Vec = { + const COMMON_APP_PATH: &str = + r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin"; + const ROOT_DIR: &str = ""; + let home_dir = match env::var("HOME") { + Ok(home) => home, + Err(e) => Err(format!("Failed getting HOME from environment with error: {}.", e))?, + }; + + [ROOT_DIR, &home_dir] + .iter() + .map(|dir| String::from(*dir) + COMMON_APP_PATH) + .map(PathBuf::from) + .filter(|path| path.exists()) + .collect() + }; + + if !vscode_path.is_empty() { + let vars = match env::var_os("PATH") { + Some(path) => path, + None => Err("Could not get PATH variable from env.")?, + }; + + let mut paths = env::split_paths(&vars).collect::>(); + paths.append(&mut vscode_path); + let new_paths = env::join_paths(paths)?; + env::set_var("PATH", &new_paths); + } + + Ok(()) +} + +fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { + Cmd { unix: r"npm ci", windows: r"cmd.exe /c npm.cmd ci", work_dir: "./editors/code" }.run()?; + Cmd { + unix: r"npm run package", + windows: r"cmd.exe /c npm.cmd run package", + work_dir: "./editors/code", + } + .run()?; + + let code_binary = ["code", "code-insiders", "codium"].iter().find(|bin| { + Cmd { + unix: &format!("{} --version", bin), + windows: &format!("cmd.exe /c {}.cmd --version", bin), + work_dir: "./editors/code", + } + .run() + .is_ok() + }); + + let code_binary = match code_binary { + Some(it) => it, + None => Err("Can't execute `code --version`. Perhaps it is not in $PATH?")?, + }; + + Cmd { + unix: &format!(r"{} --install-extension ./ra-lsp-0.0.1.vsix --force", code_binary), + windows: &format!( + r"cmd.exe /c {}.cmd --install-extension ./ra-lsp-0.0.1.vsix --force", + code_binary + ), + work_dir: "./editors/code", + } + .run()?; + + let output = Cmd { + unix: &format!(r"{} --list-extensions", code_binary), + windows: &format!(r"cmd.exe /c {}.cmd --list-extensions", code_binary), + work_dir: ".", + } + .run_with_output()?; + + if !str::from_utf8(&output.stdout)?.contains("ra-lsp") { + Err("Could not install the Visual Studio Code extension. \ + Please make sure you have at least NodeJS 10.x installed and try again.")?; + } + + Ok(()) +} + +fn install_server(opts: ServerOpt) -> Result<()> { + if opts.jemalloc { + run("cargo install --path crates/ra_lsp_server --locked --force --features jemalloc", ".") + } else { + run("cargo install --path crates/ra_lsp_server --locked --force", ".") + } +} diff --git a/xtask/tests/cli.rs b/xtask/tests/cli.rs new file mode 100644 index 000000000..609fd4d8b --- /dev/null +++ b/xtask/tests/cli.rs @@ -0,0 +1,45 @@ +use ra_tools::{gen_tests, generate_boilerplate, project_root, run_rustfmt, Verify}; +use walkdir::WalkDir; + +#[test] +fn generated_grammar_is_fresh() { + if let Err(error) = generate_boilerplate(Verify) { + panic!("{}. Please update it by running `cargo gen-syntax`", error); + } +} + +#[test] +fn generated_tests_are_fresh() { + if let Err(error) = gen_tests(Verify) { + panic!("{}. Please update tests by running `cargo gen-tests`", error); + } +} + +#[test] +fn check_code_formatting() { + if let Err(error) = run_rustfmt(Verify) { + panic!("{}. Please format the code by running `cargo format`", error); + } +} + +#[test] +fn no_todo() { + WalkDir::new(project_root().join("crates")).into_iter().for_each(|e| { + let e = e.unwrap(); + if e.path().extension().map(|it| it != "rs").unwrap_or(true) { + return; + } + if e.path().ends_with("tests/cli.rs") { + return; + } + let text = std::fs::read_to_string(e.path()).unwrap(); + if text.contains("TODO") || text.contains("TOOD") { + panic!( + "\nTODO markers should not be committed to the master branch,\n\ + use FIXME instead\n\ + {}\n", + e.path().display(), + ) + } + }) +} diff --git a/xtask/tests/docs.rs b/xtask/tests/docs.rs new file mode 100644 index 000000000..ea3330175 --- /dev/null +++ b/xtask/tests/docs.rs @@ -0,0 +1,63 @@ +use std::fs; +use std::io::prelude::*; +use std::io::BufReader; +use std::path::Path; + +use walkdir::{DirEntry, WalkDir}; + +use ra_tools::project_root; + +fn is_exclude_dir(p: &Path) -> bool { + let exclude_dirs = ["tests", "test_data"]; + let mut cur_path = p; + while let Some(path) = cur_path.parent() { + if exclude_dirs.iter().any(|dir| path.ends_with(dir)) { + return true; + } + cur_path = path; + } + + false +} + +fn is_exclude_file(d: &DirEntry) -> bool { + let file_names = ["tests.rs"]; + + d.file_name().to_str().map(|f_n| file_names.iter().any(|name| *name == f_n)).unwrap_or(false) +} + +fn is_hidden(entry: &DirEntry) -> bool { + entry.file_name().to_str().map(|s| s.starts_with(".")).unwrap_or(false) +} + +#[test] +fn no_docs_comments() { + let crates = project_root().join("crates"); + let iter = WalkDir::new(crates); + for f in iter.into_iter().filter_entry(|e| !is_hidden(e)) { + let f = f.unwrap(); + if f.file_type().is_dir() { + continue; + } + if f.path().extension().map(|it| it != "rs").unwrap_or(false) { + continue; + } + if is_exclude_dir(f.path()) { + continue; + } + if is_exclude_file(&f) { + continue; + } + let mut reader = BufReader::new(fs::File::open(f.path()).unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if !line.starts_with("//!") { + panic!( + "\nMissing docs strings\n\ + module: {}\n\ + Need add doc for module\n", + f.path().display() + ) + } + } +} diff --git a/xtask/tests/main.rs b/xtask/tests/main.rs new file mode 100644 index 000000000..56d1318d6 --- /dev/null +++ b/xtask/tests/main.rs @@ -0,0 +1,2 @@ +mod cli; +mod docs; -- cgit v1.2.3