From 9d5063f6e9d6e80191d002d68c378c81c9c596d1 Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 5 Feb 2025 00:52:55 +0000 Subject: [PATCH] style: format code with Go fmt and Gofumpt This commit fixes the style issues introduced in d70c3d0 according to the output from Go fmt and Gofumpt. Details: None --- cmd/esbuild/service.go | 12 ++- internal/bundler/bundler_default_test.go | 9 +- internal/bundler/bundler_test.go | 14 ++- internal/bundler/bundler_ts_test.go | 7 +- internal/bundler/linker.go | 58 ++++++----- internal/cache/cache.go | 35 ++++--- internal/config/config.go | 39 +++---- internal/config/globals.go | 6 +- internal/css_ast/css_decl_table.go | 6 +- internal/css_parser/css_decls_box.go | 15 ++- internal/css_parser/css_decls_color.go | 27 +++-- internal/css_parser/css_parser.go | 24 +++-- internal/fs/filepath.go | 18 ++-- internal/fs/iswin_wasm.go | 6 +- internal/js_ast/js_ast.go | 60 +++++------ internal/js_lexer/js_lexer.go | 8 +- internal/js_parser/js_parser.go | 124 ++++++++++++----------- internal/js_parser/js_parser_lower.go | 32 +++--- internal/js_parser/ts_parser.go | 17 ++-- internal/js_parser/ts_parser_test.go | 5 +- internal/js_printer/js_printer.go | 24 +++-- internal/logger/logger.go | 6 +- internal/logger/logger_windows.go | 10 +- internal/resolver/resolver.go | 12 ++- internal/sourcemap/sourcemap.go | 13 ++- pkg/api/api.go | 83 ++++++++------- pkg/api/api_impl.go | 1 - pkg/cli/cli.go | 54 +++++----- 28 files changed, 387 insertions(+), 338 deletions(-) diff --git a/cmd/esbuild/service.go b/cmd/esbuild/service.go index 3b646985805..bde6800c6e2 100644 --- a/cmd/esbuild/service.go +++ b/cmd/esbuild/service.go @@ -24,11 +24,13 @@ import ( "github.com/evanw/esbuild/pkg/cli" ) -type responseCallback func(interface{}) -type rebuildCallback func(uint32) []byte -type watchStopCallback func() -type serveStopCallback func() -type pluginResolveCallback func(uint32, map[string]interface{}) []byte +type ( + responseCallback func(interface{}) + rebuildCallback func(uint32) []byte + watchStopCallback func() + serveStopCallback func() + pluginResolveCallback func(uint32, map[string]interface{}) []byte +) type activeBuild struct { rebuild rebuildCallback diff --git a/internal/bundler/bundler_default_test.go b/internal/bundler/bundler_default_test.go index 389d46c72b9..a8361b36cc6 100644 --- a/internal/bundler/bundler_default_test.go +++ b/internal/bundler/bundler_default_test.go @@ -5642,11 +5642,10 @@ func TestToESMWrapperOmission(t *testing.T) { // This is coverage for a past bug in esbuild. We used to generate this, which is wrong: // -// let x = function(foo) { -// var foo2; -// return foo2; -// }; -// +// let x = function(foo) { +// var foo2; +// return foo2; +// }; func TestNamedFunctionExpressionArgumentCollision(t *testing.T) { loader_suite.expectBundled(t, bundled{ files: map[string]string{ diff --git a/internal/bundler/bundler_test.go b/internal/bundler/bundler_test.go index ae8fc6b8bcc..4492dab3928 100644 --- a/internal/bundler/bundler_test.go +++ b/internal/bundler/bundler_test.go @@ -131,12 +131,16 @@ func (s *suite) expectBundled(t *testing.T, args bundled) { }) } -const snapshotsDir = "snapshots" -const snapshotSplitter = "\n================================================================================\n" +const ( + snapshotsDir = "snapshots" + snapshotSplitter = "\n================================================================================\n" +) -var globalTestMutex sync.Mutex -var globalSuites map[*suite]bool -var globalUpdateSnapshots bool +var ( + globalTestMutex sync.Mutex + globalSuites map[*suite]bool + globalUpdateSnapshots bool +) func (s *suite) compareSnapshot(t *testing.T, testName string, generated string) { t.Helper() diff --git a/internal/bundler/bundler_ts_test.go b/internal/bundler/bundler_ts_test.go index bcdde9bf862..083498f36ed 100644 --- a/internal/bundler/bundler_ts_test.go +++ b/internal/bundler/bundler_ts_test.go @@ -1934,10 +1934,9 @@ func TestTSEnumExportClause(t *testing.T) { // This checks that we don't generate a warning for code that the TypeScript // compiler generates that looks like this: // -// var __rest = (this && this.__rest) || function (s, e) { -// ... -// }; -// +// var __rest = (this && this.__rest) || function (s, e) { +// ... +// }; func TestTSThisIsUndefinedWarning(t *testing.T) { ts_suite.expectBundled(t, bundled{ files: map[string]string{ diff --git a/internal/bundler/linker.go b/internal/bundler/linker.go index ec6b691fa4f..ce475508eed 100644 --- a/internal/bundler/linker.go +++ b/internal/bundler/linker.go @@ -991,8 +991,7 @@ func (c *linkerContext) computeCrossChunkDependencies(chunks []chunkInfo) { // Ignore uses that aren't top-level symbols if otherChunkIndex := c.graph.Symbols.Get(importRef).ChunkIndex; otherChunkIndex.IsValid() { if otherChunkIndex := otherChunkIndex.GetIndex(); otherChunkIndex != uint32(chunkIndex) { - chunkRepr.importsFromOtherChunks[otherChunkIndex] = - append(chunkRepr.importsFromOtherChunks[otherChunkIndex], crossChunkImportItem{ref: importRef}) + chunkRepr.importsFromOtherChunks[otherChunkIndex] = append(chunkRepr.importsFromOtherChunks[otherChunkIndex], crossChunkImportItem{ref: importRef}) chunkMetas[otherChunkIndex].exports[importRef] = true } } @@ -2644,12 +2643,11 @@ func (c *linkerContext) addExportsForExportStar( } } else if existing.SourceIndex != otherSourceIndex { // Two different re-exports colliding makes it potentially ambiguous - existing.PotentiallyAmbiguousExportStarRefs = - append(existing.PotentiallyAmbiguousExportStarRefs, graph.ImportData{ - SourceIndex: otherSourceIndex, - Ref: name.Ref, - NameLoc: name.AliasLoc, - }) + existing.PotentiallyAmbiguousExportStarRefs = append(existing.PotentiallyAmbiguousExportStarRefs, graph.ImportData{ + SourceIndex: otherSourceIndex, + Ref: name.Ref, + NameLoc: name.AliasLoc, + }) resolvedExports[alias] = existing } } @@ -2968,11 +2966,11 @@ func sanitizeFilePathForVirtualModulePath(path string) string { // order that JavaScript modules were evaluated in before the top-level await // feature was introduced. // -// A -// / \ -// B C -// \ / -// D +// A +// / \ +// B C +// \ / +// D // // If A imports B and then C, B imports D, and C imports D, then the JavaScript // traversal order is D B C A. @@ -3036,11 +3034,11 @@ func (c *linkerContext) findImportedCSSFilesInJSOrder(entryPoint uint32) (order // CSS file multiple times is equivalent to evaluating it once at the last // location. So we drop all but the last evaluation in the order. // -// A -// / \ -// B C -// \ / -// D +// A +// / \ +// B C +// \ / +// D // // If A imports B and then C, B imports D, and C imports D, then the CSS // traversal order is B D C A. @@ -3657,9 +3655,12 @@ func (c *linkerContext) convertStmtsForChunk(sourceIndex uint32, stmtList *stmtL } else { if record.SourceIndex.IsValid() { if otherRepr := c.graph.Files[record.SourceIndex.GetIndex()].InputFile.Repr.(*graph.JSRepr); otherRepr.Meta.Wrap == graph.WrapESM { - stmtList.insideWrapperPrefix = append(stmtList.insideWrapperPrefix, js_ast.Stmt{Loc: stmt.Loc, + stmtList.insideWrapperPrefix = append(stmtList.insideWrapperPrefix, js_ast.Stmt{ + Loc: stmt.Loc, Data: &js_ast.SExpr{Value: js_ast.Expr{Loc: stmt.Loc, Data: &js_ast.ECall{ - Target: js_ast.Expr{Loc: stmt.Loc, Data: &js_ast.EIdentifier{Ref: otherRepr.AST.WrapperRef}}}}}}) + Target: js_ast.Expr{Loc: stmt.Loc, Data: &js_ast.EIdentifier{Ref: otherRepr.AST.WrapperRef}}, + }}}, + }) } } @@ -4349,7 +4350,11 @@ func (c *linkerContext) generateEntryPointTailJS( Data: &js_ast.SExportDefault{Value: js_ast.Stmt{ Data: &js_ast.SExpr{Value: js_ast.Expr{ Data: &js_ast.ECall{Target: js_ast.Expr{ - Data: &js_ast.EIdentifier{Ref: repr.AST.WrapperRef}}}}}}}}) + Data: &js_ast.EIdentifier{Ref: repr.AST.WrapperRef}, + }}, + }}, + }}, + }) } else { if repr.Meta.Wrap == graph.WrapESM { if repr.Meta.IsAsyncOrHasAsyncDependency { @@ -4358,13 +4363,20 @@ func (c *linkerContext) generateEntryPointTailJS( Data: &js_ast.SExpr{Value: js_ast.Expr{ Data: &js_ast.EAwait{Value: js_ast.Expr{ Data: &js_ast.ECall{Target: js_ast.Expr{ - Data: &js_ast.EIdentifier{Ref: repr.AST.WrapperRef}}}}}}}}) + Data: &js_ast.EIdentifier{Ref: repr.AST.WrapperRef}, + }}, + }}, + }}, + }) } else { // "init_foo();" stmts = append(stmts, js_ast.Stmt{ Data: &js_ast.SExpr{ Value: js_ast.Expr{Data: &js_ast.ECall{Target: js_ast.Expr{ - Data: &js_ast.EIdentifier{Ref: repr.AST.WrapperRef}}}}}}) + Data: &js_ast.EIdentifier{Ref: repr.AST.WrapperRef}, + }}}, + }, + }) } } diff --git a/internal/cache/cache.go b/internal/cache/cache.go index 000af6be2eb..7eacea39ab1 100644 --- a/internal/cache/cache.go +++ b/internal/cache/cache.go @@ -11,26 +11,25 @@ import ( // able to reuse the results of parsing between builds and make subsequent // builds faster by avoiding redundant parsing work. This only works if: // -// * The AST information in the cache must be considered immutable. There is -// no way to enforce this in Go, but please be disciplined about this. The -// ASTs are shared in between builds. Any information that must be mutated -// in the AST during a build must be done on a shallow clone of the data if -// the mutation happens after parsing (i.e. a clone that clones everything -// that will be mutated and shares only the parts that won't be mutated). +// - The AST information in the cache must be considered immutable. There is +// no way to enforce this in Go, but please be disciplined about this. The +// ASTs are shared in between builds. Any information that must be mutated +// in the AST during a build must be done on a shallow clone of the data if +// the mutation happens after parsing (i.e. a clone that clones everything +// that will be mutated and shares only the parts that won't be mutated). // -// * The information in the cache must not depend at all on the contents of -// any file other than the file being cached. Invalidating an entry in the -// cache does not also invalidate any entries that depend on that file, so -// caching information that depends on other files can result in incorrect -// results due to reusing stale data. For example, do not "bake in" some -// value imported from another file. -// -// * Cached ASTs must only be reused if the parsing options are identical -// between builds. For example, it would be bad if the AST parser depended -// on options inherited from a nearby "package.json" file but those options -// were not part of the cache key. Then the cached AST could incorrectly be -// reused even if the contents of that "package.json" file have changed. +// - The information in the cache must not depend at all on the contents of +// any file other than the file being cached. Invalidating an entry in the +// cache does not also invalidate any entries that depend on that file, so +// caching information that depends on other files can result in incorrect +// results due to reusing stale data. For example, do not "bake in" some +// value imported from another file. // +// - Cached ASTs must only be reused if the parsing options are identical +// between builds. For example, it would be bad if the AST parser depended +// on options inherited from a nearby "package.json" file but those options +// were not part of the cache key. Then the cached AST could incorrectly be +// reused even if the contents of that "package.json" file have changed. type CacheSet struct { FSCache FSCache CSSCache CSSCache diff --git a/internal/config/config.go b/internal/config/config.go index 28d7fe5ac38..2b2fb1c7120 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -309,32 +309,31 @@ type UnusedImportFlagsTS uint8 // With !UnusedImportKeepStmt && !UnusedImportKeepValues: // -// "import 'foo'" => "import 'foo'" -// "import * as unused from 'foo'" => "" -// "import { unused } from 'foo'" => "" -// "import { type unused } from 'foo'" => "" +// "import 'foo'" => "import 'foo'" +// "import * as unused from 'foo'" => "" +// "import { unused } from 'foo'" => "" +// "import { type unused } from 'foo'" => "" // // With UnusedImportKeepStmt && !UnusedImportKeepValues: // -// "import 'foo'" => "import 'foo'" -// "import * as unused from 'foo'" => "import 'foo'" -// "import { unused } from 'foo'" => "import 'foo'" -// "import { type unused } from 'foo'" => "import 'foo'" +// "import 'foo'" => "import 'foo'" +// "import * as unused from 'foo'" => "import 'foo'" +// "import { unused } from 'foo'" => "import 'foo'" +// "import { type unused } from 'foo'" => "import 'foo'" // // With !UnusedImportKeepStmt && UnusedImportKeepValues: // -// "import 'foo'" => "import 'foo'" -// "import * as unused from 'foo'" => "import * as unused from 'foo'" -// "import { unused } from 'foo'" => "import { unused } from 'foo'" -// "import { type unused } from 'foo'" => "" +// "import 'foo'" => "import 'foo'" +// "import * as unused from 'foo'" => "import * as unused from 'foo'" +// "import { unused } from 'foo'" => "import { unused } from 'foo'" +// "import { type unused } from 'foo'" => "" // // With UnusedImportKeepStmt && UnusedImportKeepValues: // -// "import 'foo'" => "import 'foo'" -// "import * as unused from 'foo'" => "import * as unused from 'foo'" -// "import { unused } from 'foo'" => "import { unused } from 'foo'" -// "import { type unused } from 'foo'" => "import {} from 'foo'" -// +// "import 'foo'" => "import 'foo'" +// "import * as unused from 'foo'" => "import * as unused from 'foo'" +// "import { unused } from 'foo'" => "import { unused } from 'foo'" +// "import { type unused } from 'foo'" => "import {} from 'foo'" const ( UnusedImportKeepStmt UnusedImportFlagsTS = 1 << iota // "importsNotUsedAsValues" != "remove" UnusedImportKeepValues // "preserveValueImports" == true @@ -502,8 +501,10 @@ type InjectableExport struct { Loc logger.Loc } -var filterMutex sync.Mutex -var filterCache map[string]*regexp.Regexp +var ( + filterMutex sync.Mutex + filterCache map[string]*regexp.Regexp +) func compileFilter(filter string) (result *regexp.Regexp) { if filter == "" { diff --git a/internal/config/globals.go b/internal/config/globals.go index de798d29ca7..619df59c57f 100644 --- a/internal/config/globals.go +++ b/internal/config/globals.go @@ -10,8 +10,10 @@ import ( "github.com/evanw/esbuild/internal/js_ast" ) -var processedGlobalsMutex sync.Mutex -var processedGlobals *ProcessedDefines +var ( + processedGlobalsMutex sync.Mutex + processedGlobals *ProcessedDefines +) // If something is in this list, then a direct identifier expression or property // access chain matching this will be assumed to have no side effects and will diff --git a/internal/css_ast/css_decl_table.go b/internal/css_ast/css_decl_table.go index 177b6873f71..edb33c30dc2 100644 --- a/internal/css_ast/css_decl_table.go +++ b/internal/css_ast/css_decl_table.go @@ -648,8 +648,10 @@ var KnownDeclarations = map[string]D{ "zoom": DZoom, } -var typoDetector *helpers.TypoDetector -var typoDetectorMutex sync.Mutex +var ( + typoDetector *helpers.TypoDetector + typoDetectorMutex sync.Mutex +) func MaybeCorrectDeclarationTypo(text string) (string, bool) { // Ignore CSS variables, which should not be corrected to CSS properties diff --git a/internal/css_parser/css_decls_box.go b/internal/css_parser/css_decls_box.go index 52587fdff36..75f7afa7436 100644 --- a/internal/css_parser/css_decls_box.go +++ b/internal/css_parser/css_decls_box.go @@ -40,15 +40,14 @@ const ( // We want to avoid a situation where the browser treats some of the original // rules as valid and others as invalid. // -// Safe: -// top: 1px; left: 0; bottom: 1px; right: 0; -// top: 1Q; left: 2Q; bottom: 3Q; right: 4Q; -// -// Unsafe: -// top: 1vh; left: 2vw; bottom: 3vh; right: 4vw; -// top: 1Q; left: 2Q; bottom: 3Q; right: 0; -// inset: 1Q 0 0 0; top: 0; +// Safe: +// top: 1px; left: 0; bottom: 1px; right: 0; +// top: 1Q; left: 2Q; bottom: 3Q; right: 4Q; // +// Unsafe: +// top: 1vh; left: 2vw; bottom: 3vh; right: 4vw; +// top: 1Q; left: 2Q; bottom: 3Q; right: 0; +// inset: 1Q 0 0 0; top: 0; type unitSafetyTracker struct { unit string status unitSafetyStatus diff --git a/internal/css_parser/css_decls_color.go b/internal/css_parser/css_decls_color.go index e1402cf4e9c..fa197141bf6 100644 --- a/internal/css_parser/css_decls_color.go +++ b/internal/css_parser/css_decls_color.go @@ -291,9 +291,12 @@ func (p *parser) lowerColor(token css_ast.Token) css_ast.Token { token.Text = "rgba" commaToken := p.commaToken() token.Children = &[]css_ast.Token{ - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexR(hex))}, commaToken, - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexG(hex))}, commaToken, - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexB(hex))}, commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexR(hex))}, + commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexG(hex))}, + commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexB(hex))}, + commaToken, {Kind: css_lexer.TNumber, Text: floatToStringForColor(float64(hexA(hex)) / 255)}, } } @@ -305,9 +308,12 @@ func (p *parser) lowerColor(token css_ast.Token) css_ast.Token { token.Text = "rgba" commaToken := p.commaToken() token.Children = &[]css_ast.Token{ - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexR(hex))}, commaToken, - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexG(hex))}, commaToken, - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexB(hex))}, commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexR(hex))}, + commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexG(hex))}, + commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexB(hex))}, + commaToken, {Kind: css_lexer.TNumber, Text: floatToStringForColor(float64(hexA(hex)) / 255)}, } } @@ -639,9 +645,12 @@ func (p *parser) mangleColor(token css_ast.Token, hex uint32) css_ast.Token { alpha = alpha[:space] } token.Children = &[]css_ast.Token{ - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexR(hex))}, commaToken, - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexG(hex))}, commaToken, - {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexB(hex))}, commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexR(hex))}, + commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexG(hex))}, + commaToken, + {Kind: css_lexer.TNumber, Text: strconv.Itoa(hexB(hex))}, + commaToken, {Kind: css_lexer.TNumber, Text: alpha}, } } diff --git a/internal/css_parser/css_parser.go b/internal/css_parser/css_parser.go index 6a560770d2a..2f4caed0137 100644 --- a/internal/css_parser/css_parser.go +++ b/internal/css_parser/css_parser.go @@ -521,17 +521,17 @@ var nonDeprecatedElementsSupportedByIE7 = map[string]bool{ // if any of the selectors are unsafe, since then browsers which don't support // that particular feature would ignore the entire merged qualified rule: // -// Input: -// a { color: red } -// b { color: red } -// input::-moz-placeholder { color: red } +// Input: +// a { color: red } +// b { color: red } +// input::-moz-placeholder { color: red } // -// Valid output: -// a, b { color: red } -// input::-moz-placeholder { color: red } +// Valid output: +// a, b { color: red } +// input::-moz-placeholder { color: red } // -// Invalid output: -// a, b, input::-moz-placeholder { color: red } +// Invalid output: +// a, b, input::-moz-placeholder { color: red } // // This considers IE 7 and above to be a browser that a user could possibly use. // Versions of IE less than 6 are not considered. @@ -1636,8 +1636,10 @@ stop: if corrected, ok := css_ast.MaybeCorrectDeclarationTypo(keyText); ok { data := p.tracker.MsgData(keyToken.Range, fmt.Sprintf("%q is not a known CSS property", keyText)) data.Location.Suggestion = corrected - p.log.AddMsgID(logger.MsgID_CSS_UnsupportedCSSProperty, logger.Msg{Kind: logger.Warning, Data: data, - Notes: []logger.MsgData{{Text: fmt.Sprintf("Did you mean %q instead?", corrected)}}}) + p.log.AddMsgID(logger.MsgID_CSS_UnsupportedCSSProperty, logger.Msg{ + Kind: logger.Warning, Data: data, + Notes: []logger.MsgData{{Text: fmt.Sprintf("Did you mean %q instead?", corrected)}}, + }) } } diff --git a/internal/fs/filepath.go b/internal/fs/filepath.go index ae65991b498..166eca5bf6d 100644 --- a/internal/fs/filepath.go +++ b/internal/fs/filepath.go @@ -343,13 +343,13 @@ func (fp goFilepath) fromSlash(path string) string { // by purely lexical processing. It applies the following rules // iteratively until no further processing can be done: // -// 1. Replace multiple Separator elements with a single one. -// 2. Eliminate each . path name element (the current directory). -// 3. Eliminate each inner .. path name element (the parent directory) -// along with the non-.. element that precedes it. -// 4. Eliminate .. elements that begin a rooted path: -// that is, replace "/.." by "/" at the beginning of a path, -// assuming Separator is '/'. +// 1. Replace multiple Separator elements with a single one. +// 2. Eliminate each . path name element (the current directory). +// 3. Eliminate each inner .. path name element (the parent directory) +// along with the non-.. element that precedes it. +// 4. Eliminate .. elements that begin a rooted path: +// that is, replace "/.." by "/" at the beginning of a path, +// assuming Separator is '/'. // // The returned path ends in a slash only if it represents a root directory, // such as "/" on Unix or `C:\` on Windows. @@ -359,8 +359,8 @@ func (fp goFilepath) fromSlash(path string) string { // If the result of this process is an empty string, Clean // returns the string ".". // -// See also Rob Pike, ``Lexical File Names in Plan 9 or -// Getting Dot-Dot Right,'' +// See also Rob Pike, “Lexical File Names in Plan 9 or +// Getting Dot-Dot Right,” // https://9p.io/sys/doc/lexnames.html func (fp goFilepath) clean(path string) string { originalPath := path diff --git a/internal/fs/iswin_wasm.go b/internal/fs/iswin_wasm.go index b44a60e06dc..abfc53e438e 100644 --- a/internal/fs/iswin_wasm.go +++ b/internal/fs/iswin_wasm.go @@ -7,8 +7,10 @@ import ( "os" ) -var checkedIfWindows bool -var cachedIfWindows bool +var ( + checkedIfWindows bool + cachedIfWindows bool +) func CheckIfWindows() bool { if !checkedIfWindows { diff --git a/internal/js_ast/js_ast.go b/internal/js_ast/js_ast.go index 362f6367306..30a6e247494 100644 --- a/internal/js_ast/js_ast.go +++ b/internal/js_ast/js_ast.go @@ -480,12 +480,14 @@ type EImportMeta struct { } // These help reduce unnecessary memory allocations -var BMissingShared = &BMissing{} -var EMissingShared = &EMissing{} -var ESuperShared = &ESuper{} -var ENullShared = &ENull{} -var EUndefinedShared = &EUndefined{} -var EThisShared = &EThis{} +var ( + BMissingShared = &BMissing{} + EMissingShared = &EMissing{} + ESuperShared = &ESuper{} + ENullShared = &ENull{} + EUndefinedShared = &EUndefined{} + EThisShared = &EThis{} +) type ENew struct { Target Expr @@ -976,11 +978,11 @@ type SSwitch struct { // This object represents all of these types of import statements: // -// import 'path' -// import {item1, item2} from 'path' -// import * as ns from 'path' -// import defaultItem, {item1, item2} from 'path' -// import defaultItem, * as ns from 'path' +// import 'path' +// import {item1, item2} from 'path' +// import * as ns from 'path' +// import defaultItem, {item1, item2} from 'path' +// import defaultItem, * as ns from 'path' // // Many parts are optional and can be combined in different ways. The only // restriction is that you cannot have both a clause and a star namespace. @@ -1535,27 +1537,27 @@ func (s *Scope) RecursiveSetStrictMode(kind StrictModeKind) { // block are merged into a single namespace while the non-exported code is // still scoped to just within that block: // -// let x = 1; -// namespace Foo { -// let x = 2; -// export let y = 3; -// } -// namespace Foo { -// console.log(x); // 1 -// console.log(y); // 3 -// } +// let x = 1; +// namespace Foo { +// let x = 2; +// export let y = 3; +// } +// namespace Foo { +// console.log(x); // 1 +// console.log(y); // 3 +// } // // Doing this also works inside an enum: // -// enum Foo { -// A = 3, -// B = A + 1, -// } -// enum Foo { -// C = A + 2, -// } -// console.log(Foo.B) // 4 -// console.log(Foo.C) // 5 +// enum Foo { +// A = 3, +// B = A + 1, +// } +// enum Foo { +// C = A + 2, +// } +// console.log(Foo.B) // 4 +// console.log(Foo.C) // 5 // // This is a form of identifier lookup that works differently than the // hierarchical scope-based identifier lookup in JavaScript. Lookup now needs diff --git a/internal/js_lexer/js_lexer.go b/internal/js_lexer/js_lexer.go index f86fe0fd99e..6bc1e2b6ee9 100644 --- a/internal/js_lexer/js_lexer.go +++ b/internal/js_lexer/js_lexer.go @@ -945,9 +945,11 @@ func (lexer *Lexer) NextJSXElementChild() { } else { replacement = "{'>'}" } - msg := logger.Msg{Kind: logger.Error, Data: lexer.tracker.MsgData(logger.Range{Loc: logger.Loc{Start: int32(lexer.end)}, Len: 1}, - fmt.Sprintf("The character \"%c\" is not valid inside a JSX element", lexer.codePoint)), - Notes: []logger.MsgData{{Text: fmt.Sprintf("Did you mean to escape it as %q instead?", replacement)}}} + msg := logger.Msg{ + Kind: logger.Error, Data: lexer.tracker.MsgData(logger.Range{Loc: logger.Loc{Start: int32(lexer.end)}, Len: 1}, + fmt.Sprintf("The character \"%c\" is not valid inside a JSX element", lexer.codePoint)), + Notes: []logger.MsgData{{Text: fmt.Sprintf("Did you mean to escape it as %q instead?", replacement)}}, + } msg.Data.Location.Suggestion = replacement if !lexer.ts.Parse { // TypeScript treats this as an error but Babel doesn't treat this diff --git a/internal/js_parser/js_parser.go b/internal/js_parser/js_parser.go index e7aa849b2f5..2071f35ea09 100644 --- a/internal/js_parser/js_parser.go +++ b/internal/js_parser/js_parser.go @@ -24,10 +24,10 @@ import ( // // 1. Parse the source into an AST, create the scope tree, and declare symbols. // -// 2. Visit each node in the AST, bind identifiers to declared symbols, do -// constant folding, substitute compile-time variable definitions, and -// lower certain syntactic constructs as appropriate given the language -// target. +// 2. Visit each node in the AST, bind identifiers to declared symbols, do +// constant folding, substitute compile-time variable definitions, and +// lower certain syntactic constructs as appropriate given the language +// target. // // So many things have been put in so few passes because we want to minimize // the number of full-tree passes to improve performance. However, we need @@ -1269,7 +1269,6 @@ func (p *parser) declareSymbol(kind js_ast.SymbolKind, loc logger.Loc, name stri // Overwrite this name in the declaring scope p.currentScope.Members[name] = js_ast.ScopeMember{Ref: ref, Loc: loc} return ref - } func (p *parser) hoistSymbols(scope *js_ast.Scope) { @@ -1645,20 +1644,19 @@ func (p *parser) logDeferredArrowArgErrors(errors *deferredErrors) { // // Specifically, for await: // -// // This is ok -// async function foo() { (x = await y) } +// // This is ok +// async function foo() { (x = await y) } // -// // This is an error -// async function foo() { (x = await y) => {} } +// // This is an error +// async function foo() { (x = await y) => {} } // // And for yield: // -// // This is ok -// function* foo() { (x = yield y) } -// -// // This is an error -// function* foo() { (x = yield y) => {} } +// // This is ok +// function* foo() { (x = yield y) } // +// // This is an error +// function* foo() { (x = yield y) => {} } type deferredArrowArgErrors struct { invalidExprAwait logger.Range invalidExprYield logger.Range @@ -2444,7 +2442,8 @@ func (p *parser) parseAsyncPrefixExpr(asyncRange logger.Range, level js_ast.L, f case js_lexer.TEqualsGreaterThan: if level <= js_ast.LAssign { arg := js_ast.Arg{Binding: js_ast.Binding{Loc: asyncRange.Loc, Data: &js_ast.BIdentifier{ - Ref: p.storeNameInRef(js_lexer.MaybeSubstring{String: "async"})}}} + Ref: p.storeNameInRef(js_lexer.MaybeSubstring{String: "async"}), + }}} p.pushScopeForParsePass(js_ast.ScopeFunctionArgs, asyncRange.Loc) defer p.popScope() @@ -2508,7 +2507,8 @@ func (p *parser) parseAsyncPrefixExpr(asyncRange logger.Range, level js_ast.L, f // "async" // "async + 1" return js_ast.Expr{Loc: asyncRange.Loc, Data: &js_ast.EIdentifier{ - Ref: p.storeNameInRef(js_lexer.MaybeSubstring{String: "async"})}} + Ref: p.storeNameInRef(js_lexer.MaybeSubstring{String: "async"}), + }} } func (p *parser) parseFnExpr(loc logger.Loc, isAsync bool, asyncRange logger.Range) js_ast.Expr { @@ -2735,7 +2735,8 @@ func (p *parser) parseParenExpr(loc logger.Loc, level js_ast.L, opts parenExprOp if isAsync { p.logExprErrors(&errors) async := js_ast.Expr{Loc: loc, Data: &js_ast.EIdentifier{ - Ref: p.storeNameInRef(js_lexer.MaybeSubstring{String: "async"})}} + Ref: p.storeNameInRef(js_lexer.MaybeSubstring{String: "async"}), + }} return js_ast.Expr{Loc: loc, Data: &js_ast.ECall{ Target: async, Args: items, @@ -3411,7 +3412,8 @@ func (p *parser) parsePrefix(level js_ast.L, errors *deferredErrors, flags exprF how = " You can use 'Loader: map[string]api.Loader{\".js\": api.LoaderJSX}' to do that." } p.log.AddErrorWithNotes(&p.tracker, p.lexer.Range(), "The JSX syntax extension is not currently enabled", []logger.MsgData{{ - Text: "The esbuild loader for this file is currently set to \"js\" but it must be set to \"jsx\" to be able to parse JSX syntax." + how}}) + Text: "The esbuild loader for this file is currently set to \"js\" but it must be set to \"jsx\" to be able to parse JSX syntax." + how, + }}) p.options.jsx.Parse = true } @@ -5987,7 +5989,8 @@ func (p *parser) parseStmt(opts parseStmtOpts) js_ast.Stmt { expr := p.parseSuffix(p.parseAsyncPrefixExpr(asyncRange, js_ast.LComma, 0), js_ast.LComma, nil, 0) p.lexer.ExpectOrInsertSemicolon() return js_ast.Stmt{Loc: loc, Data: &js_ast.SExportDefault{ - DefaultName: defaultName, Value: js_ast.Stmt{Loc: loc, Data: &js_ast.SExpr{Value: expr}}}} + DefaultName: defaultName, Value: js_ast.Stmt{Loc: loc, Data: &js_ast.SExpr{Value: expr}}, + }} } if p.lexer.Token == js_lexer.TFunction || p.lexer.Token == js_lexer.TClass || p.lexer.IsContextualKeyword("interface") { @@ -6049,7 +6052,8 @@ func (p *parser) parseStmt(opts parseStmtOpts) js_ast.Stmt { p.lexer.ExpectOrInsertSemicolon() defaultName := createDefaultName() return js_ast.Stmt{Loc: loc, Data: &js_ast.SExportDefault{ - DefaultName: defaultName, Value: js_ast.Stmt{Loc: loc, Data: &js_ast.SExpr{Value: expr}}}} + DefaultName: defaultName, Value: js_ast.Stmt{Loc: loc, Data: &js_ast.SExpr{Value: expr}}, + }} case js_lexer.TAsterisk: if !opts.isModuleScope && (!opts.isNamespaceScope || !opts.isTypeScriptDeclare) { @@ -7328,10 +7332,10 @@ func findIdentifiers(binding js_ast.Binding, identifiers []js_ast.Decl) []js_ast // can. Everything can be trimmed except for hoisted declarations ("var" and // "function"), which affect the parent scope. For example: // -// function foo() { -// if (false) { var x; } -// x = 1; -// } +// function foo() { +// if (false) { var x; } +// x = 1; +// } // // We can't trim the entire branch as dead or calling foo() will incorrectly // assign to a global variable instead. @@ -7520,7 +7524,8 @@ func (p *parser) visitStmts(stmts []js_ast.Stmt, kind stmtsKind) []js_ast.Stmt { index = len(letDecls) fnStmts[s.Fn.Name.Ref] = index letDecls = append(letDecls, js_ast.Decl{Binding: js_ast.Binding{ - Loc: s.Fn.Name.Loc, Data: &js_ast.BIdentifier{Ref: s.Fn.Name.Ref}}}) + Loc: s.Fn.Name.Loc, Data: &js_ast.BIdentifier{Ref: s.Fn.Name.Ref}, + }}) // Also write the function to the hoisted sibling symbol if applicable if hoistedRef, ok := p.hoistedRefForSloppyModeBlockFn[s.Fn.Name.Ref]; ok { @@ -7840,8 +7845,10 @@ func (p *parser) mangleStmts(stmts []js_ast.Stmt, kind stmtsKind) []js_ast.Stmt if len(result) > 0 && s.ValueOrNil.Data != nil { prevStmt := result[len(result)-1] if prevS, ok := prevStmt.Data.(*js_ast.SExpr); ok { - result[len(result)-1] = js_ast.Stmt{Loc: prevStmt.Loc, - Data: &js_ast.SReturn{ValueOrNil: js_ast.JoinWithComma(prevS.Value, s.ValueOrNil)}} + result[len(result)-1] = js_ast.Stmt{ + Loc: prevStmt.Loc, + Data: &js_ast.SReturn{ValueOrNil: js_ast.JoinWithComma(prevS.Value, s.ValueOrNil)}, + } continue } } @@ -8956,7 +8963,8 @@ func (p *parser) maybeKeepExprSymbolName(value js_ast.Expr, name string, wasAnon } func (p *parser) keepExprSymbolName(value js_ast.Expr, name string) js_ast.Expr { - value = p.callRuntime(value.Loc, "__name", []js_ast.Expr{value, + value = p.callRuntime(value.Loc, "__name", []js_ast.Expr{ + value, {Loc: value.Loc, Data: &js_ast.EString{Value: helpers.StringToUTF16(name)}}, }) @@ -9964,22 +9972,21 @@ func isUnsightlyPrimitive(data js_ast.E) bool { // a constant declared later on, then we need to end the const local prefix. // We want to avoid situations like this: // -// const x = y; // This is supposed to throw due to TDZ -// const y = 1; +// const x = y; // This is supposed to throw due to TDZ +// const y = 1; // // or this: // -// const x = 1; -// const y = foo(); // This is supposed to throw due to TDZ -// const z = 2; -// const foo = () => z; +// const x = 1; +// const y = foo(); // This is supposed to throw due to TDZ +// const z = 2; +// const foo = () => z; // // But a situation like this is ok: // -// const x = 1; -// const y = [() => z]; -// const z = 2; -// +// const x = 1; +// const y = [() => z]; +// const z = 2; func isSafeForConstLocalPrefix(expr js_ast.Expr) bool { switch e := expr.Data.(type) { case *js_ast.EMissing, *js_ast.EString, *js_ast.ERegExp, *js_ast.EBigInt, *js_ast.EFunction, *js_ast.EArrow: @@ -10112,14 +10119,14 @@ const ( // // Example usage: // -// // "value" => "value + value" -// // "value()" => "(_a = value(), _a + _a)" -// valueFunc, wrapFunc := p.captureValueWithPossibleSideEffects(loc, 2, value) -// return wrapFunc(js_ast.Expr{Loc: loc, Data: &js_ast.EBinary{ -// Op: js_ast.BinOpAdd, -// Left: valueFunc(), -// Right: valueFunc(), -// }}) +// // "value" => "value + value" +// // "value()" => "(_a = value(), _a + _a)" +// valueFunc, wrapFunc := p.captureValueWithPossibleSideEffects(loc, 2, value) +// return wrapFunc(js_ast.Expr{Loc: loc, Data: &js_ast.EBinary{ +// Op: js_ast.BinOpAdd, +// Left: valueFunc(), +// Right: valueFunc(), +// }}) // // This returns a function for generating references instead of a raw reference // because AST nodes are supposed to be unique in memory, not aliases of other @@ -11744,7 +11751,8 @@ pattern: p.log.AddIDWithNotes(logger.MsgID_JS_UnsupportedRegExp, logger.Debug, &p.tracker, r, fmt.Sprintf("%s in %s", what, where), append(notes, logger.MsgData{ Text: "This regular expression literal has been converted to a \"new RegExp()\" constructor " + "to avoid generating code with a syntax error. However, you will need to include a " + - "polyfill for \"RegExp\" for your code to have the correct behavior at run-time."})) + "polyfill for \"RegExp\" for your code to have the correct behavior at run-time.", + })) } return @@ -15266,8 +15274,10 @@ func newParser(log logger.Log, source logger.Source, lexer js_lexer.Lexer, optio return p } -var defaultJSXFactory = []string{"React", "createElement"} -var defaultJSXFragment = []string{"React", "Fragment"} +var ( + defaultJSXFactory = []string{"React", "createElement"} + defaultJSXFragment = []string{"React", "Fragment"} +) func Parse(log logger.Log, source logger.Source, options Options) (result js_ast.AST, ok bool) { ok = true @@ -15371,7 +15381,7 @@ func Parse(log logger.Log, source logger.Source, options Options) (result js_ast CanBeRemovedIfUnused: true, } - var before = []js_ast.Part{nsExportPart} + before := []js_ast.Part{nsExportPart} var parts []js_ast.Part var after []js_ast.Part @@ -15612,14 +15622,12 @@ func (p *parser) prepareForVisitPass() { } // Determine whether or not this file is ESM - p.isFileConsideredToHaveESMExports = - p.esmExportKeyword.Len > 0 || - p.esmImportMeta.Len > 0 || - p.topLevelAwaitKeyword.Len > 0 || - p.options.moduleTypeData.Type.IsESM() - p.isFileConsideredESM = - p.isFileConsideredToHaveESMExports || - p.esmImportStatementKeyword.Len > 0 + p.isFileConsideredToHaveESMExports = p.esmExportKeyword.Len > 0 || + p.esmImportMeta.Len > 0 || + p.topLevelAwaitKeyword.Len > 0 || + p.options.moduleTypeData.Type.IsESM() + p.isFileConsideredESM = p.isFileConsideredToHaveESMExports || + p.esmImportStatementKeyword.Len > 0 // Legacy HTML comments are not allowed in ESM files if p.isFileConsideredESM && p.lexer.LegacyHTMLCommentRange.Len > 0 { diff --git a/internal/js_parser/js_parser_lower.go b/internal/js_parser/js_parser_lower.go index e3ea2d34162..463728f4e57 100644 --- a/internal/js_parser/js_parser_lower.go +++ b/internal/js_parser/js_parser_lower.go @@ -327,8 +327,10 @@ func (p *parser) lowerFunction( (*args)[i].Binding.Data = &js_ast.BIdentifier{Ref: ref} // Append a variable declaration to the function body - prefixStmts = append(prefixStmts, js_ast.Stmt{Loc: arg.Binding.Loc, - Data: &js_ast.SLocal{Kind: js_ast.LocalVar, Decls: decls}}) + prefixStmts = append(prefixStmts, js_ast.Stmt{ + Loc: arg.Binding.Loc, + Data: &js_ast.SLocal{Kind: js_ast.LocalVar, Decls: decls}, + }) } } } @@ -937,26 +939,26 @@ func (p *parser) lowerNullishCoalescing(loc logger.Loc, left js_ast.Expr, right // properties are grouped into object literals and then passed to the // "__spreadValues" and "__spreadProps" functions like this: // -// "{a, b, ...c, d, e}" => "__spreadProps(__spreadValues(__spreadProps({a, b}, c), {d, e})" +// "{a, b, ...c, d, e}" => "__spreadProps(__spreadValues(__spreadProps({a, b}, c), {d, e})" // // If the object literal starts with a spread, then we pass an empty object // literal to "__spreadValues" to make sure we clone the object: // -// "{...a, b}" => "__spreadProps(__spreadValues({}, a), {b})" +// "{...a, b}" => "__spreadProps(__spreadValues({}, a), {b})" // // It's not immediately obvious why we don't compile everything to a single // call to a function that takes any number of arguments, since that would be // shorter. The reason is to preserve the order of side effects. Consider // this code: // -// let a = { -// get x() { -// b = {y: 2} -// return 1 -// } -// } -// let b = {} -// let c = {...a, ...b} +// let a = { +// get x() { +// b = {y: 2} +// return 1 +// } +// } +// let b = {} +// let c = {...a, ...b} // // Converting the above code to "let c = __spreadFn({}, a, null, b)" means "c" // becomes "{x: 1}" which is incorrect. Converting the above code instead to @@ -1515,8 +1517,10 @@ func (p *parser) lowerObjectRestHelper( for i, capturedKey := range capturedKeys { keysToExclude[i] = capturedKey() } - assign(binding, p.callRuntime(binding.Loc, "__objRest", []js_ast.Expr{init, - {Loc: binding.Loc, Data: &js_ast.EArray{Items: keysToExclude, IsSingleLine: isSingleLine}}})) + assign(binding, p.callRuntime(binding.Loc, "__objRest", []js_ast.Expr{ + init, + {Loc: binding.Loc, Data: &js_ast.EArray{Items: keysToExclude, IsSingleLine: isSingleLine}}, + })) } splitArrayPattern := func( diff --git a/internal/js_parser/ts_parser.go b/internal/js_parser/ts_parser.go index 811d1a3b52d..c079c2d523f 100644 --- a/internal/js_parser/ts_parser.go +++ b/internal/js_parser/ts_parser.go @@ -130,18 +130,17 @@ func (p *parser) skipTypeScriptFnArgs() { // This is a spot where the TypeScript grammar is highly ambiguous. Here are // some cases that are valid: // -// let x = (y: any): (() => {}) => { }; -// let x = (y: any): () => {} => { }; -// let x = (y: any): (y) => {} => { }; -// let x = (y: any): (y[]) => {}; -// let x = (y: any): (a | b) => {}; +// let x = (y: any): (() => {}) => { }; +// let x = (y: any): () => {} => { }; +// let x = (y: any): (y) => {} => { }; +// let x = (y: any): (y[]) => {}; +// let x = (y: any): (a | b) => {}; // // Here are some cases that aren't valid: // -// let x = (y: any): (y) => {}; -// let x = (y: any): (y) => {return 0}; -// let x = (y: any): asserts y is (y) => {}; -// +// let x = (y: any): (y) => {}; +// let x = (y: any): (y) => {return 0}; +// let x = (y: any): asserts y is (y) => {}; func (p *parser) skipTypeScriptParenOrFnType() { if p.trySkipTypeScriptArrowArgsWithBacktracking() { p.skipTypeScriptReturnType() diff --git a/internal/js_parser/ts_parser_test.go b/internal/js_parser/ts_parser_test.go index 079f949aa7f..29a89c54f12 100644 --- a/internal/js_parser/ts_parser_test.go +++ b/internal/js_parser/ts_parser_test.go @@ -442,9 +442,8 @@ func TestTSClass(t *testing.T) { expectPrintedTS(t, "class A implements B.C, F.G {}", "class A {\n}\n") expectPrintedTS(t, "class A extends X implements B.C, F.G {}", "class A extends X {\n}\n") - reservedWordError := - " is a reserved word and cannot be used in strict mode\n" + - ": NOTE: All code inside a class is implicitly in strict mode\n" + reservedWordError := " is a reserved word and cannot be used in strict mode\n" + + ": NOTE: All code inside a class is implicitly in strict mode\n" expectParseErrorTS(t, "class Foo { constructor(public) {} }", ": ERROR: \"public\""+reservedWordError) expectParseErrorTS(t, "class Foo { constructor(protected) {} }", ": ERROR: \"protected\""+reservedWordError) diff --git a/internal/js_printer/js_printer.go b/internal/js_printer/js_printer.go index c28d1be42ce..e2083dcbb6f 100644 --- a/internal/js_printer/js_printer.go +++ b/internal/js_printer/js_printer.go @@ -19,16 +19,20 @@ import ( "github.com/evanw/esbuild/internal/sourcemap" ) -var positiveInfinity = math.Inf(1) -var negativeInfinity = math.Inf(-1) - -const hexChars = "0123456789ABCDEF" -const firstASCII = 0x20 -const lastASCII = 0x7E -const firstHighSurrogate = 0xD800 -const lastHighSurrogate = 0xDBFF -const firstLowSurrogate = 0xDC00 -const lastLowSurrogate = 0xDFFF +var ( + positiveInfinity = math.Inf(1) + negativeInfinity = math.Inf(-1) +) + +const ( + hexChars = "0123456789ABCDEF" + firstASCII = 0x20 + lastASCII = 0x7E + firstHighSurrogate = 0xD800 + lastHighSurrogate = 0xDBFF + firstLowSurrogate = 0xDC00 + lastLowSurrogate = 0xDFFF +) func canPrintWithoutEscape(c rune, asciiOnly bool) bool { if c <= lastASCII { diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 92d86fe9b9c..a86c4fc5ca8 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -256,8 +256,10 @@ func (a Path) ComesBeforeInSortedOrder(b Path) bool { (a.Flags == b.Flags && a.IgnoredSuffix < b.IgnoredSuffix))))) } -var noColorResult bool -var noColorOnce sync.Once +var ( + noColorResult bool + noColorOnce sync.Once +) func hasNoColorEnvironmentVariable() bool { noColorOnce.Do(func() { diff --git a/internal/logger/logger_windows.go b/internal/logger/logger_windows.go index f2383ff87e1..ab6cefc8077 100644 --- a/internal/logger/logger_windows.go +++ b/internal/logger/logger_windows.go @@ -12,10 +12,12 @@ import ( const SupportsColorEscapes = true -var kernel32 = syscall.NewLazyDLL("kernel32.dll") -var getConsoleMode = kernel32.NewProc("GetConsoleMode") -var setConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") -var getConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + getConsoleMode = kernel32.NewProc("GetConsoleMode") + setConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") + getConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") +) type consoleScreenBufferInfo struct { dwSizeX int16 diff --git a/internal/resolver/resolver.go b/internal/resolver/resolver.go index cfbf9490f74..afc911bb431 100644 --- a/internal/resolver/resolver.go +++ b/internal/resolver/resolver.go @@ -883,8 +883,10 @@ func (r resolverQuery) dirInfoCached(path string) *dirInfo { return cached } -var errParseErrorImportCycle = errors.New("(import cycle)") -var errParseErrorAlreadyLogged = errors.New("(error already logged)") +var ( + errParseErrorImportCycle = errors.New("(import cycle)") + errParseErrorAlreadyLogged = errors.New("(error already logged)") +) // This may return "parseErrorAlreadyLogged" in which case there was a syntax // error, but it's already been reported. No further errors should be logged. @@ -1152,8 +1154,8 @@ func (r resolverQuery) dirInfoUncached(path string) *dirInfo { } // https://devblogs.microsoft.com/typescript/announcing-typescript-4-7-beta/#resolution-customization-with-modulesuffixes -// "Note that the empty string '' in moduleSuffixes is necessary for TypeScript to -// also look-up ./foo.ts. In a sense, the default value for moduleSuffixes is ['']." +// "Note that the empty string ” in moduleSuffixes is necessary for TypeScript to +// also look-up ./foo.ts. In a sense, the default value for moduleSuffixes is [”]." var defaultModuleSuffixes = []string{""} var rewrittenFileExtensions = map[string][]string{ @@ -2118,7 +2120,7 @@ func IsPackagePath(path string) bool { // This list can be obtained with the following command: // -// node --experimental-wasi-unstable-preview1 -p "[...require('module').builtinModules].join('\n')" +// node --experimental-wasi-unstable-preview1 -p "[...require('module').builtinModules].join('\n')" // // Be sure to use the *LATEST* version of node when updating this list! var BuiltInNodeModules = map[string]bool{ diff --git a/internal/sourcemap/sourcemap.go b/internal/sourcemap/sourcemap.go index d0c3f8ace9a..55e36389e03 100644 --- a/internal/sourcemap/sourcemap.go +++ b/internal/sourcemap/sourcemap.go @@ -73,12 +73,11 @@ var base64 = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456 // bit. The continuation bit tells us whether there are more digits in this // value following this digit. // -// Continuation -// | Sign -// | | -// V V -// 101011 -// +// Continuation +// | Sign +// | | +// V V +// 101011 func EncodeVLQ(value int) []byte { var vlq int if value < 0 { @@ -175,7 +174,7 @@ func DecodeVLQUTF16(encoded []uint16) (int, int, bool) { } // Recover the value - var value = vlq >> 1 + value := vlq >> 1 if (vlq & 1) != 0 { value = -value } diff --git a/pkg/api/api.go b/pkg/api/api.go index 9c281c2af05..78401910001 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -5,7 +5,7 @@ // creating a child process, there is also an API for the command-line // interface itself: https://godoc.org/github.com/evanw/esbuild/pkg/cli. // -// Build API +// # Build API // // This function runs an end-to-end build operation. It takes an array of file // paths as entry points, parses them and all of their dependencies, and @@ -14,29 +14,29 @@ // // Example usage: // -// package main +// package main // -// import ( -// "os" +// import ( +// "os" // -// "github.com/evanw/esbuild/pkg/api" -// ) +// "github.com/evanw/esbuild/pkg/api" +// ) // -// func main() { -// result := api.Build(api.BuildOptions{ -// EntryPoints: []string{"input.js"}, -// Outfile: "output.js", -// Bundle: true, -// Write: true, -// LogLevel: api.LogLevelInfo, -// }) +// func main() { +// result := api.Build(api.BuildOptions{ +// EntryPoints: []string{"input.js"}, +// Outfile: "output.js", +// Bundle: true, +// Write: true, +// LogLevel: api.LogLevelInfo, +// }) // -// if len(result.Errors) > 0 { -// os.Exit(1) -// } -// } +// if len(result.Errors) > 0 { +// os.Exit(1) +// } +// } // -// Transform API +// # Transform API // // This function transforms a string of source code into JavaScript. It can be // used to minify JavaScript, convert TypeScript/JSX to JavaScript, or convert @@ -45,36 +45,35 @@ // // Example usage: // -// package main -// -// import ( -// "fmt" -// "os" +// package main // -// "github.com/evanw/esbuild/pkg/api" -// ) +// import ( +// "fmt" +// "os" // -// func main() { -// jsx := ` -// import * as React from 'react' -// import * as ReactDOM from 'react-dom' +// "github.com/evanw/esbuild/pkg/api" +// ) // -// ReactDOM.render( -//

Hello, world!

, -// document.getElementById('root') -// ); -// ` +// func main() { +// jsx := ` +// import * as React from 'react' +// import * as ReactDOM from 'react-dom' // -// result := api.Transform(jsx, api.TransformOptions{ -// Loader: api.LoaderJSX, -// }) +// ReactDOM.render( +//

Hello, world!

, +// document.getElementById('root') +// ); +// ` // -// fmt.Printf("%d errors and %d warnings\n", -// len(result.Errors), len(result.Warnings)) +// result := api.Transform(jsx, api.TransformOptions{ +// Loader: api.LoaderJSX, +// }) // -// os.Stdout.Write(result.Code) -// } +// fmt.Printf("%d errors and %d warnings\n", +// len(result.Errors), len(result.Warnings)) // +// os.Stdout.Write(result.Code) +// } package api type SourceMap uint8 diff --git a/pkg/api/api_impl.go b/pkg/api/api_impl.go index b282fd2edc1..be5cb7df7b0 100644 --- a/pkg/api/api_impl.go +++ b/pkg/api/api_impl.go @@ -1551,7 +1551,6 @@ func (impl *pluginImpl) onStart(callback func() (OnStartResult, error)) { Name: impl.plugin.Name, Callback: func() (result config.OnStartResult) { response, err := callback() - if err != nil { result.ThrownError = err return diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index ec2fac7ee43..d8a9e1e57ee 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -3,18 +3,17 @@ // // Example usage: // -// package main +// package main // -// import ( -// "os" +// import ( +// "os" // -// "github.com/evanw/esbuild/pkg/cli" -// ) -// -// func main() { -// os.Exit(cli.Run(os.Args[1:])) -// } +// "github.com/evanw/esbuild/pkg/cli" +// ) // +// func main() { +// os.Exit(cli.Run(os.Args[1:])) +// } package cli import ( @@ -38,14 +37,13 @@ func Run(osArgs []string) int { // // Example usage: // -// options, err := cli.ParseBuildOptions([]string{ -// "input.js", -// "--bundle", -// "--minify", -// }) -// -// result := api.Build(options) +// options, err := cli.ParseBuildOptions([]string{ +// "input.js", +// "--bundle", +// "--minify", +// }) // +// result := api.Build(options) func ParseBuildOptions(osArgs []string) (options api.BuildOptions, err error) { options = newBuildOptions() _, errWithNote := parseOptionsImpl(osArgs, &options, nil, kindExternal) @@ -61,14 +59,13 @@ func ParseBuildOptions(osArgs []string) (options api.BuildOptions, err error) { // // Example usage: // -// options, err := cli.ParseTransformOptions([]string{ -// "--minify", -// "--loader=tsx", -// "--define:DEBUG=false", -// }) -// -// result := api.Transform(input, options) +// options, err := cli.ParseTransformOptions([]string{ +// "--minify", +// "--loader=tsx", +// "--define:DEBUG=false", +// }) // +// result := api.Transform(input, options) func ParseTransformOptions(osArgs []string) (options api.TransformOptions, err error) { options = newTransformOptions() _, errWithNote := parseOptionsImpl(osArgs, nil, &options, kindExternal) @@ -85,14 +82,13 @@ func ParseTransformOptions(osArgs []string) (options api.TransformOptions, err e // // Example usage: // -// serveOptions, args, err := cli.ParseServeOptions([]string{ -// "--serve=8000", -// }) -// -// buildOptions, err := cli.ParseBuildOptions(args) +// serveOptions, args, err := cli.ParseServeOptions([]string{ +// "--serve=8000", +// }) // -// result := api.Serve(serveOptions, buildOptions) +// buildOptions, err := cli.ParseBuildOptions(args) // +// result := api.Serve(serveOptions, buildOptions) func ParseServeOptions(osArgs []string) (options api.ServeOptions, remainingArgs []string, err error) { return parseServeOptionsImpl(osArgs) }