Skip to content

Commit

Permalink
Add clippy & fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Dec 6, 2024
1 parent ca292c6 commit b321383
Show file tree
Hide file tree
Showing 22 changed files with 241 additions and 72 deletions.
8 changes: 8 additions & 0 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
edition = "2018"
format_strings = true
group_imports = "StdExternalCrate"
hex_literal_case = "Lower"
imports_granularity = "Crate"
reorder_impl_items = true
use_field_init_shorthand = true
wrap_comments = true
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"editor.codeActionsOnSave": {
"source.fixAll": "explicit"
},
"rust-analyzer.check.command": "clippy",
"[xml]": {
"editor.defaultFormatter": null
},
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 15 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,21 @@ Create custom elements, bind data, route switching, and quickly develop WebApps

## Project Packages

| Package | Description |
| ---------------------------------------------- | ---------------------------------------------------------------- |
| [packages/gem](packages/gem) | Gem core |
| [packages/gem-devtools](packages/gem-devtools) | Browser debugging tool for Gem |
| [packages/gem-analyzer](packages/gem-analyzer) | Gem element analyzer, which can automatically generate documents |
| [packages/gem-book](packages/gem-book) | Documentation site builder created using Gem |
| [packages/duoyun-ui](packages/duoyun-ui) | UI library created using Gem |
| [packages/gem-port](packages/gem-port) | Export Gem elements as React/Vue/Svelte components |
| [packages/gem-examples](packages/gem-examples) | Gem and DuoyunUI examples |

[Rodmap](https://mm.tt/app/map/3412316197?t=TGs84FRcwQ).
| Package | Description |
| ----------------------------------------------- | ---------------------------------------------------------------- |
| [gem](packages/gem) | Gem core |
| [gem-devtools](packages/gem-devtools) | Browser debugging tool for Gem |
| [gem-analyzer](packages/gem-analyzer) | Gem element analyzer, which can automatically generate documents |
| [gem-book](packages/gem-book) | Documentation site builder created using Gem |
| [duoyun-ui](packages/duoyun-ui) | UI library created using Gem |
| [gem-port](packages/gem-port) | Export Gem elements as React/Vue/Svelte components |
| [gem-examples](packages/gem-examples) | Gem and DuoyunUI examples |
| [language-service](packages/language-service) | language service for Gem |
| [vscode-gem-plugin](packages/vscode-gem-plugin) | VSCode extension |
| [swc-plugin-gem](crates/swc-plugin-gem) | Building plugin for [SWC](https://swc.rs/) |
| [zed-plugin-gem](crates/swc-plugin-gem) | [Zed](https://zed.dev/) extension |

[Roadmap](https://mm.tt/app/map/3412316197?t=TGs84FRcwQ).

## Contribution

Expand Down
22 changes: 13 additions & 9 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,19 @@

## 项目结构

| 目录 | 描述 |
| ---------------------------------------------- | --------------------------------------- |
| [packages/gem](packages/gem) | Gem 核心 |
| [packages/gem-devtools](packages/gem-devtools) | Gem 的浏览器调试工具 |
| [packages/gem-analyzer](packages/gem-analyzer) | Gem 元素分析器,能自动生成文档 |
| [packages/gem-book](packages/gem-book) | 使用 Gem 创建的文档站生成器 |
| [packages/duoyun-ui](packages/duoyun-ui) | 使用 Gem 创建的 UI 库 |
| [packages/gem-port](packages/gem-port) | 将 Gem 元素导出为 React/Vue/Svelte 组件 |
| [packages/gem-examples](packages/gem-examples) | 一些 Gem 和 DuoyunUI 示例 |
| 目录 | 描述 |
| ----------------------------------------------- | --------------------------------------- |
| [gem](packages/gem) | Gem 核心 |
| [gem-devtools](packages/gem-devtools) | Gem 的浏览器调试工具 |
| [gem-analyzer](packages/gem-analyzer) | Gem 元素分析器,能自动生成文档 |
| [gem-book](packages/gem-book) | 使用 Gem 创建的文档站生成器 |
| [duoyun-ui](packages/duoyun-ui) | 使用 Gem 创建的 UI 库 |
| [gem-port](packages/gem-port) | 将 Gem 元素导出为 React/Vue/Svelte 组件 |
| [gem-examples](packages/gem-examples) | 一些 Gem 和 DuoyunUI 示例 |
| [language-service](packages/language-service) | Gem 的语言服务 |
| [vscode-gem-plugin](packages/vscode-gem-plugin) | VSCode 扩展 |
| [swc-plugin-gem](crates/swc-plugin-gem) | [SWC](https://swc.rs/) 构建插件 |
| [zed-plugin-gem](crates/swc-plugin-gem) | [Zed](https://zed.dev/) 扩展 |

[路线图](https://mm.tt/app/map/3412316197?t=TGs84FRcwQ)

Expand Down
26 changes: 26 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
cognitive-complexity-threshold = 50
disallowed-names = [
"bool",
"char",
"str",
"f32",
"f64",
"i8",
"i16",
"i32",
"i64",
"u8",
"u16",
"u32",
"u64",
"isize",
"usize",
]
ignore-interior-mutability = [
"bytes::Bytes",
"swc_atoms::Atom",
"swc_atoms::JsWord",
"swc_ecma_ast::Id",
]
msrv = "1.70"
type-complexity-threshold = 25000
2 changes: 1 addition & 1 deletion crates/swc-plugin-gem/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
*.wasm
.swcrc
.swc
*.d.ts
auto-import.d.ts
2 changes: 1 addition & 1 deletion crates/swc-plugin-gem/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"experimental": {
"plugins": [
[
"swc_plugin_gem",
"swc-plugin-gem",
{
"autoImport": {
"extends": "gem",
Expand Down
7 changes: 6 additions & 1 deletion crates/swc-plugin-gem/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
"main": "swc_plugin_gem.wasm",
"files": [],
"scripts": {
"prepublishOnly": "cross-env CARGO_TARGET_DIR=target cargo build-wasi --release && cp target/wasm32-wasip1/release/swc_plugin_gem.wasm .",
"build:dev": "cross-env CARGO_TARGET_DIR=target cargo build-wasi",
"cp:dev": "cp target/wasm32-wasip1/debug/swc_plugin_gem.wasm .",
"build": "npm run build:dev -- --release",
"cp": "cp target/wasm32-wasip1/release/swc_plugin_gem.wasm .",
"prepublishOnly": "pnpm run build && npm run cp",
"dev": "cargo watch -s \"npm run build:dev && npm run cp:dev\"",
"test": "cross-env RUST_LOG=info cargo watch -x test"
},
"preferUnplugged": true,
Expand Down
32 changes: 21 additions & 11 deletions crates/swc-plugin-gem/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
use serde::Deserialize;
use swc_common::pass::Optional;
use swc_core::ecma::visit::VisitMutWith;
use swc_core::plugin::metadata::TransformPluginMetadataContextKind;
use swc_core::plugin::{plugin_transform, proxies::TransformPluginProgramMetadata};
use swc_core::{
ecma::visit::VisitMutWith,
plugin::{
metadata::TransformPluginMetadataContextKind, plugin_transform,
proxies::TransformPluginProgramMetadata,
},
};
use swc_ecma_ast::Program;
pub use visitors::import::{import_transform, AutoImport};
pub use visitors::memo::memo_transform;
pub use visitors::minify::minify_transform;
pub use visitors::path::path_transform;
pub use visitors::preload::preload_transform;
pub use visitors::{
hmr::hmr_transform,
import::{import_transform, AutoImport},
memo::memo_transform,
minify::minify_transform,
path::path_transform,
preload::preload_transform,
};

mod visitors;

Expand All @@ -23,7 +30,7 @@ struct PluginConfig {
pub resolve_path: bool,
///depend on URL loader, top await
pub preload: bool,
/// un-implement
/// Under development, need add `@mantou/gem/helper/hmr` to entry
pub hmr: bool,
/// un-implement
pub lazy_view: bool,
Expand All @@ -47,10 +54,9 @@ pub fn process_transform(mut program: Program, data: TransformPluginProgramMetad
},
Optional {
enabled: match config.auto_import {
AutoImport::Gem(enabeld) => enabeld,
AutoImport::Gem(enabled) => enabled,
AutoImport::Custom(_) => true,
},
// 执行在每个文件
visitor: import_transform(config.auto_import, config.auto_import_dts),
},
Optional {
Expand All @@ -65,6 +71,10 @@ pub fn process_transform(mut program: Program, data: TransformPluginProgramMetad
enabled: config.preload,
visitor: preload_transform(),
},
Optional {
enabled: config.hmr,
visitor: hmr_transform(),
},
));

program
Expand Down
31 changes: 31 additions & 0 deletions crates/swc-plugin-gem/src/visitors/hmr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//! https://rspack.dev/api/runtime-api/hmr
//! 为 HMR 添加一些特殊的转换
use swc_core::{
ecma::visit::{noop_visit_mut_type, VisitMut, VisitMutWith},
quote,
};
use swc_ecma_ast::ModuleItem;

#[derive(Default)]
struct TransformVisitor {}

impl VisitMut for TransformVisitor {
noop_visit_mut_type!();

fn visit_mut_module_items(&mut self, node: &mut Vec<ModuleItem>) {
node.visit_mut_children_with(self);

node.push(quote!(
"
if (module.hot) {
module.hot.accept();
}
" as ModuleItem,
));
}
}

pub fn hmr_transform() -> impl VisitMut {
TransformVisitor::default()
}
26 changes: 13 additions & 13 deletions crates/swc-plugin-gem/src/visitors/import.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::{collections::HashMap, env, fs};

use indexmap::{IndexMap, IndexSet};
use node_resolve::Resolver;
use once_cell::sync::{Lazy, OnceCell};
use regex::Regex;
use serde::Deserialize;
use std::{collections::HashMap, env, fs};
use swc_common::{SyntaxContext, DUMMY_SP};
use swc_core::{
atoms::Atom,
Expand All @@ -15,13 +16,13 @@ use swc_ecma_ast::{
VarDeclarator,
};

static CREATED_DTS: OnceCell<bool> = OnceCell::new();

static GLOBAL_CONFIG: OnceCell<AutoImportConfig> = OnceCell::new();

static CUSTOM_ELEMENT_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?s)<(?<tag>\w+(-\w+)+)(\s|>)").unwrap());

// FIXME: 每个文件作为 loader 重新执行整个程序,这个全局缓存并没有生效
static CREATED_DTS: OnceCell<bool> = OnceCell::new();
static GLOBAL_CONFIG: OnceCell<AutoImportConfig> = OnceCell::new();

#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
enum MemberOrMemberAs {
Expand Down Expand Up @@ -53,7 +54,7 @@ impl TransformVisitor {
self.defined_members.insert(ident.to_id());
}

fn visit_mut_class(&mut self, node: &Box<Class>) {
fn visit_mut_class(&mut self, node: &Class) {
if let Some(expr) = &node.super_class {
if let Some(ident) = expr.as_ident() {
self.inset_used_member(ident);
Expand Down Expand Up @@ -146,7 +147,7 @@ impl VisitMut for TransformVisitor {
node.visit_mut_children_with(self);

if let Some(ident) = &node.name.as_ident() {
self.inset_defined_member(&ident);
self.inset_defined_member(ident);
}
}

Expand All @@ -163,9 +164,7 @@ impl VisitMut for TransformVisitor {
if !self.defined_members.contains(id) {
let pkg = GLOBAL_CONFIG.get().unwrap().member_map.get(id.0.as_str());
if let Some(pkg) = pkg {
let set = available_import
.entry(pkg.into())
.or_insert(Default::default());
let set = available_import.entry(pkg.into()).or_default();
set.insert(&id.0, (&id.0, &id.1));
}
}
Expand All @@ -175,15 +174,16 @@ impl VisitMut for TransformVisitor {
let mut specifiers: Vec<ImportSpecifier> = vec![];
for (member, (_member_as, ctx)) in set {
specifiers.push(ImportSpecifier::Named(ImportNamedSpecifier {
local: Ident::new(member.clone(), DUMMY_SP, ctx.clone()),
local: Ident::new(member.clone(), DUMMY_SP, *ctx),
span: DUMMY_SP,
imported: None,
is_type_only: false,
}));
}
out.push(ImportDecl {
specifiers,
// 也许可以支持替换:'@mantou/gem/{:pascal:}' + ColorPicker -> '@mantou/gem/ColorPicker'
// 也许可以支持替换:'@mantou/gem/{:pascal:}' + ColorPicker ->
// '@mantou/gem/ColorPicker'
src: Box::new(Str::from(pkg)),
span: DUMMY_SP,
type_only: false,
Expand Down Expand Up @@ -261,7 +261,7 @@ fn merge_content(
return merge_content(get_config_content(AutoImport::Gem(true)), root);
} else {
let resolver = Resolver::new()
.with_extensions(&["json"])
.with_extensions(["json"])
.with_basedir(env::current_dir().expect("get current dir error"));
if let Ok(full_path) = resolver.resolve(&extends) {
if let Ok(json_str) = fs::read_to_string(full_path) {
Expand Down
1 change: 1 addition & 0 deletions crates/swc-plugin-gem/src/visitors/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod hmr;
pub mod import;
pub mod memo;
pub mod minify;
Expand Down
26 changes: 12 additions & 14 deletions crates/swc-plugin-gem/src/visitors/path.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::{env, path::PathBuf};
use std::{env, path::Path};

use node_resolve::Resolver;
use pathdiff::diff_paths;
use swc_core::ecma::visit::{noop_visit_mut_type, VisitMut};
use swc_ecma_ast::{CallExpr, Callee, ExprOrSpread, ImportDecl, Lit, Str};
use typed_path::{Utf8Path, Utf8UnixEncoding, Utf8WindowsEncoding};

fn converting_to_unix_path(path_buf: &PathBuf) -> String {
let windows_path = Utf8Path::<Utf8WindowsEncoding>::new(path_buf.to_str().unwrap());
fn converting_to_unix_path(path: &Path) -> String {
let windows_path = Utf8Path::<Utf8WindowsEncoding>::new(path.to_str().unwrap());
windows_path.with_encoding::<Utf8UnixEncoding>().to_string()
}

Expand All @@ -20,14 +20,15 @@ impl TransformVisitor {
fn resolve_path(&self, origin: &str) -> Str {
if let Some(filename) = &self.filename {
let cwd = env::current_dir().expect("get current dir error");
let dir = cwd.join(filename).parent().unwrap().to_path_buf();
let full_filename = cwd.join(filename);
let dir = full_filename.parent().unwrap();
let resolver = Resolver::new()
.with_extensions(&["ts", "js", ".mjs"])
.with_basedir(dir.clone());
if let Ok(full_path) = resolver.resolve(origin) {
.with_extensions(["ts", "js", ".mjs"])
.with_basedir(dir.to_path_buf());
if let Ok(ref full_path) = resolver.resolve(origin) {
if let Some(relative_path) = diff_paths(
&converting_to_unix_path(&full_path),
&converting_to_unix_path(&dir),
converting_to_unix_path(full_path),
converting_to_unix_path(dir),
) {
if let Some(relative_path) = relative_path.to_str() {
let relative_path = relative_path.replace(".ts", ".js");
Expand All @@ -54,7 +55,7 @@ impl VisitMut for TransformVisitor {
// 只处理 string 的动态导入
fn visit_mut_call_expr(&mut self, node: &mut CallExpr) {
if let Callee::Import(_) = node.callee {
if let Some(Some(Lit::Str(source))) = node.args.get(0).map(|e| e.expr.as_lit()) {
if let Some(Some(Lit::Str(source))) = node.args.first().map(|e| e.expr.as_lit()) {
node.args = vec![ExprOrSpread {
spread: None,
expr: self.resolve_path(source.value.as_str()).into(),
Expand All @@ -65,8 +66,5 @@ impl VisitMut for TransformVisitor {
}

pub fn path_transform(filename: Option<String>) -> impl VisitMut {
TransformVisitor {
filename,
..Default::default()
}
TransformVisitor { filename }
}
2 changes: 1 addition & 1 deletion crates/swc-plugin-gem/src/visitors/preload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use swc_core::{
use swc_ecma_ast::{Ident, ImportDecl, ModuleItem, Str};

static IMG_REG: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)\.(gif|jpe?g|tiff?|png|webp|bmp)$").unwrap());
Lazy::new(|| Regex::new(r"(?i)\.(svg|gif|jpe?g|tiff?|a?png|webp|avif|bmp)$").unwrap());

enum AwaitItem {
Img(Ident),
Expand Down
Loading

0 comments on commit b321383

Please sign in to comment.