Documentation
¶
Index ¶
- Constants
- Variables
- func AddQuotes(str string) string
- func AddTensorFuncs()
- func EscapeQuotes(str string) string
- func Escapes(next rune) bool
- func ExecWordIsCommand(f string) bool
- func ExecWords(ln string) ([]string, error)
- func TensorfsCommands() []string
- type Error
- type GoCode
- func (gc *GoCode) GoLine(ln int) int
- func (gc *GoCode) NumSourceLines() int
- func (gc *GoCode) SourceLine(ln int) int
- func (gc *GoCode) ToGo(pos textpos.Pos) (textpos.Pos, bool)
- func (gc *GoCode) ToGoal(pos textpos.Pos) (textpos.Pos, bool)
- func (gc *GoCode) ToGoalRegion(reg textpos.Region) (textpos.Region, bool)
- type GoOptions
- type SourceLine
- type State
- func (st *State) AddChunk()
- func (st *State) AddError(err error) error
- func (st *State) AddLine(ln string)
- func (st *State) Code() string
- func (st *State) DepthError() error
- func (st *State) GoFile(in, out, code string) ([]byte, error)
- func (st *State) ResetCode()
- func (st *State) ResetDepth()
- func (st *State) TotalDepth() int
- func (st *State) TranspileCode(code string)
- func (st *State) TranspileExec(ewords []string, output bool) Tokens
- func (st *State) TranspileExecString(str string, output bool) Tokens
- func (st *State) TranspileExecTokens(toks Tokens, code string, output bool) Tokens
- func (st *State) TranspileFile(in string, out string) error
- func (st *State) TranspileGo(toks Tokens, code string) Tokens
- func (st *State) TranspileGoNDimIndex(toks Tokens, code string, gtoks *Tokens, idIdx, rbIdx int) int
- func (st *State) TranspileGoRange(toks Tokens, code string, start, end int) Tokens
- func (st *State) TranspileLine(code string) string
- func (st *State) TranspileLineTokens(code string) Tokens
- func (st *State) TranspileMath(toks Tokens, code string, fullLine bool) Tokens
- func (st *State) UnclosedError() error
- type Token
- func (tk *Token) IsBacktickString() bool
- func (tk *Token) IsBracket() bool
- func (tk *Token) IsGo() bool
- func (tk *Token) IsOp() bool
- func (tk *Token) IsPathDelim() bool
- func (tk *Token) IsPathExtraDelim() bool
- func (tk *Token) IsValidExecIdent() bool
- func (tk *Token) IsWord() bool
- func (tk *Token) String() string
- type Tokens
- func (tk *Tokens) Add(tok token.Token, str ...string) *Token
- func (tk *Tokens) AddMulti(tok ...token.Token)
- func (tk *Tokens) AddTokens(toks ...*Token) *Tokens
- func (tk Tokens) BracketDepths() (paren, brace, brack int)
- func (tk Tokens) Code() string
- func (tk Tokens) CodeMap() (string, []token.Pos)
- func (tk Tokens) Contains(toks ...token.Token) bool
- func (tk *Tokens) DeleteLastComma()
- func (tk *Tokens) Insert(i int, tok token.Token, str ...string) *Token
- func (tk Tokens) IsAssignExpr() bool
- func (tk Tokens) Last() *Token
- func (tk Tokens) ModeEnd() int
- func (tk Tokens) Path(idx0 bool) (string, int)
- func (tk Tokens) ReplaceIdentAt(at int, str string, n int) Tokens
- func (tk Tokens) RightMatching() int
- func (tk Tokens) String() string
- type WordsError
Constants ¶
const ShellSpecial = "\\\"'`{}[]|&;<>$*?#()"
ShellSpecial are the chars, other than spaces, that the shell gives a meaning outside of quotes, which a backslash escapes.
Variables ¶
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.
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 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 Escapes ¶ added in v0.2.12
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 ¶
ExecWordIsCommand returns true if given exec word is a command-like string (excluding any paths)
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
CodeMessage returns the message of the error, without its position.
func (*Error) CodePos ¶ added in v0.2.5
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.
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
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
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
NumSourceLines returns the number of lines of the Goal source.
func (*GoCode) SourceLine ¶ added in v0.2.13
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
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
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.
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 (*State) AddChunk ¶
func (st *State) AddChunk()
AddChunk adds current lines into a chunk of code that should be compiled separately.
func (*State) AddError ¶
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) Code ¶
Code returns the current transpiled lines, split into chunks that should be compiled separately.
func (*State) DepthError ¶
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
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) TotalDepth ¶
TotalDepth returns the sum of any unresolved paren, brace, or bracket depths.
func (*State) TranspileCode ¶
TranspileCode processes each line of given code, adding the results to the LineStack
func (*State) TranspileExec ¶
TranspileExec returns transpiled tokens assuming Exec code, with the given bools indicating the type of run to execute.
func (*State) TranspileExecString ¶
TranspileExecString returns transpiled tokens assuming Exec code, from a string, with the given bool indicating whether [Output] is needed.
func (*State) TranspileExecTokens ¶
TranspileExecTokens returns transpiled tokens assuming Exec code, from given tokens, with the given bool indicating whether [Output] is needed.
func (*State) TranspileFile ¶
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 ¶
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 ¶
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 ¶
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 ¶
TranspileLineTokens returns the tokens for the full line
func (*State) TranspileMath ¶
TranspileMath does math mode transpiling. fullLine indicates code should be full statement(s).
func (*State) UnclosedError ¶ added in v0.2.5
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 (*Token) IsBacktickString ¶
IsBacktickString returns true if the given STRING uses backticks
func (*Token) IsBracket ¶
IsBracket returns true if the given token is a bracket delimiter: paren, brace, bracket
func (*Token) IsPathDelim ¶
func (*Token) IsPathExtraDelim ¶
func (*Token) IsValidExecIdent ¶
IsValidExecIdent returns true if the given token is a valid component of an Exec mode identifier
type Tokens ¶
type Tokens []*Token
Tokens is a slice of Token
func TokensFromString ¶
Tokens converts the string into tokens
func (Tokens) BracketDepths ¶
BracketDepths returns the depths for the three bracket delimiters [paren, bracket, brace], based on unmatched right versions.
func (Tokens) Code ¶
Code returns concatenated Str values of the tokens, to generate a surface-valid code string.
func (Tokens) CodeMap ¶ added in v0.2.5
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 ¶
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) IsAssignExpr ¶
IsAssignExpr checks if there are any Go assignment or define tokens outside of { } Go code.
func (Tokens) ModeEnd ¶
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 ¶
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 ¶
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 ¶
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.
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