KCL Language Documentation
repository·main·Indexed 25 days ago
https://github.com/kcl-lang/kclKCL is a constraint-based record and functional language optimized for managing complex, large-scale configurations in cloud-native environments. It provides a type-safe, modular way to generate, validate, and automate configuration data such as JSON and YAML. The project includes a Rust SDK (kcl_api) for executing KCL programs, a JSON-RPC server for remote interaction, and FFI capabilities via call_native.
What's inside KCL
- KCL is an open-source, constraint-based record and functional language designed to enhance the writing of complex configurations, particularly for cloud-native scenarios. It promotes modularity, scalability, and stability in configurations by providing advanced programming language technology. KCL is used to simplify logic writing, provide automation APIs, and integrate with existing systems.
Overview of KCL: Constraint-based Record & Functional Language
mainKCL is an open-source, constraint-based record and functional language designed to improve the management of complex configurations, such as cloud-native Kubernetes configurations. It focuses on modularity, extensibility, and stability, providing a way to write logic for configuration that is easy to automate and integrate with ecosystem tools.
Key capabilities include:
- Generating static configuration data: Exporting to formats like JSON and YAML.
- Schema-based modeling: Using Schemas to abstract configuration data and reduce boilerplate.
- Constraint-based validation: Defining rules within Schemas to automatically validate data.
- Configuration management: Organizing and simplifying large-scale configurations via GitOps and automation.
- Kubernetes integration: Directly editing or validating existing Kubernetes resources using cloud-native tools.
Key features of KCL
mainKCL provides a robust set of features for configuration engineering:
- Language Design: Easy-to-use syntax inspired by Python and Golang, featuring a spec-driven design with independent syntax, semantics, runtime, and system modules.
- Modeling & Types: Quick modeling via out-of-the-box modules, Schema-centric configuration types, and support for Config, Schema, Lambda, and Rule.
- Stability & Safety: Achieved through a static type system, constraints, and rules. It is domain-oriented and lacks system-level functions (like native threads or IO) to reduce security risks.
- Scalability & Performance: High scalability via an automatic merge mechanism for isolated config blocks. High performance is achieved using Rust & C, with support for native code compilation and WASM.
- Automation & API: Supports CRUD APIs, multilingual SDKs (Rust, Go, Python, .NET, Java, Node.js), and language plugins.
- Ecosystem & Tooling: Native support for OpenAPI and Kubernetes (CRD, KRM). Includes language tools (Format, Lint, Test, Vet, Doc, package management) and multiple IDE extensions.
- Integrations: Compatible with
kubectl(KCL Plugin),Kustomize(KCL Plugin),Helm(KCL Plugin),KPT(KCL SDK), andCrossplane(KCL Function).
KCL Language Support: IDE, LSP, and SDKs
mainKCL provides several tools to integrate the language into development workflows:
- IDE Extension & Language Server: KCL uses the Language Server Protocol (LSP) to provide IDE capabilities such as code completion, error detection, and hover information.
- Language Tools: Utilities for syntax highlighting, linting, formatting, and refactoring.
- APIs and SDKs: KCL offers APIs and SDKs for multiple programming languages, enabling integration with various technology stacks.
Navigate the KCL Developer Guide
mainThe KCL Developer Guide is structured into four main parts to assist with different stages of development and contribution:
- Building and Testing
KCL: Information on building, testing, debugging, and profiling the compiler. - Contributing to
KCL: Procedures for contributing, including git and GitHub workflows. KCLArchitecture: An introduction to the compiler architecture and detailed explanations of each compilation process.- Appendices: Supplemental information, including a glossary.
For a high-level overview of how to get started, refer to the Quick Start guide.
- Building and Testing
Understand the KCL workspace structure
mainThe
kcl-lang/kclrepository is organized as a single large Cargo workspace. When working with the source code, you will primarily interact with these three main directories:crates: Contains the source code for the KCL core, composed of many individual crates that form the compiler.compiler_base: Contains basic libraries for compilers that are dependent on thekclcore.scripts: Contains source code and image build scripts.tests: Contains the compiler grammar integration tests.
How the KCL Watch System works
mainThe KCL Watch System is a monitoring mechanism designed to detect changes to files and directories within a KCL package. It works by combining four core components:
- Watcher: Uses a file system notification library (like
notify) to monitor paths asynchronously. - File Type Detector: Analyzes file extensions (e.g.,
.k,.mod,.JSON,.YAML) to determine the file type. - Handler Registry: Manages specific operations (actions like creation, modification, or deletion) mapped to specific file types.
- Configuration Manager: Manages settings such as watch paths and handler configurations, typically via a
kcl.tomlfile.
When a file system event occurs, the Watcher detects it, the File Type Detector identifies the file type, and the Handler Registry executes the corresponding action defined in the configuration.
- Watcher: Uses a file system notification library (like
Key structures in the KCL Language Server
mainThe following core structures manage the state and communication of the KCL Language Server:
LanguageServerState: The central state holder. It contains:Sender: A channel to send messages to the client.- Task sender/receiver: Channels for background operation tasks.
analysis: Holds compilation results and semantic information.vfs: The Virtual File System for managing unsaved file changes.- Various caches for performance.
LanguageServerSnapshot: A snapshot of theLanguageServerStateused to handle tasks within threads.Event: The primary unit of work, divided into:- Task: Internal scheduling (e.g.,
Notificationto log info,Responseto return data to client, orRetry). - LSP Message: External communication.
LSP Notification(e.g.,didOpen,didChange) requires no response, whileLSP Request(e.g.,gotoDefinition,hover) requires a response from the server.
- Task: Internal scheduling (e.g.,
Understand the KCL Language Server workflow
mainThe KCL Language Server implements the Language Server Protocol (LSP) to provide IDE features like autocomplete, diagnostics, and jump-to-definition.
Server Lifecycle
- Initialization: The server starts via
stdioconnections, parses initialization parameters from the client, and sends its supported capabilities (e.g., highlighting, completion, hover). - Main Loop: The server executes
main_loop(), which initializes aLanguageServerStateand callsrun(). - Event Processing:
LanguageServerStatereceivesEventsand distributes them to a thread pool. - VFS & Compilation: The server uses a Virtual File System (VFS) to track changes (create, delete, modify). It compiles files based on the current state and writes results (AST and semantic information) to a database. If compilation errors occur, the server proactively sends diagnostics to the client.
Compilation Logic (Compile Units)
Because KCL does not use a single project file (like
Cargo.toml), the server useslookup_compile_unit()to determine what to compile based on these rules:- Entry files: Always compiled.
- Configuration files: If a
kcl.yamlexists in the current directory, it is compiled according to its definition. - Package fallback: If no
kcl.yamlis found, the current directory is compiled as a package.
- Initialization: The server starts via
Explore the KCL core crates
mainThe
cratesdirectory contains the core components of the KCL compiler. Depending on your goal (e.g., building an extension, understanding the AST, or modifying the CLI), you should focus on the following crates:Interface & API
api: The interface layer for the KCL Rust core. It provides over ten important APIs (parsing, running code, toolchain APIs, etc.) used by other multi-language SDKs likekcl-go,kcl-py, andkcl-java.cmd: Houses the command-line interface tools, such as thelibkclbinary.spec: Houses code related to the KCL language specification, including language versioning, feature definitions, syntax rules, and API definitions.version: Manages compiler versioning (setting, updating, and displaying version information).
Frontend (Lexing & Parsing)
lexer: Performs lexical analysis, breaking raw KCL source into a stream of tokens.parser: Constructs the Abstract Syntax Tree (AST) from the token stream.ast: Defines the core Abstract Syntax Tree (AST), tree walkers, and token definitions.ast_pretty: Utilities for formatting and printing the AST in a human-readable format.
Middle-end (Analysis & Querying)
compiler: Contains the main compilation logic, converting high-level KCL code into an intermediate representation.sema(Semantic Analysis): Handles type checking, validation, and ensuring programs follow semantic rules.query: Manages code queries and information retrieval (e.g., finding variable definitions) within KCL programs.loader: Manages KCL modules, including discovery, parsing, and assembly from various sources.error: Defines and handles error messages, diagnostics, and compiler warnings.config: Manages configuration, including command-line argument parsing and configuration files.
Backend & Runtime (Execution)
evaluator: Contains logic for evaluating expressions and executing KCL code, including value computation and user-defined functions.runtime: Provides necessary runtime support, such as memory management, value representation, and built-in functions.runner: Manages the setup and invocation of the KCL runtime environment to execute compiled programs.
Utilities & Tooling
macros: Contains macro definitions and utilities for code generation within the compiler.tools: Additional utilities like code formatters, linters, the language server, and development scripts.utils: A collection of helper functions and common routines used across the project.
KCL Runtime Components: Values and Standard Libraries
mainAt runtime, the KCL environment operates using two primary components:
- Values: These are the runtime representations of entities defined in your KCL code. They include primitives (integers, strings) and complex data structures.
- System Standard Libraries: Pre-defined functions and resources provided by KCL that users can invoke to interact with the system and perform complex tasks.
KCL code formatting: Line length and indentation
mainWhen contributing to the KCL codebase, adhere to these formatting rules:
- Line Length: Lines should be at most 100 characters. Keeping lines closer to 80 characters is preferred.
- Indentation: Use 4-space indentation. Do not use tabs.