github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/ast/localstat.go (about)

     1  package ast
     2  
     3  // LocalStat is a statement node representing the declaration / definition of a
     4  // list of local variables.
     5  type LocalStat struct {
     6  	Location
     7  	NameAttribs []NameAttrib
     8  	Values      []ExpNode
     9  }
    10  
    11  var _ Stat = LocalStat{}
    12  
    13  // NewLocalStat returns a LocalStat instance defining the given names with the
    14  // given values.
    15  func NewLocalStat(nameAttribs []NameAttrib, values []ExpNode) LocalStat {
    16  	loc := MergeLocations(nameAttribs[0], nameAttribs[len(nameAttribs)-1])
    17  	if len(values) > 0 {
    18  		loc = MergeLocations(loc, values[len(values)-1])
    19  	}
    20  	// Give a name to functions defined here if possible
    21  	for i, v := range values {
    22  		if i >= len(nameAttribs) {
    23  			break
    24  		}
    25  		f, ok := v.(Function)
    26  		if ok && f.Name == "" {
    27  			f.Name = nameAttribs[i].Name.Val
    28  			values[i] = f
    29  		}
    30  	}
    31  	return LocalStat{Location: loc, NameAttribs: nameAttribs, Values: values}
    32  }
    33  
    34  // ProcessStat uses the given StatProcessor to process the receiver.
    35  func (s LocalStat) ProcessStat(p StatProcessor) {
    36  	p.ProcessLocalStat(s)
    37  }
    38  
    39  // HWrite prints a tree representation of the node.
    40  func (s LocalStat) HWrite(w HWriter) {
    41  	w.Writef("local")
    42  	w.Indent()
    43  	for i, nameAttrib := range s.NameAttribs {
    44  		w.Next()
    45  		w.Writef("name_%d: %s", i, nameAttrib)
    46  	}
    47  	for i, val := range s.Values {
    48  		w.Next()
    49  		w.Writef("val_%d: ", i)
    50  		val.HWrite(w)
    51  	}
    52  	w.Dedent()
    53  }
    54  
    55  // LocalAttrib is the type of a local name attrib
    56  type LocalAttrib uint8
    57  
    58  // Valid values for LocalAttrib
    59  const (
    60  	NoAttrib    LocalAttrib = iota
    61  	ConstAttrib             // <const>, introduced in Lua 5.4
    62  	CloseAttrib             // <close>, introduced in Lua 5.4
    63  )
    64  
    65  // A NameAttrib is a name introduce by a local definition, together with an
    66  // optional attribute (in Lua 5.4 that is 'close' or 'const').
    67  type NameAttrib struct {
    68  	Location
    69  	Name   Name
    70  	Attrib LocalAttrib
    71  }
    72  
    73  // NewNameAttrib returns a new NameAttribe for the given name and attrib.
    74  func NewNameAttrib(name Name, attribName *Name, attrib LocalAttrib) NameAttrib {
    75  	loc := name.Location
    76  	if attribName != nil {
    77  		loc = MergeLocations(loc, attribName)
    78  
    79  	}
    80  	return NameAttrib{
    81  		Location: loc,
    82  		Name:     name,
    83  		Attrib:   attrib,
    84  	}
    85  }