Skip to content

feat(ast-grep): Add experimental ast-grep Wasm plugin #435

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions packages/swc-ast-grep/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
transform/
tests/
25 changes: 25 additions & 0 deletions packages/swc-ast-grep/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]

description = "SWC Plugin for @swc/sdk"


authors = { workspace = true }
edition = { workspace = true }
homepage = { workspace = true }
license = { workspace = true }
name = "swc_plugin_ast_grep"
publish = false
repository = { workspace = true }
rust-version = { workspace = true }
version = "0.1.0"


[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
serde_json = { workspace = true }
swc_core = { workspace = true, features = ["ecma_plugin_transform"] }


swc_ast_grep = { path = "./transform" }
22 changes: 22 additions & 0 deletions packages/swc-ast-grep/README.tmpl.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# @swc/plugin-swc-ast-grep

## Usage

.swcrc:

```json
{
"jsc": {
"experimental": {
"plugins": [
"@swc/plugin-swc-ast-grep",
{
"rules": "rules.yaml"
}
]
}
}
}
```

${CHANGELOG}
25 changes: 25 additions & 0 deletions packages/swc-ast-grep/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "@swc/plugin-ast-grep",
"version": "1.0.0",
"description": "SWC plugin for ast-grep",
"main": "swc_plugin_ast_grep.wasm",
"scripts": {
"prepack": "cargo build --release -p swc_plugin_ast_grep --target wasm32-wasip1 && cp ../../target/wasm32-wasip1/release/swc_plugin_ast_grep.wasm ."
},
"homepage": "https://swc.rs",
"repository": {
"type": "git",
"url": "git+https://github.com/swc-project/plugins.git",
"directory": "packages/swc-ast-grep"
},
"bugs": {
"url": "https://github.com/swc-project/plugins/issues"
},
"author": "강동윤 <kdy1997.dev@gmail.com>",
"keywords": [],
"license": "Apache-2.0",
"preferUnplugged": true,
"dependencies": {
"@swc/counter": "^0.1.3"
}
}
2 changes: 2 additions & 0 deletions packages/swc-ast-grep/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#[plugin_transform]
fn swc_ast_grep_plugin(mut program: Program, data: TransformPluginProgramMetadata) -> Program {}
32 changes: 32 additions & 0 deletions packages/swc-ast-grep/transform/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[package]

description = "SWC plugin to invoke ast-grep"


authors = { workspace = true }
edition = { workspace = true }
homepage = { workspace = true }
license = { workspace = true }
name = "swc_ast_grep"
publish = false
repository = { workspace = true }
rust-version = { workspace = true }
version = "0.1.0"


[dependencies]
default-from-serde = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] }
swc_atoms = { workspace = true }
swc_common = { workspace = true }
swc_ecma_ast = { workspace = true }
swc_ecma_codegen = { workspace = true }
swc_ecma_utils = { workspace = true }
swc_ecma_visit = { workspace = true }

[dev-dependencies]
swc_ecma_parser = { workspace = true }
swc_ecma_transforms_base = { workspace = true }
swc_ecma_transforms_testing = { workspace = true }
testing = { workspace = true }
42 changes: 42 additions & 0 deletions packages/swc-ast-grep/transform/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use default_from_serde::SerdeDefault;
use serde::Deserialize;
use swc_atoms::Atom;

#[derive(Debug, Clone, Deserialize, SerdeDefault)]
pub struct Config {
#[serde(default)]
pub flag: FlagConfig,

/// Drop imports from the following modules.
#[serde(default = "default_remove_imports_from")]
pub remove_imports_from: Vec<Atom>,
}

#[derive(Debug, Clone, Deserialize, SerdeDefault)]
pub struct FlagConfig {
/// If true,
///
/// - the variable name must be an identifier.
#[serde(default)]
pub strict: bool,

#[serde(default = "default_flag_import_source")]
pub import_sources: Vec<ImportItem>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ImportItem {
pub module: Atom,
pub name: Atom,
}

fn default_remove_imports_from() -> Vec<Atom> {
vec![Atom::new("@swc/sdk/annotations")]
}

fn default_flag_import_source() -> Vec<ImportItem> {
vec![ImportItem {
module: Atom::new("@swc/sdk/flag"),
name: Atom::new("flag"),
}]
}
158 changes: 158 additions & 0 deletions packages/swc-ast-grep/transform/src/flag.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
use swc_common::{comments::Comments, errors::HANDLER, Spanned};
use swc_ecma_ast::{
Expr, KeyValueProp, ObjectLit, Pat, Prop, PropName, PropOrSpread, VarDeclarator,
};
use swc_ecma_utils::ExprFactory;

use crate::SwcSdkTransform;

impl<C> SwcSdkTransform<C>
where
C: Comments,
{
///
/// ## Cases
///
/// ### Empty arugments
///
/// ```js
///
/// import { flag } from "@swc/sdk/flag";
///
/// const foo = flag();
/// ```
///
/// becomes
///
/// ```js
/// import { flag } from "@swc/sdk/flag";
///
/// const foo = flag({
/// key: "foo",
/// });
/// ```
///
/// ### With arguments
///
/// ```js
/// import { flag } from "@swc/sdk/flag";
///
/// const foo = flag({
/// decide: () => false,
/// });
/// ```
///
/// becomes
///
/// ```js
/// import { flag } from "@swc/sdk/flag";
///
/// const foo = flag({
/// key: "foo",
/// decide: () => false,
/// });
/// ```
///
/// ### With custom adapter
///
///
/// ```js
/// import { flag } from "@swc/sdk/flag";
///
/// const foo = flag(someAdapter({
/// decide: () => false,
/// });
/// ```
///
/// becomes
///
/// ```js
/// import { flag } from "@swc/sdk/flag";
///
/// const foo = flag(someAdapter({
/// key: "foo",
/// decide: () => false,
/// }));
/// ```
pub(super) fn transform_flag(&mut self, v: &mut VarDeclarator) -> Option<!> {
let init = v.init.as_deref_mut()?;
let call_expr = init.as_mut_call()?;

let callee = call_expr.callee.as_mut_expr()?;

let import_of_flag_callee = self
.imports
.is_in_import_items(callee, &self.config.flag.import_sources)?;

let name = match &v.name {
Pat::Ident(i) => i.clone(),
_ => {
if self.config.flag.strict {
HANDLER.with(|handler| {
handler
.struct_span_err(
v.name.span(),
"The variable name for the `flag()` calls must be an identifier",
)
.span_note(import_of_flag_callee, "flag() is imported here")
.emit();
});
}
return None;
}
};

let prop = PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident("key".into()),
value: name.sym.clone().into(),
})));

if call_expr.args.is_empty() {
call_expr.args.push(
ObjectLit {
props: vec![prop],
..Default::default()
}
.as_arg(),
);
} else if let Some(obj) = find_object(&mut call_expr.args[0].expr) {
if obj
.props
.iter()
.filter_map(|p| p.as_prop())
.any(|p| match &**p {
Prop::KeyValue(KeyValueProp { key, .. }) => {
matches!(key, PropName::Ident(i) if i.sym == "key")
}
_ => false,
})
{
return None;
}

obj.props.push(prop);
}

None
}
}

fn find_object(arg: &mut Expr) -> Option<&mut ObjectLit> {
match arg {
Expr::Object(obj) => Some(obj),
Expr::Call(call) => {
if call.args.is_empty() {
call.args.push(
ObjectLit {
..Default::default()
}
.as_arg(),
);
}

let arg = call.args.get_mut(0)?;
find_object(&mut arg.expr)
}
_ => None,
}
}
Loading
Loading