Commit graph

1515 commits

Author SHA1 Message Date
camc314
14d0590b0b feat(minifier): implement folding of simple function calls (Boolean) (#6484)
Basically `Boolean(true)` -> `true` or `Boolean(foo)` -> `!!foo`
2024-10-13 06:26:32 +00:00
camc314
7fbc7b6dae feat(minifier): implement folding of simple function calls (String) (#6483)
basically `String(foo)` -> `foo + ''`
2024-10-13 06:26:31 +00:00
DonIsaac
58467a53a1 feat(parser): better handling of invalid modifiers (#6482)
## What This PR Does

1. Recover on, and provide a better message for, invalid `export` modifier on constructor parameters. Before, an `unexpected token` error would be produced and the parser would panic. Now, the parser recovers and produces a message saying `'export' modifier cannot appear on a parameter.`
  ```ts
class Foo {
    constructor(export x: number) {}
}
  ```

2. Recover on, and provide a better message for, invalid modifiers on index signatures. Same recovery/message characteristics as above.
  ```ts
class Foo {
    public [x: string]: string;
}
```
2024-10-13 03:16:02 +00:00
DonIsaac
8ea6b721b8 feat(parser): better errors for reserved words used as identifier names (#6478)
## What This PR Does
Provide better error messages when a reserved word is used as a `BindingIdentifier`
```ts
var const = 1;
export enum const {}
const if = 1;
```
2024-10-13 03:16:01 +00:00
Boshen
91c87dd380 refactor(codegen)!: remove Codegen::enableSourceMap API (#6452) 2024-10-12 04:56:43 +00:00
Boshen
7645e5c34b refactor(codegen)!: remove CommentOptions API (#6451) 2024-10-11 13:53:28 +00:00
overlookmotel
073b02af14 refactor(ast): type params field before params in TS function declaration types (#6391)
Our convention is that AST type fields are ordered in order they appear in source. Move `type_parameters` fields in TS function declaration types to before `this_param` and formal parameters.
2024-10-11 09:57:28 +00:00
7086cmd
06ea1216af feat(minifier): fold for statement (#6450) 2024-10-11 08:33:23 +00:00
Boshen
cb8f4210c3 refactor(prettier)!: remove source_text argument from constructor (#6448) 2024-10-11 06:27:33 +00:00
Boshen
520096030a refactor(oxc)!: remove passing Trivias around (#6446)
part of #6426
2024-10-11 06:09:25 +00:00
Boshen
2808973af3 feat(ast)!: add Program::comments (#6445) 2024-10-11 04:47:36 +00:00
Boshen
2b7be08af4 feat(ast)! add source_text to Program (#6444) 2024-10-11 04:13:41 +00:00
Boshen
b1bf12c336 fix(parser): do not parse as and satisfies expression in javascript (#6442)
closes #6427
2024-10-11 03:31:24 +00:00
DonIsaac
80266d85c9 feat(linter)!: support plugins in oxlint config files (#6088)
> Closes #5046
This PR migrates the linter crate and oxlint app to use the new `LinterBuilder` API. This PR has the following effects:

1. `plugins` in oxlint config files are now supported
2. irons out weirdness when using CLI args and config files together. CLI args are now always applied on top of config file settings, overriding them.

# Breaking Changes
Before, config files would override rules set in CLI arguments. For example, running this command:
```sh
oxlint -A correctness -c oxlintrc.json
```
With this config file
```jsonc
// oxlintrc.json
{
  "rules": {
    "no-const-assign": "error"
  }
}
```
Would result in a single rule, `no-const-assign` being turned on at an error level with all other rules disabled (i.e. set to "allow").

Now, **CLI arguments will override config files**. That same command with the same config file will result with **all rules being disabled**.

## Details

For a more in-depth explanation, assume we are running the below command using the `oxlintrc.json` file above:
```sh
oxlint -A all -W correctness -A all -W suspicious -c oxlintrc.json
```

### Before
> Note: GitHub doesn't seem to like deeply nested lists. Apologies for the formatting.

Here was the config resolution process _before_ this PR:
<details><summary>Before Steps</summary>

1. Start with a default set of filters (["correctness", "warn"]) if no filters were passed to the CLI. Since some were, the filter list starts out empty.
2. Apply each filter taken from the CLI from left to right. When a filter allows a rule or category, it clears the configured set of rules. So applying those filters looks like this
  a. start with an empty list `[]`
  b. `("all", "allow")` -> `[]`
  c. `("correctness", "warn")` -> `[ <correctness rules> ]`
  d. `("all", "allow")` -> `[]`
  e. `("suspicious", "warn")` -> `[ <suspicious rules> ]`. This is the final rule set for this step
3. Apply overrides from `oxlintrc.json`. This is where things get a little funky, as mentioned in point 2 of what this PR does. At this point, all rules in the rules list are only from the CLI.
  a. If a rule is only set in the CLI and is not present in the config file, there's no effect
  b. If a rule is in the config file but not the CLI, it gets inserted into the list.
  c. If a rule is already in the list and in the config file
    i. If the rule is only present once (e.g. `"no-loss-of-precision": "error"`), unconditionally override whatever was in the CLI with what was set in the config file
    ii. If the rule is present twice (e.g. `"no-loss-of-precision": "off", "@typescript-eslint/no-loss-of-precision": "error"`),
      a. if all rules in the config file are set to `allow`, then turn the rule off
      b. If one of them is `warn` or `deny`, then update the currently-set rule's config object, but _leave its severity alone_.

  So, for our example, the final rule set would be `[<all suspicious rules: "warn">, no-const-assign: "error"]`

</details>

### After
Rule filters were completely re-worked in a previous PR. Now, lint filters aren't kept on hand-only the rule list is.

<details><summary>After Steps</summary>

1. Start with the default rule set, which is all correctness rules for all enabled plugins (`[<all correctness rules: "warn">]`)
2. Apply configuration from `oxlintrc.json` _first_.
  a. If the rule is warn/deny exists in the list already, update its severity and config object. If it's not in the list, add it.
  b. If the rule is set to allow, remove it from the list.

  The list is now `[<all correctness rules except no-const-assign: "warn">, no-const-assign: "error"]`.

3. Apply each filter taken from the CLI from left to right. This works the same way as before. So, after they're applied, the list is now `[<suspicous rules: "warn">]`

</details>
2024-10-10 19:21:50 +00:00
Boshen
6a194f9086 docs(span): document validity of ModuleKind::Unambiguous (#6423)
relates #6249
2024-10-10 14:59:41 +00:00
leaysgur
b5b0af98cb feat(regular_expression): Support RegExp Modifiers (#6410)
Fixes #6354
2024-10-10 14:46:17 +00:00
camc314
9dc4ee9c98 feat(minifier): implement block stmt support for StatementFusion (#6422) 2024-10-10 14:41:04 +00:00
leaysgur
c822b48d4f fix(regular_expression): Fix CharacterClass negative codegen (#6415)
Part of #6413 , fixes these mismatch.

```
  × Regular Expression content mismatch for `/[^]a/m`: `[]a` == `[]a`
  × Regular Expression content mismatch for `/a[^]/`: `a[]` == `a[]`
  × Regular Expression content mismatch for `/[^]/`: `[]` == `[]`
  × Regular Expression content mismatch for `/[^]/`: `[]` == `[]`
```
2024-10-10 05:00:45 +00:00
Boshen
95892ecc86 feat(coverage): add ContentEq test for regular_expression (#6411)
closes #6409

Marking as good first issue if anyone wants to pick this up and fix the failing test.
2024-10-10 02:21:21 +00:00
Boshen
eacde0553e chore(coverage): proposal-json-modules to stage 4 (#6380) 2024-10-09 03:09:35 +00:00
DonIsaac
834ee2aa6c fix(semantic): TSConditionalType scope enter/exit locations (#6351)
Fixes the same problem as #6270, but uses `#[scope(enter_before)]` and `#[scope(exit_after)]` to correct scope entry/exit locations.
2024-10-09 01:34:46 +00:00
DonIsaac
d9718adc8d feat(ast_tools): support #[scope(exit_before)] (#6350)
Closes #6311.

Adds support for `#[scope(exit_before)]`, which is the opposite of `#[scope(enter_before)]`
2024-10-09 01:34:44 +00:00
DonIsaac
6e3224d5fa feat(linter): configure by category in config files (#6120)
> closes #5454

Adds a `categories` property to config files, where each key is a `RuleCategory` and each value is `"allow"/"off"`, `"warn"`, or `"deny"/"error"`.

Note that this change won't come into effect until after #6088 is merged.
2024-10-08 22:19:07 +00:00
Boshen
f0a97811e4 chore(deps): update pnpm to v9.12.1 (#6365) 2024-10-08 14:54:27 +00:00
DonIsaac
01b878ecdb feat(parser)!: use BindingIdentifier for namespace declaration names (#6003)
Use `BindingIdentifier` instead of `IdentifierName` so that AST visitors can access the bound symbol id for the namespace's name. This makes namespace consistent with other named declarations, such as `Class`, `Function`, and `TSInterfaceDeclaration`.

We should consider modifying `TSModuleDeclarationName::StringLiteral(...)` to also store a `symbol_id`, since one gets bound in semantic for it as well.
2024-10-08 08:39:31 +00:00
DonIsaac
3b53dd4deb refactor(parser): provide better error messages for const modifiers on class elements (#6353)
Quality-of-life improvement for invalid `const` modifiers on class elements. Instead of panicking, the parser will eat `const` and report it as an error.

```ts
class C {
  static const H = 1;
}
```
2024-10-08 08:23:32 +00:00
DonIsaac
6159560170 fix(parser): string ImportSpecifiers for type imports (#6352)
Fixes a parse failure on imports like this:
```ts
import { type "<A>" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module";
```
2024-10-08 08:17:30 +00:00
overlookmotel
4fd89e8eed test(transformer): fix indentation in transformer test fixtures (#6346)
Unimportant nit. Fix whitespace in the transformer test fixtures.
2024-10-08 01:32:07 +00:00
overlookmotel
cf20f3a89d feat(transformer): exponentiation transform: support private fields (#6345)
Babel doesn't support private fields in this transform, but there's no reason not to. So we can.
2024-10-08 01:32:06 +00:00
overlookmotel
4aa4e6bec0 refactor(transformer): exponentiation transform: do not wrap in SequenceExpression if not needed (#6343)
`left **= right` is transformed to `left = Math.pow(left, right)`. There is no need to wrap it in a `SequenceExpression`.
2024-10-08 01:32:05 +00:00
7086cmd
f9ae70c74a feat(minifier): minify basic arithmetic calculations. (#6280)
It uses to_string to check which is shorter, which is extremely tough. Waiting for further refactor.
2024-10-07 10:41:06 +00:00
overlookmotel
2bcd12a868 fix(transformer): exponentiation transform: fix reference flags (#6330) 2024-10-07 10:35:34 +00:00
overlookmotel
28cbfa7c64 fix(transformer): exponentiation transform: fix temp var names (#6329)
Fix one case that I missed in #6318.
2024-10-07 09:00:35 +00:00
camchenry
4008afe512 feat(minifier): fold array and object constructors (#6257)
This will fold expressions like `new Object()` to `{}`, and `new Array()` to `[]`. Based on the closure compiler tests: b7e380b632/test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java (L78).

This is outside my usual area, so feedback is welcome.

NOTE: this was previously a full stack of PRs, but Graphite decided to stop working completely for some reason and only gave me this error when I submitted a PR:
```
ERROR: Failed to submit PR for 10-02-feat_minifier_fold_single_arg_new_array_expressions:
{}
```
so I decided to just completely remake this stack and submit as 1 PR.
2024-10-07 06:02:07 +00:00
overlookmotel
3a4bcc77fc fix(transformer): exponentiation transform: fix temp var names (#6318)
Make naming of temp vars follow Babel. It wasn't apparent that our version of this transform was behaving differently from Babel because the Babel plugin has very few tests. The added tests replicate Babel's output.
2024-10-06 23:08:10 +00:00
overlookmotel
ccb7bdcc56 fix(transformer): exponentiation transform: do not replace object when private property (#6313)
Fix exponentiation operator transform to bail out early if a private class property.

We can't transform this:

```js
class C {
    #p;
    method() {
        this.#p **= 2;
    }
}
```

But we should at least leave it alone. Previously `get_obj_ref` called `ast.move_expression(expr)` on the member expression's object before bailing out, so example above was transformed to:

```js
class C {
    #p;
    method() {
        null.#p **= 2; // <-- `null`
    }
}
```

This PR makes it spot this case early and bail out *before* calling `ast.move_expression(expr)`.
2024-10-06 23:08:08 +00:00
Boshen
020bb80b65 refactor(codegen)!: change to CodegenReturn::code and CodegenReturn::map (#6310) 2024-10-06 05:05:47 +00:00
overlookmotel
bd81c5134c fix(transformer): exponentiation transform: fix duplicate symbols (#6300)
Identifier was being cloned unnecessarily, creating an extra symbol.
2024-10-06 00:51:28 +00:00
Boshen
8729755baa feat(oxc,napi/transform): napi/transform use oxc compiler pipeline (#6298)
part of #6156
2024-10-05 16:35:09 +00:00
overlookmotel
409dffc8ab refactor(traverse)!: generate_uid return a BoundIdentifier (#6294)
Closes #5020.

`TraverseCtx::generate_uid` and associated methods return a `BoundIdentifier`, containing both symbol ID and name. This reduces boilerplate code for the caller and avoids and unnecessary lookup to get the name.

Also add a couple of helper methods to `BoundIdentifier` to reduce boilerplate further.
2024-10-05 16:00:50 +00:00
overlookmotel
06797b6900 fix(transformer): logical assignment operator transform: fix reference IDs (#6289) 2024-10-05 14:48:37 +00:00
overlookmotel
e19deaa102 ci(transformer): move post-transform checker to tasks crate (#6288)
Move post-transform checker into a `tasks` crate. It doesn't feel like it belongs in `oxc_semantic`. It also feels like too heavy a lump of code to put in `tasks/common`.
2024-10-05 14:48:37 +00:00
overlookmotel
0f5afd7ede test(transformer): transform checker output symbol name for mismatches (#6286)
Transform checker include symbol names in output for symbol mismatches. This is rather more helpful for locating bugs than just `SymbolId(3)`.
2024-10-05 14:42:06 +00:00
7086cmd
37cbabbac4 fix(minifier): should not handle the strict operation for bool comparison. (#6261) 2024-10-03 12:16:10 +00:00
leaysgur
5a73a663dc refactor(regular_expression)!: Simplify public APIs (#6262)
This PR makes 2 changes to improve the existing API that are not very useful.

- Remove `(Literal)Parser` and `FlagsParser` and their ASTs
- Add `with_flags(flags_text)` helper to `ParserOptions`

Here are the details.

> Remove `(Literal)Parser` and `FlagsParser` and their ASTs

Previously, the `oxc_regular_expression` crate exposed 3 parsers.

- `(Literal)Parser`: assumes `/pattern/flags` format
- `PatternParser`: assumes `pattern` part only
- `FlagsParser`: assumes `flags` part only

However, it turns out that in actual usecases, only the `PatternParser` is actually sufficient, as the pattern and flags are validated and sliced in advance on the `oxc_parser` side.

The current usecase for `(Literal)Parser` is mostly for internal testing.

There were also some misuses of `(Literal)Parser` that restore `format!("/{pattern}/{flags}")` back and use `(Literal)Parser`.

Therefore, only `PatternParser` is now published, and unnecessary ASTs have been removed.
(This also obsoletes #5592 .)

> Added `with_flags(flags_text)` helper to `ParserOptions`

Strictly speaking, there was a subtle difference between the "flag" strings that users were aware of and the "mode" recognised by the parser.

Therefore, it was a common mistake to forget to enable `unicode_mode` when using the `v` flag.

With this helper, crate users no longer need to distinguish between flags and modes.
2024-10-03 02:47:08 +00:00
overlookmotel
4f6bc79734 refactor(transformer)!: remove source_type param from Transformer::new (#6251)
Closes #6248.
2024-10-03 00:21:01 +00:00
7086cmd
23b646484c feat(minifier): fold true / false comparison. (#6225)
Input:
```js
a == false
```
Previous:
```js
a == !1
```
Current:
```js
a == 0
```

Only handle it when it is non-plus, non-relation binary expressions. Align with [Closure Compiler](https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520SIMPLE_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%2540formatting%2520pretty_print%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250Ax%2520%253C%253C%2520true%253B%250A%250Ax%2520%252B%2520true%253B%250A%250Ax%2520-%2520true%253B%250A%250Ax%2520%257C%2520true%253B%250A%250Ax%2520%2525%2520true%253B%250A%250Ay%2520!%253D%2520false%253B%250A%250Af()%2520%253D%253D%2520false%253B%250A%250Ax%2520instanceof%2520true%250A%250Ax%2520**%2520true%250A%250Ax%2520%2526%2520true%250A%250Ax%2520%255E%2520false%250A%250Ax%2520%253D%253D%2520(x%2520instanceof%2520false)%250A%250Ax%2520instanceof%2520(x%2520%253C%253C%2520true)%250A%250Ax%2520%253D%253D%2520fake(false)).
2024-10-02 13:37:17 +00:00
7086cmd
585ccdad8c feat(minifier): support subtraction assignment. (#6214)
Due to the potential for string concatenation when using the `+=` operator, we should only handle the scenario when using the `-=` operator.
2024-10-02 01:42:56 +00:00
overlookmotel
911e4e58ab ci(minifier): minifier benchmark measure only the minifier itself (#6222)
Minifier benchmark currently includes the time to run parser and semantic as well as the minifier itself. Similar to transformer benchmark, only measure the minifier itself in the benchmark.

This will give us a clearer picture of performance changes, and should also reduce variance in the benchmarks.
2024-10-01 17:43:39 +00:00
7086cmd
cca0034e8b feat(minifier): handle positive NaN and Infinity. (#6207)
`+NaN` -> `NaN`, `+Infinity` -> `Infinity`.
2024-10-01 10:12:19 +00:00