Skip to content
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

feat(xtask): impl as_ast_kind method for each variant #5491

Merged
merged 1 commit into from
Sep 5, 2024

Conversation

IWANABETHATGUY
Copy link
Contributor

No description provided.

@github-actions github-actions bot added A-ast Area - AST A-ast-tools Area - AST tools labels Sep 5, 2024
@Boshen
Copy link
Member

Boshen commented Sep 5, 2024

What's the usage?

Copy link

graphite-app bot commented Sep 5, 2024

Your org has enabled the Graphite merge queue for merging into main

Add the label “0-merge” to the PR and Graphite will automatically add it to the merge queue when it’s ready to merge. Or use the label “hotfix” to add to the merge queue as a hot fix.

You must have a Graphite account and log in to Graphite in order to use the merge queue. Sign up using this link.

@IWANABETHATGUY
Copy link
Contributor Author

What's the usage?

e.g.

fn is_wanted_node(node: &AstNode, ctx: &LintContext<'_>) -> Option<bool> {
let parent = ctx.nodes().parent_node(node.id())?;
if let AstKind::MethodDefinition(mdef) = parent.kind() {
if matches!(mdef.kind, MethodDefinitionKind::Constructor) {
let parent_2 = ctx.nodes().parent_node(parent.id())?;
let parent_3 = ctx.nodes().parent_node(parent_2.id())?;
if let AstKind::Class(c) = parent_3.kind() {
let super_class = c.super_class.as_ref()?;
return Some(!matches!(super_class, Expression::NullLiteral(_)));
}
}
}
Some(false)
}

could be rewritten as:

    fn is_wanted_node(node: &AstNode, ctx: &LintContext<'_>) -> Option<bool> {
        let parent = ctx.nodes().parent_node(node.id())?;
        if let AstKind::MethodDefinition(mdef) = parent.kind() {
            if matches!(mdef.kind, MethodDefinitionKind::Constructor) {
                let parent_2 = ctx.nodes().parent_node(parent.id())?;
                let parent_3 = ctx.nodes().parent_node(parent_2.id())?;
                let c = parent_3.kind().as_class()?;
                let super_class = c.super_class.as_ref()?;
                return Some(!matches!(super_class, Expression::NullLiteral(_)));
            }
        }

        Some(false)
    }

@IWANABETHATGUY
Copy link
Contributor Author

This could avoid written many nested levels if let #ty pattern match:
if let AstKind::xxx() =

@IWANABETHATGUY
Copy link
Contributor Author

Also, this makes the code more easily combine with Option combinator

@IWANABETHATGUY IWANABETHATGUY marked this pull request as ready for review September 5, 2024 14:40
@Boshen Boshen requested a review from rzvxa September 5, 2024 14:41
Copy link

codspeed-hq bot commented Sep 5, 2024

CodSpeed Performance Report

Merging #5491 will not alter performance

Comparing feat/ast-kind-as-ty-impl (cedf7a4) with main (a96866d)

Summary

✅ 29 untouched benchmarks

@IWANABETHATGUY
Copy link
Contributor Author

feel free to close it if you are not satisfied since it is not written by hand, 😄

@IWANABETHATGUY
Copy link
Contributor Author

It is used in many place in our codebase:
image

Copy link
Collaborator

@rzvxa rzvxa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

I'm not sure if we need to return the inner values with the lifetime of a; But other than this thought everything looks good.

@IWANABETHATGUY
Copy link
Contributor Author

IWANABETHATGUY commented Sep 5, 2024

LGTM!

I'm not sure if we need to return the inner values with the lifetime of a; But other than this thought everything looks good.

Ok, I omit the 'a lifetime

@rzvxa
Copy link
Collaborator

rzvxa commented Sep 5, 2024

LGTM!
I'm not sure if we need to return the inner values with the lifetime of a; But other than this thought everything looks good.

Ok, I omit the 'a lifetime

Thanks, That wasn't really a change request. I just wanted to put my concern out there to see what you guys think about it.

So please feel free to revert it if you think having the lifetime can be helpful(I'm not sure how many of these pattern matchings are looking for an inner value with the lifetime so it might very well be necessary to simplify many of these).

@Boshen Boshen added the 0-merge Merge with Graphite Merge Queue label Sep 5, 2024
@IWANABETHATGUY
Copy link
Contributor Author

LGTM!
I'm not sure if we need to return the inner values with the lifetime of a; But other than this thought everything looks good.

Ok, I omit the 'a lifetime

Thanks, That wasn't really a change request. I just wanted to put my concern out there to see what you guys think about it.

So please feel free to revert it if you think having the lifetime can be helpful(I'm not sure how many of these pattern matchings are looking for an inner value with the lifetime so it might very well be necessary to simplify many of these).

I don't know it either, I think people could add it back if meets some scenario when found it is not convenient to use.

@Boshen
Copy link
Member

Boshen commented Sep 5, 2024

AST codegen is getting too powerful 🦸

Copy link

graphite-app bot commented Sep 5, 2024

Merge activity

  • Sep 5, 12:11 PM EDT: The merge label '0-merge' was detected. This PR will be added to the Graphite merge queue once it meets the requirements.
  • Sep 5, 12:12 PM EDT: Boshen added this pull request to the Graphite merge queue.
  • Sep 5, 12:15 PM EDT: The merge label '0-merge' was detected. This PR will be added to the Graphite merge queue once it meets the requirements.
  • Sep 5, 12:33 PM EDT: Boshen merged this pull request with the Graphite merge queue.

@graphite-app graphite-app bot merged commit cedf7a4 into main Sep 5, 2024
24 checks passed
@graphite-app graphite-app bot deleted the feat/ast-kind-as-ty-impl branch September 5, 2024 16:33
@shulaoda
Copy link
Contributor

shulaoda commented Sep 5, 2024

This could avoid written many nested levels if let #ty pattern match: if let AstKind::xxx() =

But it seems that we can't stop the behavior of if let Some() =. Does this help with the following writing style?

fn run<'a>(possible_jest_node: &PossibleJestNode<'a, '_>, ctx: &LintContext<'a>) {
let node = possible_jest_node.node;
if let AstKind::CallExpression(call_expr) = node.kind() {
if is_type_of_jest_fn_call(

@IWANABETHATGUY
Copy link
Contributor Author

This could avoid written many nested levels if let #ty pattern match: if let AstKind::xxx() =

But it seems that we can't stop the behavior of if let Some() =. Does this help with the following writing style?

fn run<'a>(possible_jest_node: &PossibleJestNode<'a, '_>, ctx: &LintContext<'a>) {
let node = possible_jest_node.node;
if let AstKind::CallExpression(call_expr) = node.kind() {
if is_type_of_jest_fn_call(

Yeah you could just:

diff --git a/crates/oxc_ast/src/generated/ast_kind.rs b/crates/oxc_ast/src/generated/ast_kind.rs
index 2c68cb958..e512d0034 100644
--- a/crates/oxc_ast/src/generated/ast_kind.rs
+++ b/crates/oxc_ast/src/generated/ast_kind.rs
@@ -696,7 +696,7 @@ impl<'a> AstKind<'a> {
         }
     }
 
-    pub fn as_call_expression(&self) -> Option<&CallExpression<'a>> {
+    pub fn as_call_expression(&self) -> Option<&'a CallExpression<'a>> {
         if let Self::CallExpression(v) = self {
             Some(*v)
         } else {
@@ -936,7 +936,7 @@ impl<'a> AstKind<'a> {
         }
     }
 
-    pub fn as_if_statement(&self) -> Option<&IfStatement<'a>> {
+    pub fn as_if_statement(&self) -> Option<&'a IfStatement<'a>> {
         if let Self::IfStatement(v) = self {
             Some(*v)
         } else {
diff --git a/crates/oxc_linter/src/rules/vitest/no_conditional_tests.rs b/crates/oxc_linter/src/rules/vitest/no_conditional_tests.rs
index 17be91c88..ce9be1882 100644
--- a/crates/oxc_linter/src/rules/vitest/no_conditional_tests.rs
+++ b/crates/oxc_linter/src/rules/vitest/no_conditional_tests.rs
@@ -66,30 +66,27 @@ impl Rule for NoConditionalTests {
     }
 }
 
-fn run<'a>(possible_jest_node: &PossibleJestNode<'a, '_>, ctx: &LintContext<'a>) {
+fn run<'a>(possible_jest_node: &PossibleJestNode<'a, '_>, ctx: &LintContext<'a>) -> Option<()> {
     let node = possible_jest_node.node;
-    if let AstKind::CallExpression(call_expr) = node.kind() {
-        if is_type_of_jest_fn_call(
-            call_expr,
-            possible_jest_node,
-            ctx,
-            &[
-                JestFnKind::General(JestGeneralFnKind::Describe),
-                JestFnKind::General(JestGeneralFnKind::Test),
-            ],
-        ) {
-            let if_statement_node = ctx
-                .nodes()
-                .iter_parents(node.id())
-                .find(|node| matches!(node.kind(), AstKind::IfStatement(_)));
+    let call_expr = node.kind().as_call_expression()?;
+    if is_type_of_jest_fn_call(
+        call_expr,
+        possible_jest_node,
+        ctx,
+        &[
+            JestFnKind::General(JestGeneralFnKind::Describe),
+            JestFnKind::General(JestGeneralFnKind::Test),
+        ],
+    ) {
+        let if_statement_node = ctx
+            .nodes()
+            .iter_parents(node.id())
+            .find(|node| matches!(node.kind(), AstKind::IfStatement(_)))?;
 
-            let Some(node) = if_statement_node else { return };
-
-            if let AstKind::IfStatement(if_statement) = node.kind() {
-                ctx.diagnostic(no_conditional_tests(if_statement.span));
-            }
-        }
+        let if_stmt = if_statement_node.kind().as_if_statement()?;
+        ctx.diagnostic(no_conditional_tests(if_stmt.span));
     }
+    None
 }
 
 #[test]

@IWANABETHATGUY
Copy link
Contributor Author

I need to add the 'a back , or the code not gonna compile, 😢 @rzvxa

@rzvxa
Copy link
Collaborator

rzvxa commented Sep 5, 2024

I need to add the 'a back , or the code not gonna compile, 😢 @rzvxa

Yes, it seems like it😓

I like this implementation(#5506) better than the one with the reference, What are your thoughts on it?

shulaoda added a commit to shulaoda/oxc that referenced this pull request Sep 5, 2024
Boshen pushed a commit to shulaoda/oxc that referenced this pull request Sep 6, 2024
Boshen pushed a commit that referenced this pull request Sep 6, 2024
@oxc-bot oxc-bot mentioned this pull request Sep 6, 2024
Boshen added a commit that referenced this pull request Sep 6, 2024
## [0.27.0] - 2024-09-06

- bd820f9 semantic: [**BREAKING**] Remove
`SymbolTable::get_symbol_id_from_name` and
`SymbolTable::get_scope_id_from_name` (#5480) (overlookmotel)

- cba93f5 ast: [**BREAKING**] Add `ThisExpression` variants to
`JSXElementName` and `JSXMemberExpressionObject` (#5466) (overlookmotel)

- 87c5df2 ast: [**BREAKING**] Rename `Expression::without_parentheses`
(#5448) (overlookmotel)

### Features

- e8bdd12 allocator: Add `AsMut` impl for `Box` (#5515) (overlookmotel)
- 90facd3 ast: Add `ContentHash` trait; remove noop `Hash`
implementation from `Span` (#5451) (rzvxa)
- 23285f4 ast: Add `ContentEq` trait. (#5427) (rzvxa)
- 59abf27 ast, parser: Add `oxc_regular_expression` types to the parser
and AST. (#5256) (rzvxa)
- 68a1c01 ast_tools: Add dedicated `Derive` trait. (#5278) (rzvxa)
- c782916 codegen: Print `type_parameters` in `TaggedTemplateExpression`
(#5438) (Dunqing)
- 4cb63fe index: Impl rayon related to trait for IndexVec (#5421)
(IWANABETHATGUY)
- ba4b68c minifier: Remove parenthesized expression for dce (#5439)
(Boshen)
- ed8ab6d oxc: Conditional expose `oxc_cfg` in `oxc` crate (#5524)
(IWANABETHATGUY)
- 91b39c4 oxc_diagnostic: Impl DerefMut for OxcDiagnostic (#5474)
(IWANABETHATGUY)
- 10279f5 parser: Add syntax error for hyphen in `JSXMemberExpression`
`<Foo.bar-baz />` (#5440) (Boshen)
- 0f50b1e semantic: Check for initializers in ambient
`VariableDeclaration`s (#5463) (DonIsaac)
- 62f7fff semantic: Check for non-declared, non-abstract object
accessors without bodies (#5461) (DonIsaac)
- 5407143 semantic: Check for non-declared, non-abstract class accessors
without bodies (#5460) (DonIsaac)
- 052e94c semantic: Check for parameter properties in constructor
overloads (#5459) (DonIsaac)
- 32d4bbb transformer: Add `TransformOptions::enable_all` method (#5495)
(Boshen)
- c59d8b3 transformer: Support all /regex/ to `new RegExp` transforms
(#5387) (Dunqing)
- cedf7a4 xtask: Impl `as_ast_kind` method for each variant (#5491)
(IWANABETHATGUY)

### Bug Fixes

- 0df1d9d ast, codegen, linter: Panics in fixers. (#5431) (rzvxa)
- fce549e diagnostics: Ignore `Interrupted` and `BrokenPipe` errors
while printing (#5526) (Boshen)
- ea7a52f napi/transform: Fix test (Boshen)
- 9b984b3 regex: Panic on displaying surrogated `UnicodeEscape`
characters. (#5469) (rzvxa)
- 88b7ddb regular_expression: Handle unterminated character class
(#5523) (leaysgur)
- 7a797ac semantic: Incorrect reference when `MemberExpression` used in
`TSPropertySignature` (#5525) (Dunqing)
- d8b9909 semantic: `IdentifierReference` within `TSPropertySignature`
cannot reference type-only import binding (#5441) (Dunqing)
- 8f9627d transformer: RegExp transform do not transform invalid regexps
(#5494) (overlookmotel)
- 2060efc transformer: RegExp transform don't transform all RegExps
(#5486) (overlookmotel)
- cfe5497 transformer: Do not create double reference in JSX transform
(#5414) (overlookmotel)
- 0617249 transformer/nullish-coalescing-operator: Incorrect reference
flags (#5408) (Dunqing)
- 0eb32a6 traverse: Invalid variable name generated by
`generate_uid_based_on_node` (#5407) (Dunqing)- b96bea4 Add back
lifetime (#5507) (IWANABETHATGUY)

### Performance

- bfabd8f syntax: Further optimize `is_identifier_name` (#5426)
(overlookmotel)
- aeda84f syntax: Optimize `is_identifier_name` (#5425) (overlookmotel)
- ed8937e transformer: Memoize rope instance (#5518) (Dunqing)
- bfab091 transformer: Store needed options only on `RegExp` (#5484)
(overlookmotel)
- b4765af transformer: Pre-calculate if unsupported patterns in RegExp
transform (#5483) (overlookmotel)
- 182ab91 transformer: Pre-calculate unsupported flags in RegExp
transform (#5482) (overlookmotel)

### Documentation

- 64db1b4 ast: Clarify docs for `RegExpPattern` (#5497) (overlookmotel)
- 3f204a9 span: Update docs about `ContentEq` `Vec` comparison speed
(#5478) (overlookmotel)- 00511fd Use `oxc_index` instead of `index_vec`
in doc comments (#5423) (IWANABETHATGUY)

### Refactor

- 9f6e0ed ast: Simplify `ContentEq` trait definition. (#5468) (rzvxa)
- a43e951 ast: Use loop instead of recursion (#5447) (overlookmotel)
- 2224cc4 ast: Renumber `JSXMemberExpressionObject` discriminants
(#5464) (overlookmotel)
- a952c47 ast: Use loop not recursion (#5449) (overlookmotel)
- d9d7e7c ast: Remove `IdentifierName` from `TSThisParameter` (#5327)
(overlookmotel)
- ccc8a27 ast, ast_tools: Use full method path for generated derives
trait calls. (#5462) (rzvxa)
- fdb8857 linter: Use "parsed pattern" in `no_div_regex` rule. (#5417)
(rzvxa)
- e7bd49d regular_expression: Correct typo (#5429) (overlookmotel)
- e4ed41d semantic: Change the reference flag to `ReferenceFlags::Type`
if it is used within a `TSTypeQuery` (#5444) (Dunqing)
- 94a6ac6 span: Use `Hasher` from `std` (#5476) (overlookmotel)
- b47aca0 syntax: Use `generate_derive` for `CloneIn` in types outside
of `oxc_ast` crate. (#5280) (rzvxa)
- a96866d transformer: Re-order imports (#5499) (overlookmotel)
- 6abde0a transformer: Clarify match in RegExp transform (#5498)
(overlookmotel)
- 09c522a transformer: RegExp transform report pattern parsing errors
(#5496) (overlookmotel)
- dd19823 transformer: RegExp transform do not take ownership of
`Pattern` then reallocate it (#5492) (overlookmotel)
- 2514cc9 transformer/react: Move all entry points to implementation of
Traverse trait (#5473) (Dunqing)
- c984219 transformer/typescript: Move all entry points to
implementation of Traverse trait (#5422) (Dunqing)

### Styling

- 2a43fa4 linter: Introduce the writing style from PR #5491 and reduce
the if nesting (#5512) (dalaoshu)

### Testing

- 340b535 linter/no-unused-vars: Arrow functions in tagged templates
(#5510) (Don Isaac)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
@oxc-bot oxc-bot mentioned this pull request Sep 7, 2024
Boshen added a commit that referenced this pull request Sep 7, 2024
## [0.9.3] - 2024-09-07

### Features

- be3a432 linter: Implement typescript/no-magic-numbers (#4745)
(Alexander S.)
- 09aa86d linter/eslint: Implement `sort-vars` rule (#5430) (Jelle van
der Waa)
- 2ec2f7d linter/eslint: Implement no-alert (#5535) (Edwin Lim)
- a786acf linter/import: Add no-dynamic-require rule (#5389) (Jelle van
der Waa)
- 4473779 linter/node: Implement no-exports-assign (#5370) (dalaoshu)
- b846432 linter/oxc: Add fixer for `erasing-op` (#5377) (camc314)
- aff2c71 linter/react: Implement `self-closing-comp` (#5415) (Jelle van
der Waa)

### Bug Fixes

- 0df1d9d ast, codegen, linter: Panics in fixers. (#5431) (rzvxa)
- cdd1a91 linter: Typescript/no-magic-numbers: remove double minus for
reporting negative bigint numbers (#5565) (Alexander S.)
- ff88c1f linter: Don't mark binding rest elements as unused in TS
function overloads (#5470) (Cam McHenry)
- 088733b linter: Handle loops in `getter-return` rule (#5517) (Cam
McHenry)
- 82c0a16 linter: `tree_shaking/no_side_effects_in_initialization`
handle JSX correctly (#5450) (overlookmotel)
- 6285a02 linter: `eslint/radix` rule correctly check for unbound
symbols (#5446) (overlookmotel)
- c8ab353 linter/tree-shaking: Align JSXMemberExpression's report
(#5548) (mysteryven)
- 5187f38 linter/tree-shaking: Detect the correct export symbol
resolution (#5467) (mysteryven)

### Performance

- 8170954 linter/react: Add should_run conditions for react rules
(#5402) (Jelle van der Waa)

### Documentation

- a540215 linter: Update docs `Examples` for linter rules (#5513)
(dalaoshu)
- 7414190 linter: Update docs `Example` for linter rules (#5479)
(heygsc)

### Refactor

- 0ac420d linter: Use meaningful names for diagnostic parameters (#5564)
(Don Isaac)
- 81a394d linter: Deduplicate code in `oxc/no-async-await` (#5549)
(DonIsaac)
- 979c16c linter: Reduce nested if statements in
eslint/no_this_before_super (#5485) (IWANABETHATGUY)
- 1d3e973 linter: Simplify `eslint/radix` rule (#5445) (overlookmotel)
- fdb8857 linter: Use "parsed pattern" in `no_div_regex` rule. (#5417)
(rzvxa)
- 2ccbd93 linter: `react/jsx_no_undef` rule `get_member_ident` do not
return Option (#5411) (overlookmotel)

### Styling

- 2a43fa4 linter: Introduce the writing style from PR #5491 and reduce
the if nesting (#5512) (dalaoshu)- d8b29e7 Add trailing line breaks to
JSON files (#5544) (overlookmotel)- 694f032 Add trailing line breaks to
`package.json` files (#5542) (overlookmotel)

### Testing

- 340b535 linter/no-unused-vars: Arrow functions in tagged templates
(#5510) (Don Isaac)
- af69393 linter/no-useless-spread: Ensure spreads on identifiers pass
(#5561) (DonIsaac)- dc92489 Add trailing line breaks to conformance
fixtures (#5541) (overlookmotel)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
0-merge Merge with Graphite Merge Queue A-ast Area - AST A-ast-tools Area - AST tools
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants