kconfig

package module
v1.0.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

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"
    "fmt"

    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 || diagnostics.HasErrors() {
        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;它不保存某个用户的可变配置。

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

This section is empty.

Functions

func Load

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

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           any
	Status          ChangeStatus
	Previous, Value Value
	Reason          *StateReason
}

type ChangeStatus

type ChangeStatus uint8
const (
	ChangeAccepted ChangeStatus = iota
	ChangeNormalized
	ChangeFallback
	ChangeIgnored
)

type ConditionalValue

type ConditionalValue struct {
	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       string
	Condition Expr
	Span      SourceSpan
}

type ConfigState

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

func (ConfigState) Value

func (s ConfigState) Value(symbolID string) Value

func (ConfigState) Values

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

type Constraints

type Constraints struct {
	Type          ValueType
	Min, Max      *Value
	AllowedValues []ValueOption
}

type Diagnostic

type Diagnostic struct {
	Severity Severity
	Message  string
	Span     SourceSpan
}

Diagnostic explains a load, semantic, or input issue.

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 string
	Root  *Entry
}

Document is one parsed Kconfig source file.

type Entry

type Entry struct {
	ID              string
	Kind            EntryKind
	Name            string
	IncludeKind     string
	Prompt          string
	PromptCondition Expr
	Type            ValueType
	Condition       Expr
	Selects         []Relation
	Implies         []Relation
	Defaults        []ConditionalValue
	Ranges          []RangeRule
	Depends         []Expr
	Visible         []Expr
	Help            string
	OptionModules   bool
	Optional        bool
	// Properties preserves source property order for canonical writing.  The
	// semantic fields above remain the efficient, typed representation.
	Properties []Property
	Children   []*Entry
	Span       SourceSpan
}

Entry is a source-ordered menu-tree node.

type EntryKind

type EntryKind uint8

EntryKind identifies a Kconfig menu-tree entry.

const (
	EntryRoot EntryKind = iota
	EntryConfig
	EntryMenuConfig
	EntryMenu
	EntryChoice
	EntryIf
	EntryComment
	EntryInclude
)

type EntrySchema

type EntrySchema struct {
	ID, SymbolID, ParentID, Prompt string
	Kind                           EntryKind
	Type                           ValueType
	Source                         SourceSpan
	ScreenID                       string
}

type Expr

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

Expr is a parsed Kconfig conditional expression.

type FSLoader

type FSLoader struct{}

func (FSLoader) Read

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

type FrontendInput

type FrontendInput struct{ 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        string
	RootScreenID string
	Screens      []Screen
	Diagnostics  Diagnostics
}

type LoadOptions

type LoadOptions struct {
	Root      string
	Loader    SourceLoader
	Variables map[string]string
}

type Node

type Node struct {
	ID, SymbolID     string
	SelectedSymbolID string
	Kind             NodeKind
	Prompt, Help     string
	Visible, Enabled bool
	Value, Default   Value
	Constraints      Constraints
	Reason           *StateReason
	Screen           *ScreenRef
	Source           SourceSpan
}

type NodeKind

type NodeKind uint8
const (
	NodeConfig NodeKind = iota
	NodeMenuConfig
	NodeMenu
	NodeChoice
	NodeComment
)

type Project

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

func (*Project) Apply

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

func (*Project) OpenScreen

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

func (*Project) Render

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

func (*Project) Resolve

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

func (*Project) Schema

func (p *Project) Schema() Schema

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 string
	Text string
	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       Value
	Max       Value
	Condition Expr
	Span      SourceSpan
}

type Relation

type Relation struct {
	Target    string
	Condition Expr
	Span      SourceSpan
}

Relation is a conditional select or imply target.

type RenderOptions

type RenderOptions struct{ IncludeHidden bool }

type Resolution

type Resolution struct {
	State       ConfigState
	Tree        FrontendTree
	Changes     map[string]Change
	Diagnostics Diagnostics
}

type Schema

type Schema struct {
	Title   string
	Symbols []SymbolSchema
	Entries []EntrySchema
	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, OwnerID, Title string
	Breadcrumb                   []ScreenRef
	Visible, Enterable           bool
	Entries                      []Node
}

type ScreenRef

type ScreenRef struct{ ID, Title string }

type ScreenResult

type ScreenResult struct {
	Screen         Screen
	ActiveScreenID string
	Redirected     bool
	Reason         *StateReason
	Tree           FrontendTree
}

type ScreenSchema

type ScreenSchema struct {
	ID, ParentID, OwnerID, Title string
	Source                       SourceSpan
}

type Severity

type Severity uint8

Severity describes how a diagnostic affects loading or resolution.

const (
	SeverityInfo Severity = iota
	SeverityWarning
	SeverityError
)

type Source

type Source struct {
	Path string
	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      string
	Line      int
	Column    int
	EndLine   int
	EndColumn int
}

SourceSpan identifies a position in a Kconfig source file.

type StateReason

type StateReason struct {
	Code, Message string
	Source        SourceSpan
}

type SymbolLookup

type SymbolLookup func(name string) Value

SymbolLookup obtains the current value of a named symbol.

type SymbolSchema

type SymbolSchema struct {
	ID       string
	Type     ValueType
	Source   SourceSpan
	EntryIDs []string
}

type Token

type Token struct {
	Kind TokenKind
	Text string
	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 TokenKind = iota
	TokenIdent
	TokenString
	TokenNumber
	TokenNot
	TokenAnd
	TokenOr
	TokenEqual
	TokenNotEqual
	TokenLess
	TokenLessEqual
	TokenGreater
	TokenGreaterEqual
	TokenLParen
	TokenRParen
)

type TriState

type TriState uint8

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

const (
	TriNo TriState = iota
	TriModule
	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         bool
	Normalized       Value
	AllowedValues    []ValueOption
	Reason           *StateReason
	Diagnostics      Diagnostics
	AffectedEntryIDs []string
}

type Value

type Value struct {
	Type ValueType
	Tri  TriState
	Text string
	Int  int64
}

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

func BoolValue

func BoolValue(value bool) Value

func HexValue

func HexValue(value int64) Value

func IntValue

func IntValue(value int64) Value

func StringValue

func StringValue(value string) Value

func TriValue

func TriValue(value TriState) 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             Value
	SymbolID, Prompt  string
	Selected, Enabled bool
	Reason            *StateReason
}

type ValueOrigin

type ValueOrigin uint8
const (
	OriginZero ValueOrigin = iota
	OriginDefault
	OriginInput
	OriginRelation
	OriginChoice
)

type ValueType

type ValueType uint8

ValueType is the declared type of a Kconfig symbol.

const (
	TypeUnknown ValueType = iota
	TypeBool
	TypeTristate
	TypeString
	TypeInt
	TypeHex
)

Jump to

Keyboard shortcuts

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