github.com/jmigpin/editor@v1.6.0/util/parseutil/lrparser/fileset.go (about)

     1  package lrparser
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  
     7  	"github.com/jmigpin/editor/util/parseutil"
     8  )
     9  
    10  // TODO: multiple files (working for single file only)
    11  type FileSet struct {
    12  	Src      []byte // currently, just a single src
    13  	Filename string // for errors only
    14  }
    15  
    16  func NewFileSetFromBytes(src []byte) *FileSet {
    17  	return &FileSet{Src: src, Filename: "<bytes>"}
    18  }
    19  
    20  //----------
    21  
    22  //func (fset *FileSet) SliceFrom(i int) []byte {
    23  //	// TODO: implemented for single file only (need node arg?)
    24  //	return fset.src[i:]
    25  //}
    26  //func (fset *FileSet) SliceTo(i int) []byte {
    27  //	// TODO: implemented for single file only (need node arg?)
    28  //	return fset.src[:i]
    29  //}
    30  
    31  func (fset *FileSet) NodeBytes(node PNode) []byte {
    32  	return fset.Src[node.Pos():node.End()]
    33  }
    34  func (fset *FileSet) NodeString(node PNode) string {
    35  	return string(fset.Src[node.Pos():node.End()])
    36  }
    37  func (fset *FileSet) NodeInt(node PNode) (int, error) {
    38  	s := fset.NodeString(node)
    39  	v, err := strconv.ParseInt(s, 10, 64)
    40  	if err != nil {
    41  		return 0, err
    42  	}
    43  	return int(v), nil
    44  }
    45  
    46  //----------
    47  
    48  func (fset *FileSet) Error(err error) error {
    49  	if pe, ok := err.(*PosError); ok {
    50  		return fset.Error2(pe, pe.Pos)
    51  	}
    52  	return fmt.Errorf("%s: %v", fset.Filename, err)
    53  }
    54  func (fset *FileSet) Error2(err error, index int) error {
    55  	line, col := parseutil.IndexLineColumn2(fset.Src, index)
    56  	str := parseutil.SurroundingString(fset.Src, index, 20)
    57  	return fmt.Errorf("%s:%d:%d: %v: %q", fset.Filename, line, col, err, str)
    58  }