transpile

package
v0.2.16 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: BSD-3-Clause Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const ShellSpecial = "\\\"'`{}[]|&;<>$*?#()"

ShellSpecial are the chars, other than spaces, that the shell gives a meaning outside of quotes, which a backslash escapes.

Variables

View Source
var BackslashLiteral = runtime.GOOS == "windows"

BackslashLiteral is whether a backslash outside of quotes and Go code is a literal char, unless it escapes a char that the shell gives a meaning (see Escapes), such that it is the path separator, as in C:\Users and cmd\goal. It is set on Windows, where backslash is the path separator.

View Source
var ScriptImports = []string{
	`"cogentcore.org/lab/goal"`,
	`"cogentcore.org/lab/goal/goalib"`,
	`"cogentcore.org/lab/tensor"`,
	`_ "cogentcore.org/lab/tensor/tmath"`,
	`_ "cogentcore.org/lab/stats/stats"`,
	`_ "cogentcore.org/lab/stats/metric"`,
}

ScriptImports are the imports of the Go code of a Goal script, before goimports adds the others that it uses, and removes those that it does not use.

Functions

func AddQuotes

func AddQuotes(str string) string

AddQuotes surrounds given string with quotes, also escaping any contained quotes

func AddTensorFuncs added in v0.2.5

func AddTensorFuncs()

AddTensorFuncs grabs all tensor* package functions of the interpreter symbols (see tensorsymbols) and adds them to the `tensor.Funcs` map so we can properly convert symbols to either tensors or basic literals, depending on the arg types for the current function.

func EscapeQuotes

func EscapeQuotes(str string) string

EscapeQuotes replaces any " with \"

func Escapes added in v0.2.12

func Escapes(next rune) bool

Escapes returns whether a backslash outside of quotes and Go code escapes the given char that follows it (0 if none), as it always does, except with BackslashLiteral, when it only escapes spaces and the other ShellSpecial chars than backslash, and is otherwise literal.

func ExecWordIsCommand

func ExecWordIsCommand(f string) bool

ExecWordIsCommand returns true if given exec word is a command-like string (excluding any paths)

func ExecWords

func ExecWords(ln string) ([]string, error)

func TensorfsCommands added in v0.2.10

func TensorfsCommands() []string

TensorfsCommands returns the names of the commands that math mode runs on the tensorfs directories, such as ls and cd, sorted.

Types

type Error added in v0.2.5

type Error struct {

	// Line and Col are the 1-based line and column (in bytes) of the
	// error in the source code, 0 if not known.
	Line, Col int

	// Src is the source line of the error.
	Src string

	// Msg is the message of the error, without its position.
	Msg string

	// Err is the underlying error, if any.
	Err error
}

Error is an error in Goal code, at a position in its source code, such as an error of the Go code that it is transpiled to, at the position in the Goal code that it comes from.

func SourceError added in v0.2.5

func SourceError(sources [][]SourceLine, chunk, line, col int, msg string, err error) *Error

SourceError returns an Error at the given 1-based line and column of the given chunk of Go code (see State.Chunks) of the given SourceLines of all the chunks, at its position in the Goal source code: the line of the chunk, after the lines of the chunks before it.

func (*Error) CodeMessage added in v0.2.5

func (e *Error) CodeMessage() string

CodeMessage returns the message of the error, without its position.

func (*Error) CodePos added in v0.2.5

func (e *Error) CodePos() (line, col int)

CodePos returns the 1-based line and column of the error in the source code, which tools such as editors use to show where it is.

func (*Error) Error added in v0.2.5

func (e *Error) Error() string

Error returns the message of the error with its position, and the source line with a caret under the column of the error.

func (*Error) Unwrap added in v0.2.5

func (e *Error) Unwrap() error

type GoCode added in v0.2.13

type GoCode struct {

	// Code is the Go code.
	Code string

	// Lines are the lines of the Go code.
	Lines []string

	// Offset is the line of the Go code of the first line of the Goal
	// source: the number of lines of the header.
	Offset int

	// Source are the lines of the Goal source, with the map from the
	// columns of their Go code back to their own columns.
	Source []SourceLine

	// HasPackage is whether the Goal source has a package declaration.
	// Otherwise, it is a script, whose code is in a main function,
	// after the imports.
	HasPackage bool

	// Imports are the imports of the Go code of a script, as goimports
	// finds them, with a name before the path if it has one, such as _.
	Imports []string

	// Errors are the errors of transpiling the Goal source.
	Errors []*Error
}

GoCode is the Go code of a Goal file, as `goal build` makes it, but without formatting it, so that the Go code of each line of the Goal source is on its own line, after a header, with a map between the positions of the two. Tools for Go code, such as gofmt, goimports, and the Go language server (gopls), can then be used for Goal code, with their results mapped back to the Goal source, without parsing Goal.

func TranspileGo added in v0.2.13

func TranspileGo(src, gofile string, opts GoOptions) *GoCode

TranspileGo returns the Go code of the given Goal source, for the Go file of the given name (see GoCode).

func (*GoCode) GoLine added in v0.2.13

func (gc *GoCode) GoLine(ln int) int

GoLine returns the line of the Go code of the given line of the Goal source, or -1 if there is none.

func (*GoCode) NumSourceLines added in v0.2.13

func (gc *GoCode) NumSourceLines() int

NumSourceLines returns the number of lines of the Goal source.

func (*GoCode) SourceLine added in v0.2.13

func (gc *GoCode) SourceLine(ln int) int

SourceLine returns the line of the Goal source of the given line of the Go code, or -1 if there is none, as for the code that the transpiler adds before and after the code of the source, such as the imports.

func (*GoCode) ToGo added in v0.2.13

func (gc *GoCode) ToGo(pos textpos.Pos) (textpos.Pos, bool)

ToGo returns the position in the Go code of the given position in the Goal source, in lines and runes, and whether it has one.

func (*GoCode) ToGoal added in v0.2.13

func (gc *GoCode) ToGoal(pos textpos.Pos) (textpos.Pos, bool)

ToGoal returns the position in the Goal source of the given position in the Go code, in lines and runes, and whether it has one: the code that the transpiler adds before and after the code of the source, such as the imports, does not. A position at a space is after the token before it, as the spaces of the Go code are added around its tokens.

func (*GoCode) ToGoalRegion added in v0.2.13

func (gc *GoCode) ToGoalRegion(reg textpos.Region) (textpos.Region, bool)

ToGoalRegion returns the region in the Goal source of the given region in the Go code, and whether it has one, which it does if its start does.

type GoOptions added in v0.2.13

type GoOptions struct {

	// Header is the first line of the Go code, which is a comment.
	// The default is a comment that it is the Go code of a Goal file.
	Header string

	// FindImports is whether to find the imports of a script with
	// goimports, as `goal build` does. Otherwise, Imports are used.
	FindImports bool

	// Imports are the imports of a script that are used if FindImports
	// is not set, or if goimports fails, which it can for code with
	// errors. The default is [ScriptImports].
	Imports []string
}

GoOptions are the options for TranspileGo.

type SourceLine added in v0.2.5

type SourceLine struct {

	// Src is the Goal source line.
	Src string

	// Cols is the 1-based column in Src of each byte of the Go code,
	// 0 if not known (see [Tokens.CodeMap]).
	Cols []token.Pos
}

SourceLine is a line of Goal source code, with the map from the columns of the Go code that it is transpiled to back to its own columns, so that the errors of the Go code can be shown in the Goal source.

func (*SourceLine) SourceCol added in v0.2.5

func (sl *SourceLine) SourceCol(col int) int

SourceCol returns the 1-based column in the source line of the given 1-based column of its Go code, or 1 if it is not known.

type State

type State struct {
	// FuncToVar translates function definitions into variable definitions,
	// which is the default for interactive use of random code fragments
	// without the complete go formatting.
	// For pure transpiling of a complete codebase with full proper Go formatting
	// this should be turned off.
	FuncToVar bool

	// MathMode is on when math mode is turned on.
	MathMode bool

	// MathRecord is state of auto-recording of data into current directory
	// in math mode.
	MathRecord bool

	// depth of delim at the end of the current line. if 0, was complete.
	ParenDepth, BraceDepth, BrackDepth, TypeDepth, DeclDepth int

	// Chunks of code lines that are accumulated during Transpile,
	// each of which should be evaluated separately, to avoid
	// issues with contextual effects from import, package etc.
	Chunks []string

	// ChunkSources are the source lines of each of the Chunks,
	// for mapping the errors of their Go code back to the source.
	ChunkSources [][]SourceLine

	// current stack of transpiled lines, that are accumulated into
	// code Chunks.
	Lines []string

	// SourceLines are the source lines of each of the Lines.
	SourceLines []SourceLine

	// stack of runtime errors.
	Errors []error
	// contains filtered or unexported fields
}

State holds the transpiling state

func NewState

func NewState() *State

NewState returns a new transpiling state; mostly for testing

func (*State) AddChunk

func (st *State) AddChunk()

AddChunk adds current lines into a chunk of code that should be compiled separately.

func (*State) AddError

func (st *State) AddError(err error) error

AddError adds the given error to the error stack if it is non-nil, and calls the Cancel function if set, to stop execution. This is the main way that goal errors are handled. It also prints the error.

func (*State) AddLine

func (st *State) AddLine(ln string)

AddLine adds line on the stack

func (*State) Code

func (st *State) Code() string

Code returns the current transpiled lines, split into chunks that should be compiled separately.

func (*State) DepthError

func (st *State) DepthError() error

DepthError reports an error if any of the parsing depths are not zero, to be called at the end of transpiling a complete block of code.

func (*State) GoFile added in v0.2.13

func (st *State) GoFile(in, out, code string) ([]byte, error)

GoFile returns the Go code of the given code of the given input goal file, as State.TranspileFile writes it to the given output Go file, with any error, in which case the Go code is not formatted.

func (*State) ResetCode

func (st *State) ResetCode()

ResetCode resets the stack of transpiled code

func (*State) ResetDepth

func (st *State) ResetDepth()

ResetDepth resets the current depths to 0

func (*State) TotalDepth

func (st *State) TotalDepth() int

TotalDepth returns the sum of any unresolved paren, brace, or bracket depths.

func (*State) TranspileCode

func (st *State) TranspileCode(code string)

TranspileCode processes each line of given code, adding the results to the LineStack

func (*State) TranspileExec

func (st *State) TranspileExec(ewords []string, output bool) Tokens

TranspileExec returns transpiled tokens assuming Exec code, with the given bools indicating the type of run to execute.

func (*State) TranspileExecString

func (st *State) TranspileExecString(str string, output bool) Tokens

TranspileExecString returns transpiled tokens assuming Exec code, from a string, with the given bool indicating whether [Output] is needed.

func (*State) TranspileExecTokens

func (st *State) TranspileExecTokens(toks Tokens, code string, output bool) Tokens

TranspileExecTokens returns transpiled tokens assuming Exec code, from given tokens, with the given bool indicating whether [Output] is needed.

func (*State) TranspileFile

func (st *State) TranspileFile(in string, out string) error

TranspileFile transpiles the given input goal file to the given output Go file. If no existing package declaration is found, then package main and func main declarations are added. This also affects how functions are interpreted.

func (*State) TranspileGo

func (st *State) TranspileGo(toks Tokens, code string) Tokens

TranspileGo returns transpiled tokens assuming Go code. Unpacks any encapsulated shell or math expressions.

func (*State) TranspileGoNDimIndex

func (st *State) TranspileGoNDimIndex(toks Tokens, code string, gtoks *Tokens, idIdx, rbIdx int) int

TranspileGoNDimIndex processes an ident[*] sequence of tokens, translating it into a corresponding tensor Value or Set expression, if it is a multi-dimensional indexing expression which is not valid in Go, to support simple n-dimensional tensor indexing in Go (not math) mode. For 2 to 5 indexes it uses the fixed-arity methods, such as

x[i, j, k]      -> x.Value3D(int(i), int(j), int(k))
x[i, j, k] = v  -> x.Set3D(v, int(i), int(j), int(k))
x[i, j, k] += v -> x.SetAdd3D(v, int(i), int(j), int(k))
&x[i, j, k]     -> x.ValuePtr3D(int(i), int(j), int(k))

and the variadic Value, Set etc for more indexes. Gets the current sequence of toks tokens, where the ident starts at idIdx and the ] is at rbIdx. It puts the results in gtoks generated tokens. Returns a positive index to resume processing at, if it is actually an n-dimensional expr, and -1 if not, in which case the normal process resumes.

func (*State) TranspileGoRange

func (st *State) TranspileGoRange(toks Tokens, code string, start, end int) Tokens

TranspileGoRange returns transpiled tokens assuming Go code, for given start, end (exclusive) range of given tokens and code. In general the positions in the tokens applies to the _original_ code so you should just keep the original code string. However, this is needed for a specific case.

func (*State) TranspileLine

func (st *State) TranspileLine(code string) string

TranspileLine is the main function for parsing a single line of goal input, returning a new transpiled line of code that converts Exec code into corresponding Go function calls.

func (*State) TranspileLineTokens

func (st *State) TranspileLineTokens(code string) Tokens

TranspileLineTokens returns the tokens for the full line

func (*State) TranspileMath

func (st *State) TranspileMath(toks Tokens, code string, fullLine bool) Tokens

TranspileMath does math mode transpiling. fullLine indicates code should be full statement(s).

func (*State) UnclosedError added in v0.2.5

func (st *State) UnclosedError() error

UnclosedError returns an error for the last bracket of the code since State.ResetCode that is not closed, or nil if there is none: for complete code, such as that of a file, as opposed to the lines that an interactive shell transpiles one at a time, which can continue.

type Token

type Token struct {
	// Go token classification
	Tok token.Token

	// Literal string
	Str string

	// position in the original string.
	// this is only set for the original parse,
	// not for transpiled additions.
	Pos token.Pos
}

Token provides full data for one token

func NewToken

func NewToken(tok token.Token, str ...string) *Token

NewToken returns a new token, for generated tokens without Pos

func (*Token) IsBacktickString

func (tk *Token) IsBacktickString() bool

IsBacktickString returns true if the given STRING uses backticks

func (*Token) IsBracket

func (tk *Token) IsBracket() bool

IsBracket returns true if the given token is a bracket delimiter: paren, brace, bracket

func (*Token) IsGo

func (tk *Token) IsGo() bool

IsGo returns true if the given token is a Go Keyword or Comment

func (*Token) IsOp

func (tk *Token) IsOp() bool

IsOp returns true if the given token is an operator

func (*Token) IsPathDelim

func (tk *Token) IsPathDelim() bool

func (*Token) IsPathExtraDelim

func (tk *Token) IsPathExtraDelim() bool

func (*Token) IsValidExecIdent

func (tk *Token) IsValidExecIdent() bool

IsValidExecIdent returns true if the given token is a valid component of an Exec mode identifier

func (*Token) IsWord

func (tk *Token) IsWord() bool

IsWord returns true if the token is some kind of word-like entity, including IDENT, STRING, CHAR, or one of the Go keywords. This is for exec filtering.

func (*Token) String

func (tk *Token) String() string

String returns the string for the token

type Tokens

type Tokens []*Token

Tokens is a slice of Token

func TokensFromString

func TokensFromString(ln string) Tokens

Tokens converts the string into tokens

func (*Tokens) Add

func (tk *Tokens) Add(tok token.Token, str ...string) *Token

Add adds a new token, for generated tokens without Pos

func (*Tokens) AddMulti

func (tk *Tokens) AddMulti(tok ...token.Token)

AddMulti adds new basic tokens (not IDENT).

func (*Tokens) AddTokens

func (tk *Tokens) AddTokens(toks ...*Token) *Tokens

AddTokens adds given tokens to our list

func (Tokens) BracketDepths

func (tk Tokens) BracketDepths() (paren, brace, brack int)

BracketDepths returns the depths for the three bracket delimiters [paren, bracket, brace], based on unmatched right versions.

func (Tokens) Code

func (tk Tokens) Code() string

Code returns concatenated Str values of the tokens, to generate a surface-valid code string.

func (Tokens) CodeMap added in v0.2.5

func (tk Tokens) CodeMap() (string, []token.Pos)

CodeMap returns the code of the tokens, as Tokens.Code, and the position in the source of the token of each byte of it (see Token.Pos), for mapping a position in the code back to the source. A token that the transpiler adds has the position of the token before it, or 0 if none.

func (Tokens) Contains

func (tk Tokens) Contains(toks ...token.Token) bool

Contains returns true if the token string contains any of the given token(s)

func (*Tokens) DeleteLastComma

func (tk *Tokens) DeleteLastComma()

DeleteLastComma removes any final Comma. easier to generate and delete at the end

func (*Tokens) Insert

func (tk *Tokens) Insert(i int, tok token.Token, str ...string) *Token

Insert inserts a new token at given position

func (Tokens) IsAssignExpr

func (tk Tokens) IsAssignExpr() bool

IsAssignExpr checks if there are any Go assignment or define tokens outside of { } Go code.

func (Tokens) Last

func (tk Tokens) Last() *Token

Last returns the final token in the list

func (Tokens) ModeEnd

func (tk Tokens) ModeEnd() int

ModeEnd returns the position (or -1 if not found) for the next ILLEGAL mode token ($ or #) given the starting one that is at the 0 position of the current set of tokens.

func (Tokens) Path

func (tk Tokens) Path(idx0 bool) (string, int)

Path extracts a standard path or URL expression from the current list of tokens (starting at index 0), returning the path string and the number of tokens included in the path. Restricts processing to contiguous elements with no spaces! If it is not a path, returns nil string, 0

func (Tokens) ReplaceIdentAt

func (tk Tokens) ReplaceIdentAt(at int, str string, n int) Tokens

ReplaceIdentAt replaces an identifier spanning n tokens starting at given index, with a single identifier with given string. This is used in Exec mode for dealing with identifiers and paths that are separately-parsed by Go.

func (Tokens) RightMatching

func (tk Tokens) RightMatching() int

RightMatching returns the position (or -1 if not found) for the right matching [paren, bracket, brace] given the left one that is at the 0 position of the current set of tokens.

func (Tokens) String

func (tk Tokens) String() string

String is the stringer version which includes the token ID in addition to the string literal

type WordsError added in v0.2.5

type WordsError struct {
	// Pos is the byte offset of the error in the line, such as that of the
	// quote that starts an unterminated string.
	Pos int

	Msg string
}

WordsError is an error of ExecWords, such as an unterminated string, at a byte offset in the line.

func (*WordsError) Error added in v0.2.5

func (e *WordsError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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