Source file src/cmd/compile/internal/contraire/vis.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package contraire
     6  
     7  import "strings"
     8  
     9  // scorer is a visitor that computes a complexity score of an AST.
    10  type scorer struct{ acc int }
    11  
    12  func (s *scorer) score(n node) int {
    13  	s.visit(n)
    14  	res := s.acc
    15  	s.acc = 0
    16  	return res
    17  }
    18  
    19  func (s *scorer) visit(n node) { n.receive(s) }
    20  func (s *scorer) visitProg(x *prog) {
    21  	for _, d := range x.decls {
    22  		s.visit(d)
    23  	}
    24  }
    25  func (s *scorer) visitConstDecl(x *constDecl)     { s.visit(x.expr) }
    26  func (s *scorer) visitTypeDecl(x *typeDecl)       { s.visit(x.expr) }
    27  func (s *scorer) visitConstName(x *constName)     { s.acc++ }
    28  func (s *scorer) visitConstLtrl(x *constLtrl)     { s.acc++ }
    29  func (s *scorer) visitTypeName(x *typeName)       { s.acc++ }
    30  func (s *scorer) visitTypeBasic(x *typeBasic)     { s.acc++ }
    31  func (s *scorer) visitTypePointer(x *typePointer) { s.acc++; s.visit(x.expr) }
    32  
    33  // printer is a visitor that produces a string representation of an AST.
    34  type printer struct{ acc strings.Builder }
    35  
    36  func (p *printer) print(n node) string {
    37  	p.visit(n)
    38  	res := p.acc.String()
    39  	p.acc.Reset()
    40  	return res
    41  }
    42  
    43  func (p *printer) visit(n node) { n.receive(p) }
    44  func (p *printer) visitProg(x *prog) {
    45  	p.acc.WriteString("package p\n\n")
    46  	for _, d := range x.decls {
    47  		p.visit(d)
    48  		p.acc.WriteString("\n")
    49  	}
    50  }
    51  func (p *printer) visitConstDecl(x *constDecl) {
    52  	p.acc.WriteString("const ")
    53  	p.acc.WriteString(x.name)
    54  	p.acc.WriteString(" = ")
    55  	p.visit(x.expr)
    56  }
    57  func (p *printer) visitTypeDecl(x *typeDecl) {
    58  	p.acc.WriteString("type ")
    59  	p.acc.WriteString(x.name)
    60  	p.acc.WriteString(" ")
    61  	p.visit(x.expr)
    62  }
    63  func (p *printer) visitConstName(x *constName)     { p.acc.WriteString(x.name) }
    64  func (p *printer) visitConstLtrl(x *constLtrl)     { p.acc.WriteString("1") }
    65  func (p *printer) visitTypeName(x *typeName)       { p.acc.WriteString(x.name) }
    66  func (p *printer) visitTypeBasic(x *typeBasic)     { p.acc.WriteString("int") }
    67  func (p *printer) visitTypePointer(x *typePointer) { p.acc.WriteString("*"); p.visit(x.expr) }
    68  

View as plain text