Commit feba533eb2 for golang
commit feba533eb2328f8df71fd5f762057a7a508a3ef6
Author: Mark Freeman <mark@golang.org>
Date: Wed Dec 2 16:27:28 2026 -0500
cmd/compile/internal/contraire: guard typeExpr depth
This prevents infinite recursion for type expressions with a >1
branching factor.
Change-Id: Ibac59f819fec674f7d140618a63909db2e8be852
Reviewed-on: https://go-review.googlesource.com/c/go/+/869262
Auto-Submit: Mark Freeman <mark@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Griesemer <gri@google.com>
diff --git a/src/cmd/compile/internal/contraire/cfg.go b/src/cmd/compile/internal/contraire/cfg.go
index fd28cb44a0..e8948f26cf 100644
--- a/src/cmd/compile/internal/contraire/cfg.go
+++ b/src/cmd/compile/internal/contraire/cfg.go
@@ -7,6 +7,11 @@ package contraire
// Config defines the set of probabilities that Contraire will use while
// generating an AST.
type Config struct {
+ // Limits the maximum depth of type expressions. This is crucial for
+ // type expressions with a >1 branching factor to prevent infinite
+ // recursion (probabilistically).
+ TypeExprMaxDepth int
+
ConstDeclMaxCount int // [1, N]
TypeDeclMaxCount int // [1, N]
@@ -23,6 +28,8 @@ type Config struct {
// cfg is a reasonable default config.
var cfg = &Config{
+ TypeExprMaxDepth: 2,
+
ConstDeclMaxCount: 4,
TypeDeclMaxCount: 4,
diff --git a/src/cmd/compile/internal/contraire/gen.go b/src/cmd/compile/internal/contraire/gen.go
index af0e02254b..291c7ff6b2 100644
--- a/src/cmd/compile/internal/contraire/gen.go
+++ b/src/cmd/compile/internal/contraire/gen.go
@@ -18,8 +18,9 @@ type generator struct {
}
type state struct {
- constDecls []*constDecl
- typeDecls []*typeDecl
+ constDecls []*constDecl
+ typeDecls []*typeDecl
+ typeExprDepth int
}
func (g *generator) genProg() *prog {
@@ -91,10 +92,17 @@ func (g *generator) genConstLtrl() constExpr {
}
func (g *generator) genTypeExpr() typeExpr {
- return chooseCDF(
+ // Limit the branching depth of type expressions.
+ if g.s.typeExprDepth >= g.cfg.TypeExprMaxDepth {
+ return g.genTypeBasic()
+ }
+ g.s.typeExprDepth++
+ res := chooseCDF(
alt[typeExpr]{g.cfg.PTypeName, g.genTypeDeclName},
alt[typeExpr]{g.cfg.PTypeLtrl, g.genTypeLtrl},
)
+ g.s.typeExprDepth--
+ return res
}
func (g *generator) genTypeDeclName() typeExpr {