go字符串拼接问题 | 初学者思考

166 阅读3分钟

字符串拼接问题

author : XiaSang

思维导图

image.png

语法树思考

"+"的定义

因为"+"存在歧义 有两种含义

// src/cmd/compile/internal/ir/node.go

const(
    // ...省略无关代码
    // expressions
	OADD          // X + Y
	OADDSTR       // +{List} (string addition, list elements are strings)
    // ...省略无关代码
)

开始扫描

// src/cmd/compile/internal/walk/expr.go

func walkExpr1(n ir.Node, init *ir.Nodes) ir.Node {
	switch n.Op() {
	default:
		ir.Dump("walk", n)
		base.Fatalf("walkExpr: switch 1 unknown op %+v", n.Op())
		panic("unreachable")
    // ...省略无关代码
    case ir.OADDSTR:
		return walkAddString(n.(*ir.AddStringExpr), init)
    }
    // ...省略无关代码
}

字符串拼接

// src/cmd/compile/internal/walk/expr.go

func walkAddString(n *ir.AddStringExpr, init *ir.Nodes) ir.Node {
	c := len(n.List)
    // 两个肯定是不需要进行拼接的
	if c < 2 {
		base.Fatalf("walkAddString count %d too small", c)
	}
    // 字符串拼接的结果不需要逃逸且添加之后不会溢出的话 
    // 创建临时的Stack缓冲buf
	buf := typecheck.NodNil()
	if n.Esc() == ir.EscNone {
		sz := int64(0)
		for _, n1 := range n.List {
			if n1.Op() == ir.OLITERAL {
				sz += int64(len(ir.StringVal(n1)))
			}
		}

		// Don't allocate the buffer if the result won't fit.
		if sz < tmpstringbufsize {
			// Create temporary buffer for result string on stack.
			buf = stackBufAddr(tmpstringbufsize, types.Types[types.TUINT8])
		}
	}

	// build list of string arguments 就是官方注释那样 
    // 构建字符串拼接的参数列表 
	args := []ir.Node{buf}
	for _, n2 := range n.List {
		args = append(args, typecheck.Conv(n2, types.Types[types.TSTRING]))
	}

    // 根据长度选择调用合适的函数 不过最后底层都是调用 concatstrings
	var fn string
	if c <= 5 {
		// small numbers of strings use direct runtime helpers.
		// note: order.expr knows this cutoff too.
		fn = fmt.Sprintf("concatstring%d", c)
	} else {
		// large numbers of strings are passed to the runtime as a slice.
		fn = "concatstrings"

		t := types.NewSlice(types.Types[types.TSTRING])
		// args[1:] to skip buf arg
		slice := ir.NewCompLitExpr(base.Pos, ir.OCOMPLIT, t, args[1:])
		slice.Prealloc = n.Prealloc
		args = []ir.Node{buf, slice}
		slice.SetEsc(ir.EscNone)
	}

    // 生成运行时函数的表达式 进行类型检查和遍历 并非重点
	cat := typecheck.LookupRuntime(fn)
	r := ir.NewCallExpr(base.Pos, ir.OCALL, cat, nil)
	r.Args = args
	r1 := typecheck.Expr(r)
	r1 = walkExpr(r1, init)
	r1.SetType(n.Type())

	return r1
}

真正的拼接才开始

以下所有代码来自于 src/runtime/string.go

给出一定的缓冲空间

// src/runtime/string.go

// The constant is known to the compiler.
// There is no fundamental theory behind this number.
const tmpStringBufSize = 32

type tmpBuf [tmpStringBufSize]byte

真正拼接的函数 concatstrings

// src/runtime/string.go

// concatstrings implements a Go string concatenation x+y+z+...
// The operands are passed in the slice a.
// If buf != nil, the compiler has determined that the result does not
// escape the calling function, so the string data can be stored in buf
// if small enough.
func concatstrings(buf *tmpBuf, a []string) string {
	idx := 0
	l := 0
	count := 0
	for i, x := range a {
		n := len(x)
		if n == 0 {
			continue
		}
		if l+n < l {
			throw("string concatenation too long")
		}
		l += n
		count++
		idx = i
	}
	if count == 0 {
		return ""
	}

	// If there is just one string and either it is not on the stack
	// or our result does not escape the calling frame (buf != nil),
	// then we can return that string directly.
	if count == 1 && (buf != nil || !stringDataOnStack(a[idx])) {
		return a[idx]
	}
    // 这个到最后就是纯纯的Copy即可
	s, b := rawstringtmp(buf, l)
	for _, x := range a {
		copy(b, x) 
		b = b[len(x):]
	}
	return s
}

分情况调用的 C<=5

// src/runtime/string.go
// fn = fmt.Sprintf("concatstring%d", c) 是这一句的调用

func concatstring2(buf *tmpBuf, a0, a1 string) string {
	return concatstrings(buf, []string{a0, a1})
}

func concatstring3(buf *tmpBuf, a0, a1, a2 string) string {
	return concatstrings(buf, []string{a0, a1, a2})
}

func concatstring4(buf *tmpBuf, a0, a1, a2, a3 string) string {
	return concatstrings(buf, []string{a0, a1, a2, a3})
}

func concatstring5(buf *tmpBuf, a0, a1, a2, a3, a4 string) string {
	return concatstrings(buf, []string{a0, a1, a2, a3, a4})
}

补充一下

rawstringtmp函数

// src/runtime/string.go

func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
    // 如果buff不空且长度足够的话 slicebytetostringtmp
	if buf != nil && l <= len(buf) {
		b = buf[:l]
		s = slicebytetostringtmp(&b[0], len(b))
	} else {
		// 否则分配内存
		s, b = rawstring(l)
	}
	return
}

rawstring函数

// src/runtime/string.go

// rawstring allocates storage for a new string. The returned
// string and byte slice both refer to the same storage.
// The storage is not zeroed. Callers should use
// b to set the string contents and then drop b.
func rawstring(size int) (s string, b []byte) {
	p := mallocgc(uintptr(size), nil, false)
	return unsafe.String((*byte)(p), size), unsafe.Slice((*byte)(p), size)
}

slicebytetostringtmp函数

// src/runtime/string.go

// slicebytetostringtmp returns a "string" referring to the actual []byte bytes.
// 简化一下官方文档
// 这段代码主要用于将字节切片转换为字符串
// 并在启用了 race、msan、asan 工具时进行相应的内存操作检测
// 这样的设计旨在在进行相关工具检测时提供更多的信息和保障
func slicebytetostringtmp(ptr *byte, n int) string {
	if raceenabled && n > 0 {
		racereadrangepc(unsafe.Pointer(ptr),
			uintptr(n),
			getcallerpc(),
			abi.FuncPCABIInternal(slicebytetostringtmp))
	}
	if msanenabled && n > 0 {
		msanread(unsafe.Pointer(ptr), uintptr(n))
	}
	if asanenabled && n > 0 {
		asanread(unsafe.Pointer(ptr), uintptr(n))
	}
	return unsafe.String(ptr, n)
}

参考文档

  1. go官方文档
  2. Go 语言设计与实现
  3. Go语言高级编程-微信读书