printer

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 15, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package printer exports a Printer for pretty-printing TS ASTs and writer interfaces and implementations for using them Intended ultimate usage:

func nodeToInlineStr(node *ast.Node) {
	// Reuse singleton single-line writer (TODO: thread safety?)
	p = printer.NewPrinter(printer.PrinterOptions{ RemoveComments: true }, printer.PrintHandlers{})
	p.Write(node, nil /*sourceFile*/, printer.SingleLineTextWriter)
	return printer.SingleLineTextWriter.getText()
}

// or

func nodeToStr(node *ast.Node, options CompilerOptions) {
	// Use own writer
	p := printer.NewPrinter(printer.PrinterOptions{ NewLine: options.NewLine}, printer.PrintHandlers{})
	return p.Emit(node, nil /*sourceFile*/)
}

Index

Constants

View Source
const (
	EFNone              EmitFlags = 0
	EFNoSourceMap                 = EFNoLeadingSourceMap | EFNoTrailingSourceMap             // Do not emit a source map location for this node.
	EFNoTokenSourceMaps           = EFNoTokenLeadingSourceMaps | EFNoTokenTrailingSourceMaps // Do not emit source map locations for tokens of this node.
	EFNoComments                  = EFNoLeadingComments | EFNoTrailingComments               // Do not emit comments for this node.
)
View Source
const (
	GeneratedIdentifierFlagsNone     = iota // Not automatically generated.
	GeneratedIdentifierFlagsAuto            // Automatically generated identifier.
	GeneratedIdentifierFlagsLoop            // Automatically generated identifier with a preference for '_i'.
	GeneratedIdentifierFlagsUnique          // Unique name based on the 'text' property.
	GeneratedIdentifierFlagsNode            // Unique name based on the node in the 'Node' property.
	GeneratedIdentifierFlagsKindMask = 7    // Mask to extract the kind of identifier from its flags.

	GeneratedIdentifierFlagsReservedInNestedScopes = 1 << 3 // Reserve the generated name in nested scopes
	GeneratedIdentifierFlagsOptimistic             = 1 << 4 // First instance won't use '_#' if there's no conflict
	GeneratedIdentifierFlagsFileLevel              = 1 << 5 // Use only the file identifiers list and not generated names to search for conflicts
	GeneratedIdentifierFlagsAllowNameSubstitution  = 1 << 6 // Used by `module.ts` to indicate generated nodes which can have substitutions performed upon them (as they were generated by an earlier transform phase)
)

Variables

This section is empty.

Functions

func FormatGeneratedName

func FormatGeneratedName(privateName bool, prefix string, base string, suffix string) string

func IsFileLevelUniqueName

func IsFileLevelUniqueName(sourceFile *ast.SourceFile, name string, hasGlobalName func(string) bool) bool

Types

type AutoGenerateId

type AutoGenerateId uint32

type AutoGenerateInfo

type AutoGenerateInfo struct {
	Flags  GeneratedIdentifierFlags // Specifies whether to auto-generate the text for an identifier.
	Id     AutoGenerateId           // Ensures unique generated identifiers get unique names, but clones get the same name.
	Prefix string                   // Optional prefix to apply to the start of the generated name
	Suffix string                   // Optional suffix to apply to the end of the generated name
	Node   *ast.Node                // For a GeneratedIdentifierFlagsNode, the node from which to generate an identifier
}

type AutoGenerateOptions

type AutoGenerateOptions struct {
	Flags  GeneratedIdentifierFlags
	Prefix string
	Suffix string
}

type EmitContext

type EmitContext struct {
	Factory *ast.NodeFactory // Required. The NodeFactory to use to create new nodes
	// contains filtered or unexported fields
}

Stores side-table information used during transformation that can be read by the printer to customize emit

NOTE: EmitContext is not guaranteed to be thread-safe.

func NewEmitContext

func NewEmitContext() *EmitContext

func (*EmitContext) AddEmitFlags

func (c *EmitContext) AddEmitFlags(node *ast.Node, flags EmitFlags)

func (*EmitContext) AddEmitHelper

func (c *EmitContext) AddEmitHelper(node *ast.Node, helper ...*EmitHelper)

func (*EmitContext) AddHoistedFunctionDeclaration

func (c *EmitContext) AddHoistedFunctionDeclaration(node *ast.FunctionDeclarationNode)

Adds a hoisted function declaration to the current VariableEnvironment

NOTE: This is the equivalent of `transformContext.hoistFunctionDeclaration` in Strada.

func (*EmitContext) AddLexicalDeclaration

func (c *EmitContext) AddLexicalDeclaration(name *ast.IdentifierNode)

Adds a `let` declaration to the current LexicalEnvironment.

func (*EmitContext) AddVariableDeclaration

func (c *EmitContext) AddVariableDeclaration(name *ast.IdentifierNode)

Adds a `var` declaration to the current VariableEnvironment

NOTE: This is the equivalent of `transformContext.hoistVariableDeclaration` in Strada.

func (*EmitContext) AssignCommentAndSourceMapRanges

func (c *EmitContext) AssignCommentAndSourceMapRanges(to *ast.Node, from *ast.Node)

Sets the range to use for a node when emitting comments and source maps.

func (*EmitContext) AssignCommentRange

func (c *EmitContext) AssignCommentRange(to *ast.Node, from *ast.Node)

Sets the range to use for a node when emitting comments.

func (*EmitContext) AssignSourceMapRange

func (c *EmitContext) AssignSourceMapRange(to *ast.Node, from *ast.Node)

Sets the range to use for a node when emitting source maps.

func (*EmitContext) CommentRange

func (c *EmitContext) CommentRange(node *ast.Node) core.TextRange

Gets the range to use for a node when emitting comments.

func (*EmitContext) EmitFlags

func (c *EmitContext) EmitFlags(node *ast.Node) EmitFlags

func (*EmitContext) EndAndMergeLexicalEnvironment

func (c *EmitContext) EndAndMergeLexicalEnvironment(statements []*ast.Statement) []*ast.Statement

Invokes c.EndLexicalEnvironment() and merges the results into `statements`

func (*EmitContext) EndAndMergeLexicalEnvironmentList

func (c *EmitContext) EndAndMergeLexicalEnvironmentList(statements *ast.StatementList) *ast.StatementList

Invokes c.EndLexicalEnvironment() and merges the results into `statements`

func (*EmitContext) EndAndMergeVariableEnvironment

func (c *EmitContext) EndAndMergeVariableEnvironment(statements []*ast.Statement) []*ast.Statement

Invokes c.EndVariableEnvironment() and merges the results into `statements`

func (*EmitContext) EndAndMergeVariableEnvironmentList

func (c *EmitContext) EndAndMergeVariableEnvironmentList(statements *ast.StatementList) *ast.StatementList

Invokes c.EndVariableEnvironment() and merges the results into `statements`

func (*EmitContext) EndLexicalEnvironment

func (c *EmitContext) EndLexicalEnvironment() []*ast.Statement

Ends the current EndLexicalEnvironment, returning a list of statements that should be emitted at the start of the current scope.

NOTE: This is the equivalent of `transformContext.endLexicalEnvironment` in Strada. NOTE: This is *not* the same as `endLexicalEnvironment` in Strada as that method is incorrectly named.

func (*EmitContext) EndVariableEnvironment

func (c *EmitContext) EndVariableEnvironment() []*ast.Statement

Ends the current VariableEnvironment, returning a list of statements that should be emitted at the start of the current scope.

NOTE: This is the equivalent of `transformContext.endLexicalEnvironment` in Strada.

func (*EmitContext) EnsureUseStrict

func (c *EmitContext) EnsureUseStrict(statements []*ast.Statement) []*ast.Statement

Ensures `"use strict"` is the first statement of a slice of statements.

func (*EmitContext) GetAutoGenerateInfo

func (c *EmitContext) GetAutoGenerateInfo(name *ast.MemberName) *AutoGenerateInfo

Gets the associated AutoGenerateInfo entry for a given name.

func (*EmitContext) GetEmitHelpers

func (c *EmitContext) GetEmitHelpers(node *ast.Node) []*EmitHelper

func (*EmitContext) GetExternalHelpersModuleName

func (c *EmitContext) GetExternalHelpersModuleName(node *ast.SourceFile) *ast.IdentifierNode

func (*EmitContext) GetNodeForGeneratedName

func (c *EmitContext) GetNodeForGeneratedName(name *ast.MemberName) *ast.Node

Walks the associated AutoGenerateInfo entries of a name to find the root Nopde from which the name should be generated.

func (*EmitContext) HasAutoGenerateInfo

func (c *EmitContext) HasAutoGenerateInfo(node *ast.MemberName) bool

Gets whether a given name has an associated AutoGenerateInfo entry.

func (*EmitContext) HasRecordedExternalHelpers

func (c *EmitContext) HasRecordedExternalHelpers(node *ast.SourceFile) bool

func (*EmitContext) MergeEnvironment

func (c *EmitContext) MergeEnvironment(statements []*ast.Statement, declarations []*ast.Statement) []*ast.Statement

Merges declarations produced by c.EndVariableEnvironment() or c.EndLexicalEnvironment() into a slice of statements

func (*EmitContext) MergeEnvironmentList

func (c *EmitContext) MergeEnvironmentList(statements *ast.StatementList, declarations []*ast.Statement) *ast.StatementList

Merges declarations produced by c.EndVariableEnvironment() or c.EndLexicalEnvironment() into a statement list

func (*EmitContext) MostOriginal

func (c *EmitContext) MostOriginal(node *ast.Node) *ast.Node

Gets the most original node associated with this node by walking Original pointers.

NOTE: This method is analogous to `getOriginalNode` in the old compiler, but the name has changed to avoid accidental conflation with `SetOriginal`/`Original`

func (*EmitContext) MoveEmitHelpers

func (c *EmitContext) MoveEmitHelpers(source *ast.Node, target *ast.Node, predicate func(helper *EmitHelper) bool)

func (*EmitContext) NewExportStarHelper

func (c *EmitContext) NewExportStarHelper(moduleExpression *ast.Expression, exportsExpression *ast.Expression) *ast.Expression

Allocates a new Call expression to the `__exportStar` helper.

func (*EmitContext) NewGeneratedNameForNode

func (c *EmitContext) NewGeneratedNameForNode(node *ast.Node, options AutoGenerateOptions) *ast.IdentifierNode

Allocates a new unique name based on the provided node.

func (*EmitContext) NewGeneratedPrivateNameForNode

func (c *EmitContext) NewGeneratedPrivateNameForNode(node *ast.Node, options AutoGenerateOptions) *ast.PrivateIdentifierNode

Allocates a new unique private name based on the provided node.

func (*EmitContext) NewImportDefaultHelper

func (c *EmitContext) NewImportDefaultHelper(expression *ast.Expression) *ast.Expression

Allocates a new Call expression to the `__importDefault` helper.

func (*EmitContext) NewImportStarHelper

func (c *EmitContext) NewImportStarHelper(expression *ast.Expression) *ast.Expression

Allocates a new Call expression to the `__importStar` helper.

func (*EmitContext) NewLoopVariable

func (c *EmitContext) NewLoopVariable(options AutoGenerateOptions) *ast.IdentifierNode

Allocates a new loop variable name.

func (*EmitContext) NewNodeVisitor

func (c *EmitContext) NewNodeVisitor(visit func(node *ast.Node) *ast.Node) *ast.NodeVisitor

Creates a new NodeVisitor attached to this EmitContext

func (*EmitContext) NewRewriteRelativeImportExtensionsHelper

func (c *EmitContext) NewRewriteRelativeImportExtensionsHelper(firstArgument *ast.Node, preserveJsx bool) *ast.Expression

Allocates a new Call expression to the `__rewriteRelativeImportExtension` helper.

func (*EmitContext) NewStringLiteralFromNode

func (c *EmitContext) NewStringLiteralFromNode(textSourceNode *ast.Node) *ast.Node

Allocates a new StringLiteral whose source text is derived from the provided node. This is often used to create a string representation of an Identifier or NumericLiteral.

func (*EmitContext) NewTempVariable

func (c *EmitContext) NewTempVariable(options AutoGenerateOptions) *ast.IdentifierNode

Allocates a new temp variable name, but does not record it in the environment. It is recommended to pass this to either `AddVariableDeclaration` or `AddLexicalDeclaration` to ensure it is properly tracked, if you are not otherwise handling it yourself.

func (*EmitContext) NewUniqueName

func (c *EmitContext) NewUniqueName(text string, options AutoGenerateOptions) *ast.IdentifierNode

Allocates a new unique name based on the provided text.

func (*EmitContext) NewUniquePrivateName

func (c *EmitContext) NewUniquePrivateName(text string, options AutoGenerateOptions) *ast.PrivateIdentifierNode

Allocates a new unique private name based on the provided text.

func (*EmitContext) NewUnscopedHelperName

func (c *EmitContext) NewUnscopedHelperName(name string) *ast.IdentifierNode

Allocates a new Identifier representing a reference to a helper function.

func (*EmitContext) Original

func (c *EmitContext) Original(node *ast.Node) *ast.Node

Gets the original node for a given node.

NOTE: This is the equivalent to reading `node.original` in Strada.

func (*EmitContext) ParseNode

func (c *EmitContext) ParseNode(node *ast.Node) *ast.Node

Gets the original parse tree node for a given node.

NOTE: This is the equivalent to `getParseTreeNode` in Strada.

func (*EmitContext) ReadEmitHelpers

func (c *EmitContext) ReadEmitHelpers() []*EmitHelper

func (*EmitContext) RequestEmitHelper

func (c *EmitContext) RequestEmitHelper(helper *EmitHelper)

func (*EmitContext) SetCommentRange

func (c *EmitContext) SetCommentRange(node *ast.Node, loc core.TextRange)

Sets the range to use for a node when emitting comments.

func (*EmitContext) SetEmitFlags

func (c *EmitContext) SetEmitFlags(node *ast.Node, flags EmitFlags)

func (*EmitContext) SetExternalHelpersModuleName

func (c *EmitContext) SetExternalHelpersModuleName(node *ast.SourceFile, name *ast.IdentifierNode)

func (*EmitContext) SetOriginal

func (c *EmitContext) SetOriginal(node *ast.Node, original *ast.Node)

Sets the original node for a given node.

NOTE: This is the equivalent to `setOriginalNode` in Strada.

func (*EmitContext) SetSourceMapRange

func (c *EmitContext) SetSourceMapRange(node *ast.Node, loc core.TextRange)

Sets the range to use for a node when emitting source maps.

func (*EmitContext) SetTokenSourceMapRange

func (c *EmitContext) SetTokenSourceMapRange(node *ast.Node, kind ast.Kind, loc core.TextRange)

Sets the range for a token of a node when emitting source maps.

func (*EmitContext) SourceMapRange

func (c *EmitContext) SourceMapRange(node *ast.Node) core.TextRange

Gets the range to use for a node when emitting source maps.

func (*EmitContext) SplitCustomPrologue

func (c *EmitContext) SplitCustomPrologue(source []*ast.Statement) (prologue []*ast.Statement, rest []*ast.Statement)

Splits a slice of statements into two parts: custom prologue statements (e.g., with `EFCustomPrologue` set) and the rest of the statements

func (*EmitContext) SplitStandardPrologue

func (c *EmitContext) SplitStandardPrologue(source []*ast.Statement) (prologue []*ast.Statement, rest []*ast.Statement)

Splits a slice of statements into two parts: standard prologue statements and the rest of the statements

func (*EmitContext) StartLexicalEnvironment

func (c *EmitContext) StartLexicalEnvironment()

Starts a new LexicalEnvironment used to track block-scoped `let`, `const`, and `using` declarations.

see: https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts

NOTE: This is the equivalent of `transformContext.startBlockScope` in Strada. NOTE: This is *not* the same as `startLexicalEnvironment` in Strada as that method is incorrectly named.

func (*EmitContext) StartVariableEnvironment

func (c *EmitContext) StartVariableEnvironment()

Starts a new VariableEnvironment used to track hoisted `var` statements and function declarations.

see: https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts

NOTE: This is the equivalent of `transformContext.startLexicalEnvironment` in Strada.

func (*EmitContext) TokenSourceMapRange

func (c *EmitContext) TokenSourceMapRange(node *ast.Node, kind ast.Kind) (core.TextRange, bool)

Gets the range for a token of a node when emitting source maps.

func (*EmitContext) VisitFunctionBody

func (c *EmitContext) VisitFunctionBody(node *ast.BlockOrExpression, visitor *ast.NodeVisitor) *ast.BlockOrExpression

func (*EmitContext) VisitIterationBody

func (c *EmitContext) VisitIterationBody(body *ast.Statement, visitor *ast.NodeVisitor) *ast.Statement

func (*EmitContext) VisitParameters

func (c *EmitContext) VisitParameters(nodes *ast.ParameterList, visitor *ast.NodeVisitor) *ast.ParameterList

func (*EmitContext) VisitVariableEnvironment

func (c *EmitContext) VisitVariableEnvironment(nodes *ast.StatementList, visitor *ast.NodeVisitor) *ast.StatementList

type EmitFlags

type EmitFlags uint32
const (
	EFSingleLine                EmitFlags = 1 << iota // The contents of this node should be emitted on a single line.
	EFMultiLine                                       // The contents of this node should be emitted on multiple lines.
	EFNoLeadingSourceMap                              // Do not emit a leading source map location for this node.
	EFNoTrailingSourceMap                             // Do not emit a trailing source map location for this node.
	EFNoNestedSourceMaps                              // Do not emit source map locations for children of this node.
	EFNoTokenLeadingSourceMaps                        // Do not emit leading source map location for token nodes.
	EFNoTokenTrailingSourceMaps                       // Do not emit trailing source map location for token nodes.
	EFNoLeadingComments                               // Do not emit leading comments for this node.
	EFNoTrailingComments                              // Do not emit trailing comments for this node.
	EFNoNestedComments                                // Do not emit nested comments for children of this node.
	EFHelperName                                      // The Identifier refers to an *unscoped* emit helper (one that is emitted at the top of the file)
	EFExportName                                      // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
	EFLocalName                                       // Ensure an export prefix is not added for an identifier that points to an exported declaration.
	EFInternalName                                    // The name is internal to an ES5 class body function.
	EFIndented                                        // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
	EFNoIndentation                                   // Do not indent the node.
	EFReuseTempVariableScope                          // Reuse the existing temp variable scope during emit.
	EFCustomPrologue                                  // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
	EFNoHoisting                                      // Do not hoist this declaration in --module system
	EFNoAsciiEscaping                                 // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions.
	EFExternalHelpers                                 // This source file has external helpers
	EFNeverApplyImportHelper                          // Do not apply an import helper to this node
	EFStartOnNewLine                                  // Start this node on a new line
	EFIndirectCall                                    // Emit CallExpression as an indirect call: `(0, f)()`
)

type EmitHelper

type EmitHelper struct {
	Name         string                                          // A unique name for this helper.
	Scoped       bool                                            // Indicates whether the helper MUST be emitted in the current scope.
	Text         string                                          // ES3-compatible raw script text
	TextCallback func(makeUniqueName func(string) string) string // A function yielding an ES3-compatible raw script text.
	Priority     *Priority                                       // Helpers with a higher priority are emitted earlier than other helpers on the node.
	Dependencies []*EmitHelper                                   // Emit helpers this helper depends on
	ImportName   string                                          // The name of the helper to use when importing via `--importHelpers`.
}

type EmitResolver

type EmitResolver interface {
	binder.ReferenceResolver
	IsReferencedAliasDeclaration(node *ast.Node) bool
	IsValueAliasDeclaration(node *ast.Node) bool
	IsTopLevelValueImportEqualsWithEntityName(node *ast.Node) bool
	MarkLinkedReferencesRecursively(file *ast.SourceFile)
	GetExternalModuleFileFromDeclaration(node *ast.Node) *ast.SourceFile
}

type EmitTextWriter

type EmitTextWriter interface {
	Write(s string)
	WriteTrailingSemicolon(text string)
	WriteComment(text string)
	WriteKeyword(text string)
	WriteOperator(text string)
	WritePunctuation(text string)
	WriteSpace(text string)
	WriteStringLiteral(text string)
	WriteParameter(text string)
	WriteProperty(text string)
	WriteSymbol(text string, symbol *ast.Symbol)
	WriteLine()
	WriteLineForce(force bool)
	IncreaseIndent()
	DecreaseIndent()
	Clear()
	String() string
	RawWrite(s string)
	WriteLiteral(s string)
	GetTextPos() int
	GetLine() int
	GetColumn() int
	GetIndent() int
	IsAtStartOfLine() bool
	HasTrailingComment() bool
	HasTrailingWhitespace() bool
}

Externally opaque interface for printing text

var SingleLineStringWriter EmitTextWriter = &singleLineStringWriter{}

func NewTextWriter

func NewTextWriter(newLine string) EmitTextWriter

type GeneratedIdentifierFlags

type GeneratedIdentifierFlags int

func (GeneratedIdentifierFlags) HasAllowNameSubstitution

func (f GeneratedIdentifierFlags) HasAllowNameSubstitution() bool

func (GeneratedIdentifierFlags) IsAuto

func (f GeneratedIdentifierFlags) IsAuto() bool

func (GeneratedIdentifierFlags) IsFileLevel

func (f GeneratedIdentifierFlags) IsFileLevel() bool

func (GeneratedIdentifierFlags) IsLoop

func (f GeneratedIdentifierFlags) IsLoop() bool

func (GeneratedIdentifierFlags) IsNode

func (f GeneratedIdentifierFlags) IsNode() bool

func (GeneratedIdentifierFlags) IsOptimistic

func (f GeneratedIdentifierFlags) IsOptimistic() bool

func (GeneratedIdentifierFlags) IsReservedInNestedScopes

func (f GeneratedIdentifierFlags) IsReservedInNestedScopes() bool

func (GeneratedIdentifierFlags) IsUnique

func (f GeneratedIdentifierFlags) IsUnique() bool

func (GeneratedIdentifierFlags) Kind

type ListFormat

type ListFormat int
const (
	LFNone ListFormat = 0

	// Line separators
	LFSingleLine    ListFormat = 0      // Prints the list on a single line (default).
	LFMultiLine     ListFormat = 1 << 0 // Prints the list on multiple lines.
	LFPreserveLines ListFormat = 1 << 1 // Prints the list using line preservation if possible.
	LFLinesMask     ListFormat = LFSingleLine | LFMultiLine | LFPreserveLines

	// Delimiters
	LFNotDelimited       ListFormat = 0      // There is no delimiter between list items (default).
	LFBarDelimited       ListFormat = 1 << 2 // Each list item is space-and-bar (" |") delimited.
	LFAmpersandDelimited ListFormat = 1 << 3 // Each list item is space-and-ampersand (" &") delimited.
	LFCommaDelimited     ListFormat = 1 << 4 // Each list item is comma (",") delimited.
	LFAsteriskDelimited  ListFormat = 1 << 5 // Each list item is asterisk ("\n *") delimited, used with JSDoc.
	LFDelimitersMask     ListFormat = LFBarDelimited | LFAmpersandDelimited | LFCommaDelimited | LFAsteriskDelimited

	LFAllowTrailingComma ListFormat = 1 << 6 // Write a trailing comma (",") if present.

	// Whitespace
	LFIndented             ListFormat = 1 << 7 // The list should be indented.
	LFSpaceBetweenBraces   ListFormat = 1 << 8 // Inserts a space after the opening brace and before the closing brace.
	LFSpaceBetweenSiblings ListFormat = 1 << 9 // Inserts a space between each sibling node.

	// Brackets/Braces
	LFBraces         ListFormat = 1 << 10 // The list is surrounded by "{" and "}".
	LFParenthesis    ListFormat = 1 << 11 // The list is surrounded by "(" and ")".
	LFAngleBrackets  ListFormat = 1 << 12 // The list is surrounded by "<" and ">".
	LFSquareBrackets ListFormat = 1 << 13 // The list is surrounded by "[" and "]".
	LFBracketsMask   ListFormat = LFBraces | LFParenthesis | LFAngleBrackets | LFSquareBrackets

	LFOptionalIfNil   ListFormat = 1 << 14 // Do not emit brackets if the list is nil.
	LFOptionalIfEmpty ListFormat = 1 << 15 // Do not emit brackets if the list is empty.
	LFOptional        ListFormat = LFOptionalIfNil | LFOptionalIfEmpty

	// Other
	LFPreferNewLine         ListFormat = 1 << 16 // Prefer adding a LineTerminator between synthesized nodes.
	LFNoTrailingNewLine     ListFormat = 1 << 17 // Do not emit a trailing NewLine for a MultiLine list.
	LFNoInterveningComments ListFormat = 1 << 18 // Do not emit comments between each node
	LFNoSpaceIfEmpty        ListFormat = 1 << 19 // If the literal is empty, do not add spaces between braces.
	LFSingleElement         ListFormat = 1 << 20
	LFSpaceAfterList        ListFormat = 1 << 21 // Add space after list

	// Precomputed Formats
	LFModifiers                    ListFormat = LFSingleLine | LFSpaceBetweenSiblings | LFNoInterveningComments | LFSpaceAfterList
	LFHeritageClauses              ListFormat = LFSingleLine | LFSpaceBetweenSiblings
	LFSingleLineTypeLiteralMembers ListFormat = LFSingleLine | LFSpaceBetweenBraces | LFSpaceBetweenSiblings
	LFMultiLineTypeLiteralMembers  ListFormat = LFMultiLine | LFIndented | LFOptionalIfEmpty

	LFSingleLineTupleTypeElements       ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine
	LFMultiLineTupleTypeElements        ListFormat = LFCommaDelimited | LFIndented | LFSpaceBetweenSiblings | LFMultiLine
	LFUnionTypeConstituents             ListFormat = LFBarDelimited | LFSpaceBetweenSiblings | LFSingleLine
	LFIntersectionTypeConstituents      ListFormat = LFAmpersandDelimited | LFSpaceBetweenSiblings | LFSingleLine
	LFObjectBindingPatternElements      ListFormat = LFSingleLine | LFAllowTrailingComma | LFSpaceBetweenBraces | LFCommaDelimited | LFSpaceBetweenSiblings | LFNoSpaceIfEmpty
	LFArrayBindingPatternElements       ListFormat = LFSingleLine | LFAllowTrailingComma | LFCommaDelimited | LFSpaceBetweenSiblings | LFNoSpaceIfEmpty
	LFObjectLiteralExpressionProperties ListFormat = LFPreserveLines | LFCommaDelimited | LFSpaceBetweenSiblings | LFSpaceBetweenBraces | LFIndented | LFBraces | LFNoSpaceIfEmpty
	LFImportAttributes                  ListFormat = LFPreserveLines | LFCommaDelimited | LFSpaceBetweenSiblings | LFSpaceBetweenBraces | LFIndented | LFBraces | LFNoSpaceIfEmpty
	LFArrayLiteralExpressionElements    ListFormat = LFPreserveLines | LFCommaDelimited | LFSpaceBetweenSiblings | LFAllowTrailingComma | LFIndented | LFSquareBrackets
	LFCommaListElements                 ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine
	LFCallExpressionArguments           ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine | LFParenthesis
	LFNewExpressionArguments            ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine | LFParenthesis | LFOptionalIfNil
	LFTemplateExpressionSpans           ListFormat = LFSingleLine | LFNoInterveningComments
	LFSingleLineBlockStatements         ListFormat = LFSpaceBetweenBraces | LFSpaceBetweenSiblings | LFSingleLine
	LFMultiLineBlockStatements          ListFormat = LFIndented | LFMultiLine
	LFVariableDeclarationList           ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine
	LFSingleLineFunctionBodyStatements  ListFormat = LFSingleLine | LFSpaceBetweenSiblings | LFSpaceBetweenBraces
	LFMultiLineFunctionBodyStatements   ListFormat = LFMultiLine
	LFClassHeritageClauses              ListFormat = LFSingleLine
	LFClassMembers                      ListFormat = LFIndented | LFMultiLine
	LFInterfaceMembers                  ListFormat = LFIndented | LFMultiLine
	LFEnumMembers                       ListFormat = LFCommaDelimited | LFIndented | LFMultiLine
	LFCaseBlockClauses                  ListFormat = LFIndented | LFMultiLine
	LFNamedImportsOrExportsElements     ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFAllowTrailingComma | LFSingleLine | LFSpaceBetweenBraces | LFNoSpaceIfEmpty
	LFJsxElementOrFragmentChildren      ListFormat = LFSingleLine | LFNoInterveningComments
	LFJsxElementAttributes              ListFormat = LFSingleLine | LFSpaceBetweenSiblings | LFNoInterveningComments
	LFCaseOrDefaultClauseStatements     ListFormat = LFIndented | LFMultiLine | LFNoTrailingNewLine | LFOptionalIfEmpty
	LFHeritageClauseTypes               ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine
	LFSourceFileStatements              ListFormat = LFMultiLine | LFNoTrailingNewLine
	LFDecorators                        ListFormat = LFMultiLine | LFOptional | LFSpaceAfterList
	LFTypeArguments                     ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine | LFAngleBrackets | LFOptional
	LFTypeParameters                    ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine | LFAngleBrackets | LFOptional
	LFParameters                        ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine | LFParenthesis
	LFSingleArrowParameter              ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine
	LFIndexSignatureParameters          ListFormat = LFCommaDelimited | LFSpaceBetweenSiblings | LFSingleLine | LFIndented | LFSquareBrackets
	LFJSDocComment                      ListFormat = LFMultiLine | LFAsteriskDelimited
	LFImportClauseEntries               ListFormat = LFImportAttributes // Deprecated: Use LFImportAttributes
)

type NameGenerator

type NameGenerator struct {
	Context                            *EmitContext
	IsFileLevelUniqueNameInCurrentFile func(string, bool) bool // callback for Printer.isFileLevelUniqueNameInCurrentFile
	GetTextOfNode                      func(*ast.Node) string  // callback for Printer.getTextOfNode
	// contains filtered or unexported fields
}

func (*NameGenerator) GenerateName

func (g *NameGenerator) GenerateName(name *ast.MemberName) string

Generate the text for a generated identifier or private identifier

func (*NameGenerator) PopScope

func (g *NameGenerator) PopScope(reuseTempVariableScope bool)

func (*NameGenerator) PushScope

func (g *NameGenerator) PushScope(reuseTempVariableScope bool)

type PrintHandlers

type PrintHandlers struct {
	// A hook used by the Printer when generating unique names to avoid collisions with
	// globally defined names that exist outside of the current source file.
	HasGlobalName func(name string) bool

	OnBeforeEmitNode     func(nodeOpt *ast.Node)
	OnAfterEmitNode      func(nodeOpt *ast.Node)
	OnBeforeEmitNodeList func(nodesOpt *ast.NodeList)
	OnAfterEmitNodeList  func(nodesOpt *ast.NodeList)
	OnBeforeEmitToken    func(nodeOpt *ast.TokenNode)
	OnAfterEmitToken     func(nodeOpt *ast.TokenNode)
}

type Printer

type Printer struct {
	PrintHandlers
	Options PrinterOptions
	// contains filtered or unexported fields
}

func NewPrinter

func NewPrinter(options PrinterOptions, handlers PrintHandlers, emitContext *EmitContext) *Printer

func (*Printer) Emit

func (p *Printer) Emit(node *ast.Node, sourceFile *ast.SourceFile) string

func (*Printer) EmitSourceFile

func (p *Printer) EmitSourceFile(sourceFile *ast.SourceFile) string

func (*Printer) Write

func (p *Printer) Write(node *ast.Node, sourceFile *ast.SourceFile, writer EmitTextWriter)

type PrinterOptions

type PrinterOptions struct {
	// RemoveComments                bool
	NewLine core.NewLineKind
	// OmitTrailingSemicolon         bool
	NoEmitHelpers bool
	// Module                        core.ModuleKind
	// ModuleResolution              core.ModuleResolutionKind
	// Target                        core.ScriptTarget
	// SourceMap                     bool
	// InlineSourceMap               bool
	// InlineSources                 bool
	OmitBraceSourceMapPositions bool
	// ExtendedDiagnostics           bool
	// OnlyPrintJsDocStyle           bool
	// NeverAsciiEscape              bool
	// StripInternal                 bool
	PreserveSourceNewlines bool
}

type Priority

type Priority struct {
	Value int
}

type WriteKind

type WriteKind int
const (
	WriteKindNone WriteKind = iota
	WriteKindKeyword
	WriteKindOperator
	WriteKindPunctuation
	WriteKindStringLiteral
	WriteKindParameter
	WriteKindProperty
	WriteKindComment
	WriteKindLiteral
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL