CodeSampleX

Пример

cel.dev/expr v0.24.0: Constant, Expr, ParsedExpr

Проверенный пример — golang cel.dev/expr v0.24.0: Constant, Expr, ParsedExpr. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:5f2494510c703d49dd2e8ef62a92dbaf505c15e12eb459a88104391d93b1d596

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-15

Кейс

HOW
Цель
verify pkg:golang/cel.dev/expr@v0.24.0
Пакеты
Символы
  • cel.dev/expr.Constant
  • cel.dev/expr.Expr
  • cel.dev/expr.ParsedExpr
  • cel.dev/expr.Type
  • cel.dev/expr.CheckedExpr
Окружение
go 1.26.6
Создан
2026-09-15T19:25:23Z

Контракт

  1. expr.Constant represents typed constant values such as bool, int64, and string
  2. expr.Expr constructs abstract syntax tree nodes for expressions including ident and call
  3. expr.ParsedExpr holds parsed expression AST and source info serializable via protobuf
  4. expr.Type defines primitive, list, and map type specifications
  5. expr.CheckedExpr associates AST nodes with resolved types and reference maps

Файлы

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:golang/cel.dev/expr@v0.24.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/cel.dev/expr@v0.24.0

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
contract_test.go
package sample_test

import (
	"testing"

	expr "cel.dev/expr"
	"google.golang.org/protobuf/proto"
)

func TestConstantConstruction(t *testing.T) {
	// 1. Construct constant values of different types
	boolConst := &expr.Constant{
		ConstantKind: &expr.Constant_BoolValue{BoolValue: true},
	}
	if !boolConst.GetBoolValue() {
		t.Fatal("expected GetBoolValue() to be true")
	}

	intConst := &expr.Constant{
		ConstantKind: &expr.Constant_Int64Value{Int64Value: 42},
	}
	if intConst.GetInt64Value() != 42 {
		t.Fatalf("expected GetInt64Value() == 42, got %d", intConst.GetInt64Value())
	}

	strConst := &expr.Constant{
		ConstantKind: &expr.Constant_StringValue{StringValue: "hello cel"},
	}
	if strConst.GetStringValue() != "hello cel" {
		t.Fatalf("expected GetStringValue() == 'hello cel', got %s", strConst.GetStringValue())
	}
}

func TestExprAstConstruction(t *testing.T) {
	// 2. Build an AST expression node: id == 1
	lhs := &expr.Expr{
		Id: 1,
		ExprKind: &expr.Expr_IdentExpr{
			IdentExpr: &expr.Expr_Ident{
				Name: "x",
			},
		},
	}
	rhs := &expr.Expr{
		Id: 2,
		ExprKind: &expr.Expr_ConstExpr{
			ConstExpr: &expr.Constant{
				ConstantKind: &expr.Constant_Int64Value{Int64Value: 100},
			},
		},
	}
	root := &expr.Expr{
		Id: 3,
		ExprKind: &expr.Expr_CallExpr{
			CallExpr: &expr.Expr_Call{
				Function: "_==_",
				Args:     []*expr.Expr{lhs, rhs},
			},
		},
	}

	call := root.GetCallExpr()
	if call == nil {
		t.Fatal("expected GetCallExpr() to return non-nil")
	}
	if call.GetFunction() != "_==_" {
		t.Fatalf("expected function '_==_', got %s", call.GetFunction())
	}
	if len(call.GetArgs()) != 2 {
		t.Fatalf("expected 2 args, got %d", len(call.GetArgs()))
	}
	if call.GetArgs()[0].GetIdentExpr().GetName() != "x" {
		t.Fatalf("expected arg[0] ident 'x', got %s", call.GetArgs()[0].GetIdentExpr().GetName())
	}
	if call.GetArgs()[1].GetConstExpr().GetInt64Value() != 100 {
		t.Fatalf("expected arg[1] const 100, got %d", call.GetArgs()[1].GetConstExpr().GetInt64Value())
	}
}

func TestParsedExprSerialization(t *testing.T) {
	// 3. Construct ParsedExpr and serialize/deserialize via protobuf
	parsed := &expr.ParsedExpr{
		Expr: &expr.Expr{
			Id: 1,
			ExprKind: &expr.Expr_ConstExpr{
				ConstExpr: &expr.Constant{
					ConstantKind: &expr.Constant_StringValue{StringValue: "sample"},
				},
			},
		},
		SourceInfo: &expr.SourceInfo{
			Location:    "sample.cel",
			LineOffsets: []int32{0, 10, 25},
			Positions: map[int64]int32{
				1: 0,
			},
		},
	}

	data, err := proto.Marshal(parsed)
	if err != nil {
		t.Fatalf("proto.Marshal failed: %v", err)
	}

	var unmarshaled expr.ParsedExpr
	if err := proto.Unmarshal(data, &unmarshaled); err != nil {
		t.Fatalf("proto.Unmarshal failed: %v", err)
	}

	if unmarshaled.GetSourceInfo().GetLocation() != "sample.cel" {
		t.Fatalf("expected location 'sample.cel', got %s", unmarshaled.GetSourceInfo().GetLocation())
	}
	if unmarshaled.GetExpr().GetConstExpr().GetStringValue() != "sample" {
		t.Fatalf("expected const value 'sample', got %s", unmarshaled.GetExpr().GetConstExpr().GetStringValue())
	}
}

func TestTypeConstruction(t *testing.T) {
	// 4. Construct primitive and composite Type definitions
	primitiveType := &expr.Type{
		TypeKind: &expr.Type_Primitive{
			Primitive: expr.Type_INT64,
		},
	}
	if primitiveType.GetPrimitive() != expr.Type_INT64 {
		t.Fatalf("expected Primitive INT64, got %v", primitiveType.GetPrimitive())
	}

	listType := &expr.Type{
		TypeKind: &expr.Type_ListType_{
			ListType: &expr.Type_ListType{
				ElemType: primitiveType,
			},
		},
	}
	if listType.GetListType() == nil || listType.GetListType().GetElemType().GetPrimitive() != expr.Type_INT64 {
		t.Fatal("expected ListType with INT64 element type")
	}

	mapType := &expr.Type{
		TypeKind: &expr.Type_MapType_{
			MapType: &expr.Type_MapType{
				KeyType: &expr.Type{
					TypeKind: &expr.Type_Primitive{
						Primitive: expr.Type_STRING,
					},
				},
				ValueType: primitiveType,
			},
		},
	}
	if mapType.GetMapType() == nil || mapType.GetMapType().GetKeyType().GetPrimitive() != expr.Type_STRING {
		t.Fatal("expected MapType with STRING key type")
	}
}

func TestCheckedExprConstruction(t *testing.T) {
	// 5. Construct CheckedExpr with TypeMap and ReferenceMap
	checked := &expr.CheckedExpr{
		Expr: &expr.Expr{
			Id: 1,
			ExprKind: &expr.Expr_IdentExpr{
				IdentExpr: &expr.Expr_Ident{Name: "authenticated"},
			},
		},
		TypeMap: map[int64]*expr.Type{
			1: {
				TypeKind: &expr.Type_Primitive{
					Primitive: expr.Type_BOOL,
				},
			},
		},
		ReferenceMap: map[int64]*expr.Reference{
			1: {
				Name: "authenticated",
			},
		},
		SourceInfo: &expr.SourceInfo{
			Location: "auth_rule.cel",
		},
	}

	if checked.GetTypeMap()[1].GetPrimitive() != expr.Type_BOOL {
		t.Fatalf("expected TypeMap[1] to be BOOL, got %v", checked.GetTypeMap()[1].GetPrimitive())
	}
	if checked.GetReferenceMap()[1].GetName() != "authenticated" {
		t.Fatalf("expected ReferenceMap[1] name 'authenticated', got %s", checked.GetReferenceMap()[1].GetName())
	}
}
csx.json
{"case":{"caseId":"case:sha256:43102c3e399776b929c0e08e01a9642e9e2d61cf21fb8d9e0b1f3f2e23394add","contract":["expr.Constant represents typed constant values such as bool, int64, and string","expr.Expr constructs abstract syntax tree nodes for expressions including ident and call","expr.ParsedExpr holds parsed expression AST and source info serializable via protobuf","expr.Type defines primitive, list, and map type specifications","expr.CheckedExpr associates AST nodes with resolved types and reference maps"],"goal":"verify pkg:golang/cel.dev/expr@v0.24.0","kind":"HOW","packages":["pkg:golang/cel.dev/expr@v0.24.0"],"schemaVersion":1,"symbols":["cel.dev/expr.Constant","cel.dev/expr.Expr","cel.dev/expr.ParsedExpr","cel.dev/expr.Type","cel.dev/expr.CheckedExpr"]},"contractCommand":["go","test","-v","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/cel.dev/expr@v0.24.0"],"schemaVersion":1,"subject":"pkg:golang/cel.dev/expr@v0.24.0","symbols":["cel.dev/expr.Constant","cel.dev/expr.Expr","cel.dev/expr.ParsedExpr","cel.dev/expr.Type","cel.dev/expr.CheckedExpr"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	cel.dev/expr v0.24.0
	google.golang.org/protobuf v1.34.2
)
go.sum
cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY=
cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/cel.dev/expr@v0.24.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/cel.dev/expr@v0.24.0"
  ]
}

Исходный сидер

аноним