github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/compiler/errors.go (about)

     1  package compiler
     2  
     3  // This file contains some utility functions related to error handling.
     4  
     5  import (
     6  	"go/token"
     7  	"go/types"
     8  	"path/filepath"
     9  
    10  	"tinygo.org/x/go-llvm"
    11  )
    12  
    13  // makeError makes it easy to create an error from a token.Pos with a message.
    14  func (c *compilerContext) makeError(pos token.Pos, msg string) types.Error {
    15  	return types.Error{
    16  		Fset: c.program.Fset,
    17  		Pos:  pos,
    18  		Msg:  msg,
    19  	}
    20  }
    21  
    22  // addError adds a new compiler diagnostic with the given location and message.
    23  func (c *compilerContext) addError(pos token.Pos, msg string) {
    24  	c.diagnostics = append(c.diagnostics, c.makeError(pos, msg))
    25  }
    26  
    27  // getPosition returns the position information for the given value, as far as
    28  // it is available.
    29  func getPosition(val llvm.Value) token.Position {
    30  	if !val.IsAInstruction().IsNil() {
    31  		loc := val.InstructionDebugLoc()
    32  		if loc.IsNil() {
    33  			return token.Position{}
    34  		}
    35  		file := loc.LocationScope().ScopeFile()
    36  		return token.Position{
    37  			Filename: filepath.Join(file.FileDirectory(), file.FileFilename()),
    38  			Line:     int(loc.LocationLine()),
    39  			Column:   int(loc.LocationColumn()),
    40  		}
    41  	} else if !val.IsAFunction().IsNil() {
    42  		loc := val.Subprogram()
    43  		if loc.IsNil() {
    44  			return token.Position{}
    45  		}
    46  		file := loc.ScopeFile()
    47  		return token.Position{
    48  			Filename: filepath.Join(file.FileDirectory(), file.FileFilename()),
    49  			Line:     int(loc.SubprogramLine()),
    50  		}
    51  	} else {
    52  		return token.Position{}
    53  	}
    54  }