kconfig

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 3, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

kconfig-go

Go Reference

English | 中文

纯 Go、仅依赖标准库的 Linux Kconfig 解析与求值库。

kconfig-go 将一个受控根目录中的 Kconfig 文件树加载为不可变 Project,对调用方提交的部分配置进行语义求值和归一化,并生成适合 Web、桌面端或其他前端直接渲染的动态菜单树。它也可以将已归一化的状态输出为 Linux .config,或将定义写为规范化 Kconfig 文本。

设计目标:让调用方不必自行实现 Kconfig 的依赖、choice、三态、菜单可见性和默认值逻辑;前端只提交 symbol 值并替换库返回的完整动态树。

特性

  • 支持 mainmenu、menu、config、menuconfig、choice、if、comment 等常用结构。
  • 支持 source、rsource、osource、orsource 多文件包含,检测包含循环并拒绝越出项目根目录的路径。
  • 支持 bool、tristate、string、int、hex,以及 default、range、select、imply、optional、def_bool、def_tristate、option modules 等常用属性。
  • 支持 symbol 引用、!、&&、||、比较和括号表达式,以及 n / m / y 三态逻辑。
  • 通过固定点求值使默认值、依赖、关系和 choice 约束收敛;不合法输入会回退到当前语义上下文中的有效值,并产生可解释的 Change。
  • 输出静态 Schema 和动态 FrontendTree:同一个 symbol 的多处声明保有不同的菜单入口 ID。
  • 支持动态菜单/menuconfig 屏幕导航;已隐藏的目标屏幕会安全回退到最近可见祖先。
  • 提供单值 Validate,可在不改变状态的前提下取得当前约束、可选值和建议值。
  • 提供稳定排序的 Linux .config 写出和规范化 Kconfig 写出。
  • 变量展开只接受调用方显式提供的 $(NAME) / ${NAME} 值;shell 或其他宏不会执行。

安装

go get github.com/Kirizu-Official/kconfig-go

项目当前在 go.mod 中声明 Go 1.26.1。

快速开始

下面的示例加载一个 Kconfig 根文件,选择一个目标架构,然后把局部编辑应用回现有状态:

package main

import (
    "context"
    "errors"
    "fmt"
    "io/fs"

    kconfig "github.com/Kirizu-Official/kconfig-go"
)

func main() {
    project, diagnostics, err := kconfig.Load(context.Background(), "Kconfig", kconfig.LoadOptions{
        Root: "/work/firmware",
        Variables: map[string]string{
            "ARCH": "arm",
        },
    })
    if err != nil {
        panic(err)
    }
    if diagnostics.HasErrors() {
        for _, diagnostic := range diagnostics {
            if errors.Is(diagnostic, kconfig.ErrSourceRead) {
                var pathError *fs.PathError
                if errors.As(diagnostic, &pathError) {
                    fmt.Printf("读取 %s 失败:%v\n", pathError.Path, pathError.Err)
                }
            }
        }
        panic(diagnostics.Error())
    }

    resolved := project.Resolve(kconfig.FrontendInput{Values: map[string]any{
        "MACH_STM32":     true,
        "MACH_STM32F103": true,
    }})

    // 每次前端编辑只提交发生变化的 symbol;随后使用完整的新 Tree 刷新界面。
    resolved = project.Apply(resolved.State, kconfig.FrontendInput{Values: map[string]any{
        "FLASH_SIZE": "0x20000",
    }})

    configText, err := kconfig.WriteConfig(resolved.State)
    if err != nil {
        panic(err)
    }
    fmt.Print(configText)
}

典型工作流

flowchart LR
    A["Kconfig 文件树"] --> B["Load"]
    B --> C["不可变 Project"]
    C --> D["Schema: 静态目录"]
    C --> E["Resolve / Apply"]
    E --> F["ConfigState: 合法状态"]
    E --> G["FrontendTree: 动态菜单"]
    F --> H["WriteConfig"]
    C --> I["WriteKconfig"]
1. 加载:Load

Load(ctx, entry, LoadOptions) 递归加载入口文件及其 include,解析为 AST 并构建语义索引。

  • LoadOptions.Root 是所有默认文件加载的安全根目录。
  • 未传 Loader 时使用 FSLoader 从文件系统读取。
  • 需要嵌入资源、数据库或虚拟文件系统时,实现 SourceLoader 即可。
  • 包含路径会被清理并限制在 Root 下;循环、缺失文件或语法错误会出现在 Diagnostics 中。
  • Variables 只提供安全的文本替换。未定义变量、$(shell,...) 与不受支持的宏会产生错误诊断,绝不执行宿主命令。

加载成功后,Project 可以被多个调用方并发地用于 Resolve;它不保存某个用户的可变配置。

错误分类与来源

库保留两条错误通道:Load、JSON 编解码和 writer 的普通 Go error,以及可定位 Kconfig 源码问题的结构化 Diagnostics。两者都不需要以字符串判断类型:

  • ErrorCode 是稳定、可序列化的精确分类;单个诊断通过 Diagnostic.Code 暴露它。
  • Err... 是与分类一一对应的哨兵变量,适合 errors.Is,例如 errors.Is(diagnostic, kconfig.ErrIncludeEscape)。
  • Diagnostic.Span 标识 Kconfig 源码位置;Diagnostic.Cause 保留 loader 等外部来源。 对 Diagnostic 或普通 Error 使用 errors.As 可以恢复 *fs.PathError、JSON 错误或调用方自定义 loader 错误。
  • 普通库错误是 *kconfig.Error,同样包含 Code、Message 和可解包的 Cause。

错误分类覆盖解析/表达式、值和 JSON、加载与宏、索引、求值/校验,以及 writer 状态。常见对照为: ErrorCodeSourceRead / ErrSourceRead、ErrorCodeInvalidValue / ErrInvalidValue、 ErrorCodeInvalidJSONValue / ErrInvalidJSONValue。显示给用户时仍应使用 Message 和 Span;业务分支应使用 Code 或 errors.Is,而不是匹配错误文本。

2. 静态目录:Project.Schema

Schema 是可缓存的静态信息,包含 symbol、菜单入口和屏幕的稳定 ID、类型与源码位置。它适用于前端建立表单元数据或按 ID 查询,但不能决定当前是否可见或可编辑。

请注意两个不同的 ID:

字段 含义 前端用途
Node.ID 一个菜单声明入口的稳定 ID 渲染与定位同一 symbol 的多个菜单位置
Node.SymbolID 配置 symbol 的稳定 ID FrontendInput.Values 的 key
Screen.ID 可进入 menu 或 menuconfig 的稳定 ID 传给 OpenScreen 进行导航
3. 求值与局部编辑:Resolve / Apply

Resolve 接收可空、部分的 FrontendInput,填充默认值并运行固定点求值。Apply 从已有 ConfigState 保留合法用户值,只合并当前局部补丁,然后重新运行同一套语义流程。提交值使用原生标量,而不是调用方构造的 Value;库根据 symbol 的已声明类型执行转换。

Symbol 类型 FrontendInput.Values / Validate 的输入形式 示例
bool Go / JSON bool true
tristate 字符串 "n"、"m" 或 "y"
string 字符串 "board-a"
int 整数;也接受 JSON 解码后的整数 float64 和 json.Number 250000
hex 十六进制字符串 "0x20000"

类型不匹配、非整数的数值或非法十六进制文本不会绕过语义规则:Resolve / Apply 将该项回退到当前有效默认值,并在 Changes 和 warning 诊断中说明原因;Validate 则返回建议值而不修改状态。

结果 Resolution 包含:

  • State:已归一化的 ConfigState;通过 Value(symbolID) 或副本 Values() 读取;
  • Tree:当前状态下完整的动态 FrontendTree;
  • Changes:每个输入或归一化项的 Accepted、Normalized、Fallback 或 Ignored 结果;
  • Diagnostics:语义和输入相关的诊断。

前端编辑后应使用 Apply 返回的完整树替换旧树。依赖条件变化会让菜单、menuconfig 子屏幕和条目出现或隐藏,前端不应凭局部字段自行推断这些变化。

4. 渲染、导航与验证
// 默认不包含隐藏节点;后台管理或诊断界面可显式保留它们。
tree := project.Render(state, kconfig.RenderOptions{IncludeHidden: true})

// 对已失效的 screen ID,OpenScreen 会返回最近的可见祖先或根屏幕。
screen := project.OpenScreen(state, tree.RootScreenID, kconfig.RenderOptions{})

// Validate 不会修改 state,可用于编辑器的即时校验和约束提示。
result := project.Validate(state, "FLASH_SIZE", "0x20000")
_ = screen
_ = result

Node.Visible 表示是否应显示,Node.Enabled 表示用户此刻是否可以直接赋值。它们都是当前状态的派生值,不能由客户端直接覆写。Constraints 提供当前 range、bool/tristate 可选值或 choice 候选项;StateReason 解释隐藏、禁用或回退的原因。

5. 写出配置
configText, err := kconfig.WriteConfig(state)
kconfigText, err := kconfig.WriteKconfig(project)
  • WriteConfig 按 symbol 名稳定排序。禁用的 bool/tristate 使用 Linux 惯例:# CONFIG_FOO is not set。
  • WriteKconfig 会将已加载的 include 树展平为规范化定义文本。
  • 两者都不是格式保留型 round-trip:原始空行、注释位置、属性顺序和缩进不会被保留。

值与 JSON

Value 是库内部状态、动态树、约束、校验建议值和写出结果所使用的带类型联合值。调用方提交配置时不需要构造 Value,而是使用与前端 JSON 一致的标量:

input := kconfig.FrontendInput{Values: map[string]any{
    "ENABLE":     true,
    "DRIVER_MODE": "m",
    "NAME":       "board-a",
    "BAUD":       250000,
    "FLASH_SIZE": "0x20000",
}}

Value 的 JSON 表示也保持前端友好:bool 为 JSON boolean,tristate 为 "n" / "m" / "y",string 为 JSON string,int 为 JSON number,hex 为规范化十六进制字符串。读取 Node.Value、Constraints 或 ValidationResult.Normalized 时,类型已经由库保留;如需单独反序列化 Value,可先用 schema 类型初始化 ZeroValue(type),再解码。

源码模块

模块 作用
project.go 公开加载入口、LoadOptions 与不可变 Project 容器。
source.go SourceLoader / FSLoader、安全根目录检查、include 遍历、变量展开和循环检测。
ast.go AST、源码文档、菜单入口、默认值、范围和关系等核心语法数据模型。
parser.go Kconfig 文档解析、逻辑续行、块结构恢复、属性解析和源码诊断。
token.go、expr.go 表达式 token、解析和 bool/tristate 三态求值。
index.go 将 AST 合并为 symbol、菜单、choice 与 screen 索引,并生成稳定入口 ID。
schema.go 从索引投影供客户端缓存的静态 Schema。
value.go Value / ValueType / TriState、字面量解析、规范化字符串和 JSON 编解码。
resolve.go Resolve / Apply、配置状态、副本保护、固定点求值、默认值与输入归一化。
relations.go select、imply、choice 互斥和默认成员规则。
render.go 动态 FrontendTree、节点约束、菜单屏幕、面包屑和隐藏屏幕回退。
validate.go 不改变状态的单 symbol 校验、建议值、当前可选值和受影响入口。
writer.go 规范化 Kconfig 和 Linux .config 写出。
test/ 公共 API、解析、加载、安全、表达式、求值、渲染、写出和并发行为测试。

开发与验证

go test ./...
go vet ./...

非目标与边界

  • 不执行 shell、Make、Python 或其他外部命令,也不会展开任意 Kconfig 宏。
  • 不提供 UI 组件、浏览器路由或导航历史;这些属于调用方,库只提供状态相关的树和安全回退。
  • 不作为原始 Kconfig 文件的格式保持工具;写出内容是规范化语义表示。
  • Schema 只描述静态目录,不能替代当前 FrontendTree 的可见性、可编辑性或动态约束。

贡献

欢迎通过 Issue 和 Pull Request 参与改进。提交前请至少执行 go test ./... 与 go vet ./...,并为行为变更补充相应覆盖。

许可证

本项目基于 Apache License 2.0 发布。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidDirective      error = errorCodeSentinel{ErrorCodeInvalidDirective}
	ErrInvalidBlock          error = errorCodeSentinel{ErrorCodeInvalidBlock}
	ErrUnsupportedDirective  error = errorCodeSentinel{ErrorCodeUnsupportedDirective}
	ErrInvalidExpression     error = errorCodeSentinel{ErrorCodeInvalidExpression}
	ErrInvalidRange          error = errorCodeSentinel{ErrorCodeInvalidRange}
	ErrDefaultTypeMismatch   error = errorCodeSentinel{ErrorCodeDefaultTypeMismatch}
	ErrInvalidValue          error = errorCodeSentinel{ErrorCodeInvalidValue}
	ErrInvalidJSONValue      error = errorCodeSentinel{ErrorCodeInvalidJSONValue}
	ErrUnknownValueType      error = errorCodeSentinel{ErrorCodeUnknownValueType}
	ErrRootPath              error = errorCodeSentinel{ErrorCodeRootPath}
	ErrIncludeEscape         error = errorCodeSentinel{ErrorCodeIncludeEscape}
	ErrIncludeCycle          error = errorCodeSentinel{ErrorCodeIncludeCycle}
	ErrSourceRead            error = errorCodeSentinel{ErrorCodeSourceRead}
	ErrUnresolvedVariable    error = errorCodeSentinel{ErrorCodeUnresolvedVariable}
	ErrShellMacro            error = errorCodeSentinel{ErrorCodeShellMacro}
	ErrUnsupportedMacro      error = errorCodeSentinel{ErrorCodeUnsupportedMacro}
	ErrIncompatibleSymbol    error = errorCodeSentinel{ErrorCodeIncompatibleSymbol}
	ErrUndeclaredSymbol      error = errorCodeSentinel{ErrorCodeUndeclaredSymbol}
	ErrUninitializedProject  error = errorCodeSentinel{ErrorCodeUninitializedProject}
	ErrUnknownSymbol         error = errorCodeSentinel{ErrorCodeUnknownSymbol}
	ErrResolutionConvergence error = errorCodeSentinel{ErrorCodeResolutionConvergence}
	ErrInvalidState          error = errorCodeSentinel{ErrorCodeInvalidState}
	ErrMissingRootDocument   error = errorCodeSentinel{ErrorCodeMissingRootDocument}
)

The Err variables are stable error identities for errors.Is. Their matching ErrorCode is exposed on Error and Diagnostic for callers that serialize, switch on, or display the library's error taxonomy.

Functions

func Load

func Load(ctx context.Context, entry string, options LoadOptions) (*Project, Diagnostics, error)

Load reads entry and its included documents, validates their structure, and builds an immutable Project.

func ParseDocument

func ParseDocument(source Source) (*Document, Diagnostics)

ParseDocument parses one Kconfig source document.

func ParseExpr

func ParseExpr(text string, span SourceSpan) (Expr, Diagnostics)

ParseExpr parses an expression with Kconfig operator precedence.

func ParseValue

func ParseValue(kind ValueType, raw string) (Value, Diagnostic)

ParseValue parses one Kconfig literal as the requested type.

func WriteConfig

func WriteConfig(state ConfigState) (string, error)

WriteConfig emits a deterministic Linux .config file. Disabled bool and tristate symbols use Linux's conventional unset spelling.

func WriteKconfig

func WriteKconfig(project *Project) (string, error)

WriteKconfig emits normalized definitions. It intentionally does not keep original whitespace or comments positioning; Project is semantic model data.

Types

type Change

type Change struct {
	// Input is the unnormalized frontend scalar supplied by the caller.
	Input any
	// Status records whether resolution accepted, normalized, fell back from, or ignored Input.
	Status ChangeStatus
	// Previous is the initial scalar and Value is the resolved final scalar.
	Previous, Value Value
	// Reason explains fallback or ignored input when applicable.
	Reason *StateReason
}

Change records the outcome of one submitted or normalized symbol value.

type ChangeStatus

type ChangeStatus uint8

ChangeStatus reports how a submitted frontend value was handled during resolution.

const (
	// ChangeAccepted means the direct frontend scalar remained valid.
	ChangeAccepted ChangeStatus = iota
	// ChangeNormalized means resolution supplied the final value without direct input.
	ChangeNormalized
	// ChangeFallback means direct input was replaced by an active default or constraint result.
	ChangeFallback
	// ChangeIgnored means the input referred to an unknown symbol.
	ChangeIgnored
)

type ConditionalValue

type ConditionalValue struct {
	// Value holds a literal default in the declared symbol type.
	Value Value
	// Expr is used for symbol-valued defaults (for example, `default FOO`).
	// Value is retained for literal defaults so callers do not need to reparse
	// source text to render a default.
	Expr Expr
	// Raw preserves the normalized source spelling for canonical writing.
	Raw string
	// Condition controls whether this default can apply; nil means unconditional.
	Condition Expr
	// Span locates the default in its source document.
	Span SourceSpan
}

ConditionalValue is a default value whose application may depend on an expression.

type ConfigState

type ConfigState struct {
	// contains filtered or unexported fields
}

ConfigState is an immutable-by-convention resolved value set tied to one Project.

func (ConfigState) Value

func (s ConfigState) Value(symbolID string) Value

Value returns the current symbol value, or the declared zero value when the symbol is known but unset.

func (ConfigState) Values

func (s ConfigState) Values() map[string]Value

Values returns a copy of the resolved symbol map so callers cannot mutate ConfigState internals.

type Constraints

type Constraints struct {
	// Type controls the frontend scalar type and validation rules.
	Type ValueType
	// Min and Max are active inclusive bounds when the symbol has a range.
	Min, Max *Value
	// AllowedValues enumerates toggles, tristates, or choice members where applicable.
	AllowedValues []ValueOption
}

Constraints describes the current type, range, and selectable values of a node.

type Diagnostic

type Diagnostic struct {
	// Severity classifies the impact of the diagnostic.
	Severity Severity
	// Code is the stable machine-readable category. Use errors.Is with the
	// matching Err variable when callers prefer Go's error matching protocol.
	Code ErrorCode
	// Message is a human-readable explanation that does not include source position.
	Message string
	// Span identifies the relevant source location when one is available.
	Span SourceSpan
	// Cause preserves an external underlying error, such as a SourceLoader read error.
	Cause error
}

Diagnostic explains a load, semantic, or input issue.

func (Diagnostic) Error added in v1.1.0

func (d Diagnostic) Error() string

Error returns the diagnostic message for APIs that accept an individual error.

func (Diagnostic) Is added in v1.1.0

func (d Diagnostic) Is(target error) bool

Is reports whether target is the sentinel belonging to this diagnostic's Code.

func (Diagnostic) Unwrap added in v1.1.0

func (d Diagnostic) Unwrap() error

Unwrap returns the underlying external cause, when one exists.

type Diagnostics

type Diagnostics []Diagnostic

Diagnostics is an ordered collection of diagnostics.

func (Diagnostics) Error

func (d Diagnostics) Error() string

Error renders all diagnostics for use with error-returning APIs.

func (Diagnostics) HasErrors

func (d Diagnostics) HasErrors() bool

HasErrors reports whether any error-level diagnostic is present.

type Document

type Document struct {
	// Title is the optional mainmenu title declared by the document.
	Title string
	// Root is the synthetic entry that owns the document's top-level entries.
	Root *Entry
}

Document is one parsed Kconfig source file.

type Entry

type Entry struct {
	// ID is a stable, source-derived identity assigned during indexing.
	ID string
	// Kind determines which Kconfig construct this entry represents.
	Kind EntryKind
	// Name is the symbol name or include path, depending on Kind.
	Name string
	// IncludeKind preserves source/rsource/osource/orsource for include entries.
	IncludeKind string
	// Prompt is the human-readable text shown for this entry.
	Prompt string
	// PromptCondition controls whether Prompt is active.
	PromptCondition Expr
	// Type is the declared value type for configuration entries.
	Type ValueType
	// Condition is the expression attached to an if entry.
	Condition Expr
	// Selects and Implies define relationships initiated by this entry.
	Selects []Relation
	Implies []Relation
	// Defaults and Ranges retain rules in source order.
	Defaults []ConditionalValue
	Ranges   []RangeRule
	// Depends affects configuration semantics, while Visible affects presentation only.
	Depends []Expr
	Visible []Expr
	// Help is the normalized multi-line help body for this entry.
	Help string
	// OptionModules marks the symbol that controls tristate module availability.
	OptionModules bool
	// Optional permits a choice to have no selected member.
	Optional bool
	// Properties preserves source property order for canonical writing.  The
	// semantic fields above remain the efficient, typed representation.
	Properties []Property
	// Children are nested source entries in their original order.
	Children []*Entry
	// Span identifies the entry declaration in its source document.
	Span SourceSpan
}

Entry is a source-ordered menu-tree node.

type EntryKind

type EntryKind uint8

EntryKind identifies a Kconfig menu-tree entry.

const (
	// EntryRoot is the synthetic document root and is never rendered directly.
	EntryRoot EntryKind = iota
	// EntryConfig declares a regular configuration symbol.
	EntryConfig
	// EntryMenuConfig declares a configuration symbol that also opens a screen.
	EntryMenuConfig
	// EntryMenu groups nested entries into a navigable screen.
	EntryMenu
	// EntryChoice restricts nested configuration symbols to one selected member.
	EntryChoice
	// EntryIf conditionally scopes its nested entries.
	EntryIf
	// EntryComment provides non-interactive display text.
	EntryComment
	// EntryInclude points to another source document loaded into this tree.
	EntryInclude
)

type EntrySchema

type EntrySchema struct {
	// ID is a stable declaration/menu-entry identity, not a submitted-value key.
	ID string
	// SymbolID is the submitted-value key for configuration entries and empty otherwise.
	SymbolID string
	// ParentID is the static parent screen ID.
	ParentID string
	// Prompt is the source prompt visible to users when its conditions allow it.
	Prompt string
	// Kind identifies the Kconfig construct represented by this entry.
	Kind EntryKind
	// Type is the declared value type for configuration entries.
	Type ValueType
	// Source locates the declaration in its source document.
	Source SourceSpan
	// ScreenID is the child screen opened by this menu or menuconfig entry, if any.
	ScreenID string
}

EntrySchema describes one source declaration in the static menu tree.

type Error added in v1.1.0

type Error struct {
	Code    ErrorCode
	Message string
	Cause   error
}

Error is a detailed library error with a stable Code and optional external Cause. Use errors.Is with the matching Err variable and errors.As to inspect an underlying filesystem, JSON, or caller-supplied error.

func (*Error) Error added in v1.1.0

func (e *Error) Error() string

func (*Error) Is added in v1.1.0

func (e *Error) Is(target error) bool

Is reports whether target is the sentinel belonging to this error's Code.

func (*Error) Unwrap added in v1.1.0

func (e *Error) Unwrap() error

Unwrap returns the underlying external failure, when one exists.

type ErrorCode added in v1.1.0

type ErrorCode string

ErrorCode is a stable, machine-readable category for a library failure. It identifies the reason and subsystem without replacing Error or Diagnostic messages, which retain the operation-specific detail intended for people.

const (
	// ErrorCodeInvalidDirective identifies a malformed Kconfig directive or argument.
	ErrorCodeInvalidDirective ErrorCode = "invalid-directive"
	// ErrorCodeInvalidBlock identifies an invalid, mismatched, or unclosed Kconfig block.
	ErrorCodeInvalidBlock ErrorCode = "invalid-block"
	// ErrorCodeUnsupportedDirective identifies an unsupported Kconfig directive.
	ErrorCodeUnsupportedDirective ErrorCode = "unsupported-directive"
	// ErrorCodeInvalidExpression identifies malformed expression syntax, tokens, or literals.
	ErrorCodeInvalidExpression ErrorCode = "invalid-expression"
	// ErrorCodeInvalidRange identifies a malformed or invalid Kconfig range.
	ErrorCodeInvalidRange ErrorCode = "invalid-range"
	// ErrorCodeDefaultTypeMismatch identifies a default whose type conflicts with its symbol.
	ErrorCodeDefaultTypeMismatch ErrorCode = "default-type-mismatch"
	// ErrorCodeInvalidValue identifies an invalid typed Kconfig scalar.
	ErrorCodeInvalidValue ErrorCode = "invalid-value"
	// ErrorCodeInvalidJSONValue identifies malformed or type-incompatible Value JSON.
	ErrorCodeInvalidJSONValue ErrorCode = "invalid-json-value"
	// ErrorCodeUnknownValueType identifies an unsupported ValueType.
	ErrorCodeUnknownValueType ErrorCode = "unknown-value-type"
	// ErrorCodeRootPath identifies failure to resolve the configured project root.
	ErrorCodeRootPath ErrorCode = "root-path"
	// ErrorCodeIncludeEscape identifies an include path that escapes the project root.
	ErrorCodeIncludeEscape ErrorCode = "include-escape"
	// ErrorCodeIncludeCycle identifies a cycle in source includes.
	ErrorCodeIncludeCycle ErrorCode = "include-cycle"
	// ErrorCodeSourceRead identifies a non-optional SourceLoader read failure.
	ErrorCodeSourceRead ErrorCode = "source-read"
	// ErrorCodeUnresolvedVariable identifies a missing caller-supplied variable.
	ErrorCodeUnresolvedVariable ErrorCode = "unresolved-variable"
	// ErrorCodeShellMacro identifies a forbidden shell macro expansion.
	ErrorCodeShellMacro ErrorCode = "shell-macro"
	// ErrorCodeUnsupportedMacro identifies an unsupported Kconfig macro expansion.
	ErrorCodeUnsupportedMacro ErrorCode = "unsupported-macro"
	// ErrorCodeIncompatibleSymbol identifies conflicting declared symbol types.
	ErrorCodeIncompatibleSymbol ErrorCode = "incompatible-symbol"
	// ErrorCodeUndeclaredSymbol identifies a symbol referenced without declaration.
	ErrorCodeUndeclaredSymbol ErrorCode = "undeclared-symbol"
	// ErrorCodeUninitializedProject identifies an operation on an uninitialized Project.
	ErrorCodeUninitializedProject ErrorCode = "uninitialized-project"
	// ErrorCodeUnknownSymbol identifies a submitted symbol absent from the project.
	ErrorCodeUnknownSymbol ErrorCode = "unknown-symbol"
	// ErrorCodeResolutionConvergence identifies resolution that cannot reach a fixed point.
	ErrorCodeResolutionConvergence ErrorCode = "resolution-convergence"
	// ErrorCodeInvalidState identifies a ConfigState unsuitable for an operation.
	ErrorCodeInvalidState ErrorCode = "invalid-state"
	// ErrorCodeMissingRootDocument identifies a Project without a root document.
	ErrorCodeMissingRootDocument ErrorCode = "missing-root-document"
)

type Expr

type Expr interface {
	// contains filtered or unexported methods
}

Expr is a parsed Kconfig conditional expression.

type FSLoader

type FSLoader struct{}

FSLoader is the default SourceLoader implementation backed by the host filesystem.

func (FSLoader) Read

func (FSLoader) Read(_ context.Context, path string) (Source, error)

Read loads path from the host filesystem and retains the requested path for diagnostics.

type FrontendInput

type FrontendInput struct {
	// Values maps declared symbol IDs to proposed frontend scalar values.
	Values map[string]any
}

FrontendInput contains raw frontend scalars keyed by SymbolID. Resolve and Apply choose the target type from the loaded Kconfig symbol and normalize these forms internally: bool -> bool, tristate -> "n"/"m"/"y", string -> string, int -> an integral number, and hex -> a "0x..." string.

type FrontendTree

type FrontendTree struct {
	// Title is the project title used by the root screen.
	Title string
	// RootScreenID is the stable ID of the always-present root screen.
	RootScreenID string
	// Screens are rendered in static parent-before-child order.
	Screens []Screen
	// Diagnostics carries loading or rendering diagnostics relevant to this projection.
	Diagnostics Diagnostics
}

FrontendTree is the complete dynamic projection of a Project for one ConfigState.

type LoadOptions

type LoadOptions struct {
	// Root confines entry and include paths when the default filesystem loader is used.
	Root string
	// Loader optionally replaces filesystem reads with an application-provided source store.
	Loader SourceLoader
	// Variables supplies the only allowed $(NAME) and ${NAME} macro substitutions.
	Variables map[string]string
}

type Node

type Node struct {
	// ID is the stable declaration entry ID; SymbolID is the submitted-value key when applicable.
	ID, SymbolID string
	// SelectedSymbolID identifies the active choice member for choice nodes.
	SelectedSymbolID string
	// Kind determines how a frontend presents this node.
	Kind NodeKind
	// Prompt and Help are source-authored display text.
	Prompt, Help string
	// Visible controls display, while Enabled controls whether frontend edits are accepted.
	Visible, Enabled bool
	// Value is resolved state and Default is the active Kconfig default.
	Value, Default Value
	// Constraints describes valid user input at this state.
	Constraints Constraints
	// Reason explains hidden or disabled state when applicable.
	Reason *StateReason
	// Screen references the enterable child screen opened by this node, when any.
	Screen *ScreenRef
	// Source locates the original declaration.
	Source SourceSpan
}

Node is a rendered entry with its current value, visibility, and interaction constraints.

type NodeKind

type NodeKind uint8

NodeKind identifies a rendered frontend entry.

const (
	// NodeConfig renders an ordinary configuration symbol.
	NodeConfig NodeKind = iota
	// NodeMenuConfig renders a configuration symbol that may open a child screen.
	NodeMenuConfig
	// NodeMenu renders a non-value menu entry that opens a child screen.
	NodeMenu
	// NodeChoice renders a group whose member symbols are the submitted values.
	NodeChoice
	// NodeComment renders non-interactive explanatory text.
	NodeComment
)

type Project

type Project struct {
	// contains filtered or unexported fields
}

Project is an immutable, indexed Kconfig document tree ready for resolution and rendering.

func (*Project) Apply

func (p *Project) Apply(state ConfigState, patch FrontendInput) Resolution

Apply preserves valid prior user input from state, overlays patch, and resolves the complete next state.

func (*Project) OpenScreen

func (p *Project) OpenScreen(state ConfigState, id string, options RenderOptions) ScreenResult

OpenScreen returns a visible, enterable screen, falling back to an ancestor or root when id is stale or hidden.

func (*Project) Render

func (p *Project) Render(state ConfigState, options RenderOptions) FrontendTree

Render projects state into frontend screens without changing the state or Project.

func (*Project) Resolve

func (p *Project) Resolve(input FrontendInput) Resolution

Resolve applies raw frontend input to fresh defaults and converges Kconfig dependencies, relations, and choices.

func (*Project) Schema

func (p *Project) Schema() Schema

Schema returns the full static catalog, including entries hidden by current conditions.

func (*Project) Validate

func (p *Project) Validate(state ConfigState, symbolID string, candidate any) ValidationResult

Validate checks a raw frontend scalar without mutating state. Its accepted scalar forms are the same as FrontendInput.Values.

type Property

type Property struct {
	// Kind is the canonical Kconfig property keyword.
	Kind string
	// Text is the normalized property body without the keyword.
	Text string
	// Span locates the property in its source document.
	Span SourceSpan
}

Property records one source property in declaration order. It intentionally keeps only normalized text: writers are canonical rather than format-preserving.

type RangeRule

type RangeRule struct {
	// Min and Max are inclusive bounds expressed in the symbol's declared type.
	Min Value
	Max Value
	// Condition controls whether this range is active; nil means unconditional.
	Condition Expr
	// Span locates the range declaration in its source document.
	Span SourceSpan
}

RangeRule limits an integer or hexadecimal symbol while Condition is active.

type Relation

type Relation struct {
	// Target is the symbol name changed by this relation.
	Target string
	// Condition controls when the relation is active; nil means unconditional.
	Condition Expr
	// Span locates the relation in its source document.
	Span SourceSpan
}

Relation is a conditional select or imply target.

type RenderOptions

type RenderOptions struct {
	// IncludeHidden retains nodes and screens whose visibility conditions are false.
	IncludeHidden bool
}

RenderOptions controls which presentation-only entries Render returns.

type Resolution

type Resolution struct {
	// State is the fully resolved immutable-by-convention configuration state.
	State ConfigState
	// Tree is the complete dynamic frontend projection for State.
	Tree FrontendTree
	// Changes is keyed by symbol ID and describes every submitted or normalized value.
	Changes map[string]Change
	// Diagnostics collects malformed input and resolution diagnostics.
	Diagnostics Diagnostics
}

Resolution combines the resolved state, dynamic tree, per-symbol outcomes, and diagnostics.

type Schema

type Schema struct {
	// Title is the project title declared with mainmenu, or the default title.
	Title string
	// Symbols lists each declared configuration symbol and every declaration site.
	Symbols []SymbolSchema
	// Entries lists static menu-tree entries, independent of runtime visibility.
	Entries []EntrySchema
	// Screens lists navigable menu and menuconfig screens in parent-before-child order.
	Screens []ScreenSchema
}

Schema is a static, cacheable catalog. Visibility and constraints belong to FrontendTree and are deliberately absent here.

type Screen

type Screen struct {
	// ID, ParentID, and OwnerID form the navigation hierarchy.
	ID, ParentID, OwnerID string
	// Title is the display label for this screen.
	Title string
	// Breadcrumb lists the visible root-to-screen navigation path.
	Breadcrumb []ScreenRef
	// Visible reports presentation visibility; Enterable reports whether navigation is allowed.
	Visible, Enterable bool
	// Entries contains this screen's rendered nodes in source order.
	Entries []Node
}

Screen groups visible nodes that a frontend can navigate to.

type ScreenRef

type ScreenRef struct{ ID, Title string }

ScreenRef identifies a screen without embedding its entries.

type ScreenResult

type ScreenResult struct {
	// Screen is the visible screen ultimately selected for the request.
	Screen Screen
	// ActiveScreenID repeats Screen.ID as a convenient navigation result.
	ActiveScreenID string
	// Redirected reports that the requested ID was stale or hidden.
	Redirected bool
	// Reason explains the redirect or project error, when applicable.
	Reason *StateReason
	// Tree is the complete projection used to find the selected screen.
	Tree FrontendTree
}

ScreenResult combines a rendered tree with the screen selected after fallback.

type ScreenSchema

type ScreenSchema struct {
	// ID is the stable screen identity used by rendering and navigation.
	ID string
	// ParentID identifies the containing screen, or is empty for the root screen.
	ParentID string
	// OwnerID identifies the entry that opens this screen, or is empty for root.
	OwnerID string
	// Title is the screen label derived from its owning entry.
	Title string
	// Source locates the owning source entry when the screen is not root.
	Source SourceSpan
}

ScreenSchema describes a static navigable screen and its ownership relation.

type Severity

type Severity uint8

Severity describes how a diagnostic affects loading or resolution.

const (
	// SeverityInfo reports supplemental information that does not affect processing.
	SeverityInfo Severity = iota
	// SeverityWarning reports recoverable input or semantic conditions.
	SeverityWarning
	// SeverityError reports a condition that prevents reliable project use.
	SeverityError
)

type Source

type Source struct {
	// Path identifies the source for diagnostics and include resolution.
	Path string
	// Data contains the complete UTF-8 Kconfig document.
	Data []byte
}

Source is Kconfig text returned by a SourceLoader or supplied directly.

type SourceLoader

type SourceLoader interface {
	Read(context.Context, string) (Source, error)
}

SourceLoader permits applications to provide Kconfig files from an embedded filesystem or another trusted store. The loader receives a cleaned path rooted under LoadOptions.Root; it is never asked to expand Kconfig macros.

type SourceSpan

type SourceSpan struct {
	// Path is the document path supplied by the loader.
	Path string
	// Line and Column are one-based start coordinates.
	Line   int
	Column int
	// EndLine and EndColumn are optional one-based exclusive end coordinates.
	EndLine   int
	EndColumn int
}

SourceSpan identifies a position in a Kconfig source file.

type StateReason

type StateReason struct {
	// Code is a stable machine-readable reason category.
	Code string
	// Message is a user-facing explanation for the current state.
	Message string
	// Source identifies the related declaration when available.
	Source SourceSpan
}

StateReason explains why a value, node, or screen is unavailable or redirected.

type SymbolLookup

type SymbolLookup func(name string) Value

SymbolLookup obtains the current value of a named symbol.

type SymbolSchema

type SymbolSchema struct {
	// ID is the submitted-value key used by FrontendInput.Values.
	ID string
	// Type controls the scalar form accepted for the symbol.
	Type ValueType
	// Source is the first declaration location for the symbol.
	Source SourceSpan
	// EntryIDs identifies every static declaration entry for the symbol.
	EntryIDs []string
}

SymbolSchema describes one logical symbol that may have several declarations.

type Token

type Token struct {
	// Kind identifies the token category.
	Kind TokenKind
	// Text is the original token spelling.
	Text string
	// Span identifies the token's source position.
	Span SourceSpan
}

Token is a source-positioned expression token.

type TokenKind

type TokenKind uint8

TokenKind identifies a lexical unit in a Kconfig expression.

const (
	// TokenEOF marks the end of an expression token stream.
	TokenEOF TokenKind = iota
	// TokenIdent is a symbol name or tristate literal spelling.
	TokenIdent
	// TokenString is a quoted Kconfig string literal.
	TokenString
	// TokenNumber is a decimal or hexadecimal numeric literal.
	TokenNumber
	// TokenNot is the unary ! operator.
	TokenNot
	// TokenAnd is the && logical operator.
	TokenAnd
	// TokenOr is the || logical operator.
	TokenOr
	// TokenEqual is the = comparison operator.
	TokenEqual
	// TokenNotEqual is the != comparison operator.
	TokenNotEqual
	// TokenLess is the < comparison operator.
	TokenLess
	// TokenLessEqual is the <= comparison operator.
	TokenLessEqual
	// TokenGreater is the > comparison operator.
	TokenGreater
	// TokenGreaterEqual is the >= comparison operator.
	TokenGreaterEqual
	// TokenLParen is an opening parenthesis.
	TokenLParen
	// TokenRParen is a closing parenthesis.
	TokenRParen
)

type TriState

type TriState uint8

TriState is the Kconfig n < m < y lattice value.

const (
	// TriNo is the disabled n state.
	TriNo TriState = iota
	// TriModule is the modular m state.
	TriModule
	// TriYes is the enabled y state.
	TriYes
)

func EvalExpr

func EvalExpr(expr Expr, lookup SymbolLookup) TriState

EvalExpr evaluates a parsed expression using Kconfig tristate logic.

func (TriState) String

func (t TriState) String() string

String returns the Kconfig spelling of a tristate value.

type ValidationResult

type ValidationResult struct {
	// Accepted reports whether candidate is immediately valid in state.
	Accepted bool
	// Normalized is candidate when accepted, otherwise the suggested active default.
	Normalized Value
	// AllowedValues contains current toggles, tristates, or choice members.
	AllowedValues []ValueOption
	// Reason explains rejection without requiring state mutation.
	Reason *StateReason
	// Diagnostics provides parsing warnings for malformed frontend scalar forms.
	Diagnostics Diagnostics
	// AffectedEntryIDs identifies static declarations that a frontend may refresh.
	AffectedEntryIDs []string
}

ValidationResult reports whether a proposed raw scalar is accepted and how a caller should recover when it is not.

type Value

type Value struct {
	// Type selects which of Tri, Text, or Int is meaningful.
	Type ValueType
	// Tri stores bool and tristate values.
	Tri TriState
	// Text stores string values without Kconfig quote syntax.
	Text string
	// Int stores decimal and hexadecimal integer values.
	Int int64
}

Value is a typed Kconfig value. Only the field matching Type is meaningful.

func BoolValue

func BoolValue(value bool) Value

BoolValue creates a bool Value from a Go boolean.

func HexValue

func HexValue(value int64) Value

HexValue creates a hexadecimal integer Value.

func IntValue

func IntValue(value int64) Value

IntValue creates a decimal integer Value.

func StringValue

func StringValue(value string) Value

StringValue creates a string Value without adding Kconfig quote syntax.

func TriValue

func TriValue(value TriState) Value

TriValue creates a tristate Value from a Kconfig lattice value.

func ZeroValue

func ZeroValue(kind ValueType) Value

ZeroValue returns the inactive value for a declared Kconfig type.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON writes the frontend scalar form of a typed Kconfig value. A caller obtains the value type from Schema or Node.Constraints rather than having to decode the Value struct's implementation fields.

func (Value) String

func (v Value) String() string

String returns the canonical Kconfig literal for the value.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts the scalar form emitted by MarshalJSON. When the receiver already carries a type (for example, ZeroValue(schema.Type)), JSON types are checked strictly. An untyped receiver infers only unambiguous scalar forms; callers with a string/tristate or int/hex ambiguity should initialize the receiver from schema metadata first.

type ValueOption

type ValueOption struct {
	// Value is the scalar choice value; for choices it is the member's resolved value.
	Value Value
	// SymbolID identifies a choice member when this option represents one.
	SymbolID string
	// Prompt is the human-readable label for the option or choice member.
	Prompt string
	// Selected reports whether the option is active in the current state.
	Selected bool
	// Enabled reports whether the frontend may submit this option.
	Enabled bool
	// Reason explains why an unavailable option is disabled.
	Reason *StateReason
}

ValueOption describes a value or choice member available to the frontend.

type ValueOrigin

type ValueOrigin uint8

ValueOrigin records why a resolved value was chosen.

const (
	// OriginZero marks the initial inactive value before resolution.
	OriginZero ValueOrigin = iota
	// OriginDefault marks a value selected by an active default rule.
	OriginDefault
	// OriginInput marks a value provided directly by the frontend.
	OriginInput
	// OriginRelation marks a value raised by select or imply.
	OriginRelation
	// OriginChoice marks a value selected or cleared to satisfy a choice.
	OriginChoice
)

type ValueType

type ValueType uint8

ValueType is the declared type of a Kconfig symbol.

const (
	// TypeUnknown marks an unset or invalid type.
	TypeUnknown ValueType = iota
	// TypeBool accepts only n or y.
	TypeBool
	// TypeTristate accepts n, m, or y.
	TypeTristate
	// TypeString stores quoted Kconfig string values.
	TypeString
	// TypeInt stores signed decimal integers.
	TypeInt
	// TypeHex stores non-negative hexadecimal integers.
	TypeHex
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL